source
stringlengths
3
92
c
stringlengths
26
2.25M
luks_fmt_plug.c
/* luks.c * * hashkill - a hash cracking tool * Copyright (C) 2010 Milen Rangelov <gat3way@gat3way.eu> * * This software is Copyright (c) 2013 Dhiru Kholia <dhiru at openwall.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_luks; #elif FMT_REGISTERS_H john_register_one(&fmt_luks); #else #if AC_BUILT #include "autoconfig.h" #else #define _LARGEFILE64_SOURCE 1 #endif #include "jumbo.h" // large file support #include "os.h" #include <stdio.h> #include <string.h> #include <assert.h> #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <sys/types.h> #include "aes.h" #include "sha.h" #include "sha2.h" #include <string.h> #include "arch.h" #include "johnswap.h" #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "options.h" #include "memory.h" #include "base64.h" #include "pbkdf2_hmac_sha1.h" #include "dyna_salt.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 #endif #endif #include "memdbg.h" #define LUKS_MAGIC_L 6 #define LUKS_CIPHERNAME_L 32 #define LUKS_CIPHERMODE_L 32 #define LUKS_HASHSPEC_L 32 #define UUID_STRING_L 40 #define LUKS_DIGESTSIZE 20 #define LUKS_SALTSIZE 32 #define LUKS_NUMKEYS 8 #define FORMAT_LABEL "LUKS" #define FORMAT_NAME "" #define FORMAT_TAG "$luks$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #endif #define BENCHMARK_COMMENT "" #define PLAINTEXT_LENGTH 125 #define BENCHMARK_LENGTH -1 #define BINARY_SIZE LUKS_DIGESTSIZE #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt_LUKS*) #define SALT_ALIGN sizeof(struct custom_salt_LUKS*) #if SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #if ARCH_LITTLE_ENDIAN #define john_htonl(x) ((((x)>>24) & 0xffL) | (((x)>>8) & 0xff00L) | \ (((x)<<8) & 0xff0000L) | (((x)<<24) & 0xff000000L)) #define john_ntohl(x) ((((x)>>24) & 0xffL) | (((x)>>8) & 0xff00L) | \ (((x)<<8) & 0xff0000L) | (((x)<<24) & 0xff000000L)) #else #define john_htonl(x) (x) #define john_ntohl(x) (x) #endif #include "luks_insane_tests.h" /* taken from LUKS on disk format specification */ struct luks_phdr { char magic[LUKS_MAGIC_L]; uint16_t version; char cipherName[LUKS_CIPHERNAME_L]; char cipherMode[LUKS_CIPHERMODE_L]; char hashSpec[LUKS_HASHSPEC_L]; uint32_t payloadOffset; uint32_t keyBytes; char mkDigest[LUKS_DIGESTSIZE]; char mkDigestSalt[LUKS_SALTSIZE]; uint32_t mkDigestIterations; char uuid[UUID_STRING_L]; struct { uint32_t active; uint32_t passwordIterations; char passwordSalt[LUKS_SALTSIZE]; uint32_t keyMaterialOffset; uint32_t stripes; } keyblock[LUKS_NUMKEYS]; }; static struct custom_salt_LUKS { dyna_salt dsalt; char path[8192]; int loaded; struct luks_phdr myphdr; int afsize; int bestslot; int bestiter; unsigned char cipherbuf[1]; } *cur_salt; static void XORblock(char *src1, char *src2, char *dst, int n) { int j; for (j = 0; j < n; j++) dst[j] = src1[j] ^ src2[j]; } static int diffuse(unsigned char *src, unsigned char *dst, int size) { uint32_t i; uint32_t IV; /* host byte order independent hash IV */ SHA_CTX ctx; int fullblocks = (size) / 20; int padding = size % 20; for (i = 0; i < fullblocks; i++) { IV = john_htonl(i); SHA1_Init(&ctx); SHA1_Update(&ctx, &IV, 4); SHA1_Update(&ctx, src + 20 * i, 20); SHA1_Final(dst + 20 * i, &ctx); } if (padding) { IV = john_htonl(fullblocks); SHA1_Init(&ctx); SHA1_Update(&ctx, &IV, 4); SHA1_Update(&ctx, src + 20 * fullblocks, padding); SHA1_Final(dst + 20 * fullblocks, &ctx); } return 0; } static int AF_merge(unsigned char *src, unsigned char *dst, int afsize, int stripes) { int i; char *bufblock; int blocksize = afsize / stripes; bufblock = mem_calloc(1, blocksize + 20); for (i = 0; i < (stripes - 1); i++) { XORblock((char *) (src + (blocksize * i)), bufblock, bufblock, blocksize); diffuse((unsigned char *) bufblock, (unsigned char *) bufblock, blocksize); } XORblock((char *) (src + blocksize * (stripes - 1)), bufblock, (char *) dst, blocksize); MEM_FREE(bufblock); return 0; } static int af_sectors(int blocksize, int blocknumbers) { int af_size; af_size = blocksize * blocknumbers; af_size = (af_size + 511) / 512; af_size *= 512; return af_size; } static void decrypt_aes_cbc_essiv(unsigned char *src, unsigned char *dst, unsigned char *key, int size, struct custom_salt_LUKS *cs) { AES_KEY aeskey; unsigned char essiv[16]; unsigned char essivhash[32]; unsigned a; SHA256_CTX ctx; unsigned char sectorbuf[16]; unsigned char zeroiv[16]; // This should NEVER be done in the loop!! This never changed. SHA256_Init(&ctx); SHA256_Update(&ctx, key, john_ntohl(cs->myphdr.keyBytes)); SHA256_Final(essivhash, &ctx); memset(sectorbuf, 0, 16); memset(essiv, 0, 16); for (a = 0; a < (size / 512); a++) { memset(zeroiv, 0, 16); #if ARCH_LITTLE_ENDIAN memcpy(sectorbuf, &a, 4); #else { unsigned b = JOHNSWAP(a); memcpy(sectorbuf, &b, 4); } #endif AES_set_encrypt_key(essivhash, 256, &aeskey); AES_cbc_encrypt(sectorbuf, essiv, 16, &aeskey, zeroiv, AES_ENCRYPT); AES_set_decrypt_key(key, john_ntohl(cs->myphdr.keyBytes)*8, &aeskey); AES_cbc_encrypt((src+a*512), (dst+a*512), 512, &aeskey, essiv, AES_DECRYPT); } } static int hash_plugin_parse_hash(char *filename, unsigned char **cp, int afsize, int is_critical) { FILE *myfile; int readbytes; myfile = jtr_fopen(filename, "rb"); if (!myfile) { fprintf(stderr, "\n%s : %s!\n", filename, strerror(errno)); return -1; } // can this go over 4gb? *cp =(unsigned char*) mem_calloc(1, afsize + 1); if (!*cp) goto bad; // printf(">>> %d\n", cs->afsize); readbytes = fread(*cp, afsize, 1, myfile); if (readbytes < 0) { fprintf(stderr, "%s : unable to read required data\n", filename); goto bad; } fclose(myfile); return afsize+1; bad: fclose(myfile); if (is_critical) { fprintf(stderr, "\nLUKS plug-in is unable to continue due to errors!\n"); error(); } return -1; } static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static void init(struct fmt_main *self) { static int warned = 0; // extern struct fmt_main fmt_luks; #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); /* * LUKS format will need to be redesigned to address the issues mentioned in * https://github.com/magnumripper/JohnTheRipper/issues/557. * This will require a change in john's hash representation for LUKS format. * The redesign will happen after the next official jumbo release. * To avoid having to support the current LUKS hash representation forever, * just print a warning that the hash representation will change in future releases. * * So far, no "official" jumbo release supports the LUKS format, currently only * users of bleeding-jumbo may have used LUKS format. These users should be able * to re-run luks2john and retry the passwords that have been stored for the current LUKS hashes * once the redesign of john's LUKS format implementation has been completed.) */ if (!options.listconf && !(options.flags & FLG_TEST_CHK) && warned++ == 0) { fprintf(stderr, "WARNING, LUKS format hash representation will change in future releases,\n" "see doc/README.LUKS\n"); // FIXME: address github issue #557 after 1.8.0-jumbo-1 fflush(stderr); } // This printf will 'help' debug a system that truncates that monster hash, but does not cause compiler to die. // printf("length=%d end=%s\n", strlen(fmt_luks.params.tests[0].ciphertext), &((fmt_luks.params.tests[0].ciphertext)[strlen(fmt_luks.params.tests[0].ciphertext)-30])); #ifdef _MSC_VER LUKS_test_fixup(); #endif } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p, *q; unsigned char *buf; int is_inlined, i, bestslot=0; int res; int afsize; unsigned char *out; struct custom_salt_LUKS cs; uint64_t keybytes, stripes; unsigned int bestiter = 0xFFFFFFFF; out = (unsigned char*)&cs.myphdr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; if ((p = strtokm(ctcopy, "$")) == NULL) /* is_inlined */ goto err; if (!isdec(p)) goto err; is_inlined = atoi(p); if ((p = strtokm(NULL, "$")) == NULL) goto err; if (!isdec(p)) goto err; afsize = atoi(p); if (afsize != sizeof(struct luks_phdr)) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (afsize != strlen(p) / 2) goto err; if (!ishexlc(p)) goto err; for (i = 0; i < afsize; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } keybytes = john_ntohl(cs.myphdr.keyBytes); for (i = 0; i < LUKS_NUMKEYS; i++) { if ((john_ntohl(cs.myphdr.keyblock[i].passwordIterations) < bestiter) && (john_ntohl(cs.myphdr.keyblock[i].passwordIterations) > 1) && (john_ntohl(cs.myphdr.keyblock[i].active) == 0x00ac71f3)) { bestslot = i; bestiter = john_ntohl(cs.myphdr.keyblock[i].passwordIterations); } } stripes = john_ntohl(cs.myphdr.keyblock[bestslot].stripes); if ( (uint64_t)(john_ntohl(cs.myphdr.keyBytes)*john_ntohl(cs.myphdr.keyblock[bestslot].stripes)) != keybytes*stripes) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (!isdec(p)) goto err; res = atoi(p); if (res != keybytes*stripes) goto err; if (is_inlined) { if ((p = strtokm(NULL, "$")) == NULL) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (strlen(p) != LUKS_DIGESTSIZE * 2) goto err; if (!ishexlc(p)) goto err; } else { if ((p = strtokm(NULL, "$")) == NULL) /* LUKS file */ goto err; if ((p = strtokm(NULL, "$")) == NULL) /* dump file */ goto err; q = p; if ((p = strtokm(NULL, "$")) == NULL) /* mkDigest */ goto err; if (strlen(p) != LUKS_DIGESTSIZE * 2) goto err; if (!ishexlc(p)) goto err; /* more tests */ if (hash_plugin_parse_hash(q, &buf, afsize, 0) == -1) { return 0; } MEM_FREE(buf); } MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int is_inlined; int res; int i; int cnt; unsigned char *out; unsigned char *buf; struct custom_salt_LUKS cs, *psalt; static unsigned char *ptr; unsigned int bestiter = 0xFFFFFFFF; size_t size = 0; ctcopy += FORMAT_TAG_LEN; if (!ptr) ptr = mem_alloc_tiny(sizeof(struct custom_salt*),sizeof(struct custom_salt*)); memset(&cs, 0, sizeof(cs)); out = (unsigned char*)&cs.myphdr; p = strtokm(ctcopy, "$"); is_inlined = atoi(p); /* common handling */ p = strtokm(NULL, "$"); res = atoi(p); assert(res == sizeof(struct luks_phdr)); p = strtokm(NULL, "$"); for (i = 0; i < res; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } p = strtokm(NULL, "$"); res = atoi(p); if (is_inlined) { p = strtokm(NULL, "$"); size = strlen(p) / 4 * 3 + 1; buf = mem_calloc(1, size+4); base64_decode(p, strlen(p), (char*)buf); cs.afsize = size; } else { cs.afsize = res; p = strtokm(NULL, "$"); p = strtokm(NULL, "$"); strcpy(cs.path, p); size = hash_plugin_parse_hash(cs.path, &buf, cs.afsize, 1); } for (cnt = 0; cnt < LUKS_NUMKEYS; cnt++) { if ((john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations) < bestiter) && (john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations) > 1) && (john_ntohl(cs.myphdr.keyblock[cnt].active) == 0x00ac71f3)) { cs.bestslot = cnt; cs.bestiter = john_ntohl(cs.myphdr.keyblock[cnt].passwordIterations); } } cs.afsize = af_sectors(john_ntohl(cs.myphdr.keyBytes), john_ntohl(cs.myphdr.keyblock[cs.bestslot].stripes)); assert(res == cs.afsize); MEM_FREE(keeptr); psalt = (struct custom_salt_LUKS*)mem_alloc_tiny(sizeof(struct custom_salt_LUKS)+size, 4); memcpy(psalt, &cs, sizeof(cs)); memcpy(psalt->cipherbuf, buf, size); MEM_FREE(buf); psalt->dsalt.salt_alloc_needs_free = 0; // set the JtR core linkage stuff for this dyna_salt psalt->dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt_LUKS, myphdr); psalt->dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt_LUKS, myphdr, cipherbuf, size); memcpy(ptr, &psalt, sizeof(struct custom_salt*)); return (void*)ptr; } static void *get_binary(char *ciphertext) { static union { unsigned char c[LUKS_DIGESTSIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1; for (i = 0; i < LUKS_DIGESTSIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static void set_salt(void *salt) { cur_salt = *(struct custom_salt_LUKS **)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { unsigned char *af_decrypted = (unsigned char *)mem_alloc(cur_salt->afsize + 20); int i, iterations = cur_salt->bestiter; int dklen = john_ntohl(cur_salt->myphdr.keyBytes); uint32_t keycandidate[MAX_KEYS_PER_CRYPT][256/4]; uint32_t masterkeycandidate[MAX_KEYS_PER_CRYPT][256/4]; #ifdef SIMD_COEF_32 int lens[MAX_KEYS_PER_CRYPT]; unsigned char *pin[MAX_KEYS_PER_CRYPT]; union { uint32_t *pout[MAX_KEYS_PER_CRYPT]; unsigned char *poutc; } x; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; x.pout[i] = keycandidate[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, (const unsigned char*)(cur_salt->myphdr.keyblock[cur_salt->bestslot].passwordSalt), LUKS_SALTSIZE, iterations, &(x.poutc), dklen, 0); #else pbkdf2_sha1((const unsigned char *)saved_key[index], strlen(saved_key[index]), (const unsigned char*)(cur_salt->myphdr.keyblock[cur_salt->bestslot].passwordSalt), LUKS_SALTSIZE, iterations, (unsigned char*)keycandidate[0], dklen, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { // Decrypt the blocksi decrypt_aes_cbc_essiv(cur_salt->cipherbuf, af_decrypted, (unsigned char*)keycandidate[i], cur_salt->afsize, cur_salt); // AFMerge the blocks AF_merge(af_decrypted, (unsigned char*)masterkeycandidate[i], cur_salt->afsize, john_ntohl(cur_salt->myphdr.keyblock[cur_salt->bestslot].stripes)); } // pbkdf2 again #ifdef SIMD_COEF_32 for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { lens[i] = john_ntohl(cur_salt->myphdr.keyBytes); pin[i] = (unsigned char*)masterkeycandidate[i]; x.pout[i] = crypt_out[index+i]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, (const unsigned char*)cur_salt->myphdr.mkDigestSalt, LUKS_SALTSIZE, john_ntohl(cur_salt->myphdr.mkDigestIterations), &(x.poutc), LUKS_DIGESTSIZE, 0); #else pbkdf2_sha1((unsigned char*)masterkeycandidate[0], john_ntohl(cur_salt->myphdr.keyBytes), (const unsigned char*)cur_salt->myphdr.mkDigestSalt, LUKS_SALTSIZE, john_ntohl(cur_salt->myphdr.mkDigestIterations), (unsigned char*)crypt_out[index], LUKS_DIGESTSIZE, 0); #endif MEM_FREE(af_decrypted); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], LUKS_DIGESTSIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], LUKS_DIGESTSIZE); } static int cmp_exact(char *source, int index) { return 1; } static void luks_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_luks = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_DYNA_SALT | FMT_HUGE_INPUT, { NULL }, { FORMAT_TAG }, luks_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_dyna_salt_hash, NULL, set_salt, luks_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
producer.c
#include "grid.h" #include "config.h" #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <string.h> #include <omp.h> #ifndef NO_MPI #include <mpi.h> #else #define MPI_Request int #define MPI_REQUEST_NULL 0 #endif struct producer_stream { // Facet worker id, number of facets to work on int facet_worker; int facet_work_count; // Stream targets int streamer_count; int *streamer_ranks; // Send queue int send_queue_length; MPI_Request *requests; uint64_t bytes_sent; // Private buffers double complex *NMBF_NMBF_queue; // Worker structure struct recombine2d_worker worker; // Time (in s) spent in different stages double mpi_wait_time, mpi_send_time; }; void init_producer_stream(struct recombine2d_config *cfg, struct producer_stream *prod, int facet_worker, int facet_work_count, int streamer_count, int *streamer_ranks, int BF_batch, fftw_plan BF_plan, int send_queue_length) { prod->facet_worker = facet_worker; prod->facet_work_count = facet_work_count; // Set streamers prod->streamer_count = streamer_count; prod->streamer_ranks = streamer_ranks; // Initialise queue prod->send_queue_length = send_queue_length; prod->requests = (MPI_Request *) malloc(sizeof(MPI_Request) * send_queue_length); int i; for (i = 0; i < send_queue_length; i++) { prod->requests[i] = MPI_REQUEST_NULL; } // Create buffers, initialise worker prod->NMBF_NMBF_queue = (double complex *)malloc(cfg->NMBF_NMBF_size * send_queue_length); recombine2d_init_worker(&prod->worker, cfg, BF_batch, BF_plan, FFTW_MEASURE); // Initialise statistics prod->bytes_sent = 0; prod->mpi_wait_time = prod->mpi_send_time = 0; } void free_producer_stream(struct producer_stream *prod) { recombine2d_free_worker(&prod->worker); free(prod->requests); free(prod->NMBF_NMBF_queue); } void producer_add_stats(struct producer_stream *to, struct producer_stream *from) { to->bytes_sent += from->bytes_sent; to->worker.pf1_time += from->worker.pf1_time; to->worker.es1_time += from->worker.es1_time; to->worker.ft1_time += from->worker.ft1_time; to->worker.pf2_time += from->worker.pf2_time; to->worker.es2_time += from->worker.es2_time; to->worker.ft2_time += from->worker.ft2_time; to->mpi_wait_time += from->mpi_wait_time; to->mpi_send_time += from->mpi_send_time; } void producer_dump_stats(struct work_config *wcfg, int facet_worker, struct producer_stream *prod, int producer_count, double dt) { struct recombine2d_config *cfg = &wcfg->recombine; // For the "effective" statistic we count the number of bytes we // conveyed information about. This statistic is slightly messy // because on one hand we have communication overheads (decreasing // effectiveness), but on the other hand for generating // visibilities do not need to cover the entire grid (increasing // effectivenes). uint64_t effective = 0; int i; for (i = 0; i < wcfg->facet_max_work; i++) { if (wcfg->facet_work[i].set) { effective += cfg->F_size; } } double total = dt * producer_count; printf("\n%.2f s wall-clock, %.2f GB (%.2f GB effective), %.2f MB/s (%.2f MB/s effective)\n", dt, (double)prod->bytes_sent / 1000000000, (double)effective / 1000000000, (double)prod->bytes_sent / dt / 1000000, (double)effective / dt/ 1000000); printf("PF1: %.2f s (%.1f%%), FT1: %.2f s (%.1f%%), ES1: %.2f s (%.1f%%)\n", prod->worker.pf1_time, prod->worker.pf1_time / total * 100, prod->worker.ft1_time, prod->worker.ft1_time / total * 100, prod->worker.es1_time, prod->worker.es1_time / total * 100); printf("PF2: %.2f s (%.1f%%), FT2: %.2f s (%.1f%%), ES2: %.2f s (%.1f%%)\n", prod->worker.pf2_time, prod->worker.pf2_time / total * 100, prod->worker.ft2_time, prod->worker.ft2_time / total * 100, prod->worker.es2_time, prod->worker.es2_time / total * 100); double idle = total - prod->worker.pf1_time - prod->worker.ft1_time - prod->worker.es1_time - prod->worker.pf2_time - prod->worker.ft2_time - prod->worker.es2_time - prod->mpi_wait_time - prod->mpi_send_time; printf("mpi wait: %.2f s (%.1f%%), mpi send: %.2f s (%.1f%%), idle: %.2f s (%.1f%%)\n", prod->mpi_wait_time, 100 * prod->mpi_wait_time / producer_count / dt, prod->mpi_send_time, 100 * prod->mpi_send_time / producer_count / dt, idle, 100 * idle / producer_count / dt); } int make_subgrid_tag(struct work_config *wcfg, int subgrid_worker_ix, int subgrid_work_ix, int facet_worker_ix, int facet_work_ix) { // Need to encode only the work items, as with MPI both the sender // and the receiver will be identified already by the message. return facet_work_ix * wcfg->subgrid_max_work + subgrid_work_ix; } void producer_send_subgrid(struct work_config *wcfg, struct producer_stream *prod, int facet_work_ix, double complex *NMBF_BF, int subgrid_off_u, int subgrid_off_v, int iu, int iv) { struct recombine2d_config *cfg = &wcfg->recombine; // Extract subgrids along second axis double complex *NMBF_NMBF = NULL; // Find streamer (subgrid workers) to send to int iworker; for (iworker = 0; iworker < wcfg->subgrid_workers; iworker++) { // Check whether it is in streamer's work list. Note that // it can appear for multiple workers if the subgrid was // split in work assignment (typically at the grid centre). struct subgrid_work *work_list = wcfg->subgrid_work + iworker * wcfg->subgrid_max_work; int iwork; for (iwork = 0; iwork < wcfg->subgrid_max_work; iwork++) { if (work_list[iwork].nbl && work_list[iwork].iu == iu && work_list[iwork].iv == iv) break; } if (iwork >= wcfg->subgrid_max_work) continue; // Select send slot if running in distributed mode int indx; #ifndef NO_MPI if (prod->streamer_count == 0) indx = 0; else { for (indx = 0; indx < prod->send_queue_length; indx++) { if (prod->requests[indx] == MPI_REQUEST_NULL) break; } if (indx >= prod->send_queue_length) { double start = get_time_ns(); MPI_Status status; MPI_Waitany(prod->send_queue_length, prod->requests, &indx, &status); prod->mpi_wait_time += get_time_ns() - start; } assert (indx >= 0 && indx < prod->send_queue_length); } #else indx = 0; #endif // Calculate or copy sub-grid data double complex *send_buf = prod->NMBF_NMBF_queue + indx * cfg->xM_yN_size * cfg->xM_yN_size; if (!NMBF_NMBF) { NMBF_NMBF = send_buf; recombine2d_es0(&prod->worker, subgrid_off_v, subgrid_off_u, NMBF_BF, NMBF_NMBF); } else { memcpy(send_buf, NMBF_NMBF, cfg->NMBF_NMBF_size); } // Send (unless running in single-node mode, then we just pretend) #ifndef NO_MPI if (prod->streamer_ranks) { int tag = make_subgrid_tag(wcfg, iworker, iwork, prod->facet_worker, facet_work_ix); double start = get_time_ns(); MPI_Isend(send_buf, cfg->xM_yN_size * cfg->xM_yN_size, MPI_DOUBLE_COMPLEX, prod->streamer_ranks[iworker], tag, MPI_COMM_WORLD, &prod->requests[indx]); prod->mpi_send_time += get_time_ns() - start; } #endif prod->bytes_sent += sizeof(double complex) * cfg->xM_yN_size * cfg->xM_yN_size; } } bool producer_fill_facet(struct recombine2d_config *cfg, struct facet_work *work, double complex *F, int source_count, double gridder_x0, double *grid_correction, int x0_start, int x0_end) { int offset = sizeof(double complex) *x0_start * cfg->yB_size; int size = sizeof(double complex) *(x0_end - x0_start) * cfg->yB_size; if (work->path && !work->hdf5) { printf("Reading facet data from %s (%d-%d)...\n", work->path, x0_start, x0_end); // Make sure strides are compatible assert (cfg->F_stride0 == cfg->yB_size && cfg->F_stride1 == 1); // Load data from file int fd = open(work->path, O_RDONLY, 0666); if (fd > 0) { lseek(fd, offset, SEEK_SET); if (read(fd, F, size) != size) { fprintf(stderr, "failed to read enough data from %s for range %d-%d!\n", work->path, x0_start, x0_end); return false; } close(fd); } else { fprintf(stderr, "Failed to read facet data!\n"); } } else if (work->path && work->hdf5) { printf("Reading facet data from %s:%s (%d-%d)...\n", work->hdf5, work->path, x0_start, x0_end); // Make sure strides are as expected, then read // TODO: Clearly HDF5 can do partial reads, optimise assert (cfg->F_stride0 == cfg->yB_size && cfg->F_stride1 == 1); double complex *data = read_hdf5(cfg->F_size, work->hdf5, work->path); // Copy memcpy(F, data + offset / sizeof(double complex), size); free(data); } else if (source_count > 0) { // Place sources in gridder's usable region unsigned int seed = 0; int image_x0_size = (int)floor(2 * gridder_x0 * cfg->image_size); int i; for (i = 0; i < source_count; i++) { int il = (int)(rand_r(&seed) % image_x0_size) - image_x0_size / 2; int im = (int)(rand_r(&seed) % image_x0_size) - image_x0_size / 2; // Skip sources outside the current facet (region) if (il - work->facet_off_l < -cfg->yB_size/2 || il - work->facet_off_l >= cfg->yB_size/2 || im - work->facet_off_m < -cfg->yB_size/2 || im - work->facet_off_m >= cfg->yB_size/2) { continue; } // Calculate facet coordinates, keeping in mind that the // centre is at (0/0). int x0 = (im - work->facet_off_m + cfg->yB_size) % cfg->yB_size; int x1 = (il - work->facet_off_l + cfg->yB_size) % cfg->yB_size; if (x0 < x0_start || x0 >= x0_end) { continue; } double c = grid_correction[(il + cfg->image_size) % cfg->image_size] * grid_correction[(im + cfg->image_size) % cfg->image_size]; assert(c != 0); F[(x0-x0_start)*cfg->F_stride0 + x1*cfg->F_stride1] += 1 / c; } } else { // Fill facet with deterministic pseudo-random numbers int x0, x1; for (x0 = x0_start; x0 < x0_end; x0++) { unsigned int seed = x0; for (x1 = 0; x1 < cfg->yB_size; x1++) { F[(x0-x0_start)*cfg->F_stride0+x1*cfg->F_stride1] = (double)rand_r(&seed) / RAND_MAX; } } } return true; } // Gets subgrid offset for given column/rpw. Returns INT_MIN if no work was found. static int get_subgrid_off_u(struct work_config *wcfg, int iu) { // Somewhat inefficiently walk entire work list int iwork; for (iwork = 0; iwork < wcfg->subgrid_workers * wcfg->subgrid_max_work; iwork++) { if (wcfg->subgrid_work[iwork].nbl > 0 && wcfg->subgrid_work[iwork].iu == iu) break; } if (iwork >= wcfg->subgrid_workers * wcfg->subgrid_max_work) return INT_MIN; return wcfg->subgrid_work[iwork].subgrid_off_u; } static int get_subgrid_off_v(struct work_config *wcfg, int iu, int iv) { // Somewhat inefficiently walk entire work list int iwork; for (iwork = 0; iwork < wcfg->subgrid_workers * wcfg->subgrid_max_work; iwork++) { if (wcfg->subgrid_work[iwork].nbl > 0 && wcfg->subgrid_work[iwork].iu == iu && wcfg->subgrid_work[iwork].iv == iv) break; } if (iwork >= wcfg->subgrid_workers * wcfg->subgrid_max_work) return INT_MIN; return wcfg->subgrid_work[iwork].subgrid_off_v; } static void producer_work(struct work_config *wcfg, struct producer_stream *prod, struct producer_stream *producers, double complex *F, double complex *BF) { int ifacet; // Do first stage preparation and Fourier Transform if (wcfg->produce_retain_bf) for (ifacet = 0; ifacet < prod->facet_work_count; ifacet++) recombine2d_pf1_ft1_omp(&prod->worker, F + ifacet * wcfg->recombine.F_size / sizeof(*F), BF + ifacet * wcfg->recombine.BF_size / sizeof(*BF)); // TODO: Generate facet on the fly int iu; if (wcfg->produce_parallel_cols) { // Go through columns in parallel #pragma omp for schedule(dynamic) for (iu = wcfg->iu_min; iu <= wcfg->iu_max ; iu++) { // Determine column offset / check whether column actually has work int subgrid_off_u = get_subgrid_off_u(wcfg, iu); if (subgrid_off_u == INT_MIN) continue; // Loop through facets sequentially (inefficient, as it // introduces a time delay on when we touch facets) for (ifacet = 0; ifacet < prod->facet_work_count; ifacet++) { // Extract subgrids along first axis, then prepare and Fourier // transform along second axis recombine2d_es1_pf0_ft0(&prod->worker, subgrid_off_u, BF + ifacet * wcfg->recombine.BF_size / sizeof(*BF), prod->worker.NMBF_BF); // Go through rows in sequence int iv; for (iv = wcfg->iv_min; iv <= wcfg->iv_max; iv++) { int subgrid_off_v = get_subgrid_off_v(wcfg, iu, iv); if (subgrid_off_v == INT_MIN) continue; producer_send_subgrid(wcfg, prod, ifacet, prod->worker.NMBF_BF, subgrid_off_u, subgrid_off_v, iu, iv); } } } } else { // Go through columns in sequence for (iu = wcfg->iu_min; iu <= wcfg->iu_max; iu++) { // Determine column offset / check whether column actually has work int subgrid_off_u = get_subgrid_off_u(wcfg, iu); if (subgrid_off_u == INT_MIN) continue; // Loop through facets (inefficient, see above) for (ifacet = 0; ifacet < prod->facet_work_count; ifacet++) { // Extract subgrids along first axis, then prepare and Fourier // transform along second axis double complex *NMBF = producers->worker.NMBF; double complex *NMBF_BF = producers->worker.NMBF_BF; if (wcfg->produce_retain_bf) recombine2d_es1_omp(&prod->worker, subgrid_off_u, BF + ifacet * wcfg->recombine.BF_size / sizeof(*BF), NMBF); else recombine2d_pf1_ft1_es1_omp(&prod->worker, subgrid_off_u, F + ifacet * wcfg->recombine.F_size / sizeof(*F), NMBF); recombine2d_pf0_ft0_omp(&prod->worker, NMBF, NMBF_BF); // Go through rows in parallel int iv; #pragma omp for schedule(dynamic) for (iv = wcfg->iv_min; iv <= wcfg->iv_max; iv++) { int subgrid_off_v = get_subgrid_off_v(wcfg, iu, iv); if (subgrid_off_v == INT_MIN) continue; producer_send_subgrid(wcfg, prod, ifacet, NMBF_BF, subgrid_off_u, subgrid_off_v, iu, iv); } } } } } int producer(struct work_config *wcfg, int facet_worker, int *streamer_ranks) { struct recombine2d_config *cfg = &wcfg->recombine; struct facet_work *fwork = wcfg->facet_work + facet_worker * wcfg->facet_max_work; const int BF_batch = wcfg->produce_batch_rows; const int send_queue_length = wcfg->produce_queue_length; // Get number of facets we need to cover, warn if it is bigger than 1 int facet_work_count = 0; int ifacet; for (ifacet = 0; ifacet < wcfg->facet_max_work; ifacet++) if (fwork[ifacet].set) facet_work_count++; uint64_t F_size = facet_work_count * cfg->F_size; uint64_t BF_size = wcfg->produce_retain_bf ? facet_work_count * cfg->BF_size : sizeof(double complex) * cfg->yP_size * BF_batch; printf("Using %.1f GB global, %.1f GB per thread\n", (double)(F_size + BF_size) / 1000000000, facet_work_count * (double)recombine2d_worker_memory(cfg) / 1000000000); // Create global memory buffers double complex *F = (double complex *)calloc(1, F_size); double complex *BF = (double complex *)malloc(BF_size); if (!F || (!BF && wcfg->produce_retain_bf)) { free(F); free(BF); printf("Failed to allocate global buffers!\n"); return 1; } // Fill facet with random data (TODO: Handle the case that we are // meant to cover more than one facet...) printf("Filling %d facet%s...\n", facet_work_count, facet_work_count != 1 ? "s" : ""); double generate_start = get_time_ns(); int x0; const int x0_chunk = 256; for (ifacet = 0; ifacet < facet_work_count; ifacet++) { #pragma omp parallel for schedule(dynamic) for (x0 = 0; x0 < cfg->yB_size; x0+=x0_chunk) { int x0_end = x0 + x0_chunk; if (x0_end > cfg->yB_size) x0_end = cfg->yB_size; double complex *pF = F + ifacet * wcfg->recombine.F_size / sizeof(*F) + x0*cfg->F_stride0; producer_fill_facet(cfg, fwork + ifacet, pF, wcfg->produce_source_count, wcfg->gridder_x0, wcfg->grid_correction, x0, x0_end); } } printf(" %.2f s\n", get_time_ns() - generate_start); // Debugging (TODO: remove) if (false) { int x1; for (x0 = 0; x0 < cfg->yB_size; x0++) { for (x1 = 0; x1 < cfg->yB_size; x1++) { printf("%8.2f%+8.2fi\t", creal(F[x0*cfg->F_stride0+x1*cfg->F_stride1]), cimag(F[x0*cfg->F_stride0+x1*cfg->F_stride1])); } puts(""); } } // Global structures double run_start; int producer_count; struct producer_stream *producers; #pragma omp parallel { producer_count = omp_get_num_threads(); #pragma omp single { // Do global planning printf("Planning for %d threads...\n", producer_count); double planning_start = get_time_ns(); fftw_plan BF_plan = recombine2d_bf_plan(cfg, BF_batch, BF, FFTW_MEASURE); // Create producers (which involves planning, and therefore is not parallelised) producers = (struct producer_stream *) malloc(sizeof(struct producer_stream) * producer_count); int i; for (i = 0; i < producer_count; i++) { init_producer_stream(cfg, producers + i, facet_worker, facet_work_count, wcfg->facet_workers, streamer_ranks, BF_batch, BF_plan, send_queue_length); } // End of planning phase printf(" %.2f s\n", get_time_ns() - planning_start); run_start = get_time_ns(); printf("Streaming...\n"); } // Do work struct producer_stream *prod = producers + omp_get_thread_num(); producer_work(wcfg, prod, producers, F, BF); #ifndef NO_MPI // Wait for remaining packets to be sent double start = get_time_ns(); MPI_Status statuses[send_queue_length]; MPI_Waitall(send_queue_length, prod->requests, statuses); prod->mpi_wait_time += get_time_ns() - start; #endif free_producer_stream(prod); } free(BF); free(F); fftw_free(producers[0].worker.BF_plan); // Show statistics int p; for (p = 1; p < producer_count; p++) { producer_add_stats(producers, producers + p); } producer_dump_stats(wcfg, facet_worker, producers, producer_count, get_time_ns() - run_start); return 0; }
omp_get_num_threads.c
<ompts:test> <ompts:testdescription>Test which checks that the omp_get_num_threads returns the correct number of threads. Therefor it counts up a variable in a parallelized section and compars this value with the result of the omp_get_num_threads function.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp_get_num_threads</ompts:directive> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_get_num_threads</ompts:testcode:functionname> (FILE * logFile) { /* checks that omp_get_num_threads is equal to the number of threads */ <ompts:orphan:vars> int nthreads_lib; </ompts:orphan:vars> int nthreads = 0; nthreads_lib = -1; #pragma omp parallel { #pragma omp critical { nthreads++; } /* end of critical */ #pragma omp single { <ompts:orphan> <ompts:check>nthreads_lib = omp_get_num_threads ();</ompts:check> </ompts:orphan> } /* end of single */ } /* end of parallel */ fprintf (logFile, "Counted %d threads. get_num_threads returned %d.\n", nthreads, nthreads_lib); return (nthreads == nthreads_lib); } </ompts:testcode> </ompts:test>
dynamic_fmt.c
/* * This software was written by Jim Fougeron jfoug AT cox dot net * in 2009-2013. No copyright is claimed, and the software is hereby * placed in the public domain. In case this attempt to disclaim * copyright and place the software in the public domain is deemed * null and void, then the software is Copyright (c) 2009-2013 Jim Fougeron * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. * * Generic 'scriptable' hash cracker for JtR * * Renamed and changed from md5_gen* to dynamic*. We handle MD5 and SHA1 * at the present time. More crypt types 'may' be added later. * Added SHA2 (SHA224, SHA256, SHA384, SHA512), GOST, Whirlpool crypt types. * Whirlpool use oSSSL if OPENSSL_VERSION_NUMBER >= 0x10000000, otherwise use sph_* code. * * There used to be a todo list, and other commenting here. It has been * moved to ./docs/dynamic_history.txt * * KNOWN issues, and things to do. * * 1. create a new optimize flag, MGF_PASS_AFTER_FIXEDSALT and * MGF_PASS_BEFORE_FIXEDSALT. Then create DynamicFunc__appendsalt_after_pass[12] * These would only be valid for a FIXED length salted format. Then * we can write the pass right into the buffer, and get_key() would read * it back from there, either skipping over the salt, or removing the salt * from the end. This would allow crypt($s.$p) and crypt($p.s) to be optimized * in the way of string loading, and many fewer buffer copies. So dyna_1 could * be optimized to something like: // dynamic_1 Joomla md5($p.$s) static DYNAMIC_primitive_funcp _Funcs_1[] = { //Flags=MGF_PASS_BEFORE_FIXEDSALT | MGF_SALTED // saltlen=3 (or whatever). This fixed size is 'key' DynamicFunc__appendsalt_after_pass1, DynamicFunc__crypt_md5, NULL }; * WELL, the fixed size salt, it 'may' not be key for the MGF_PASS_BEFORE_FIXEDSALT, * I think I can make that 'work' for variable sized salts. But for the * MGF_PASS_AFTER_FIXEDSALT, i.e. crypt($s.$p) the fixed size salt IS key. I would * like to store all PW's at salt_len offset in the buffer, and simply overwrite the * first part of each buffer with the salt, never moving the password after the first * time it is written. THEN it is very important this ONLY be allowed when we KNOW * the salt length ahead of time. * * 2. Change regen-salts to be generic. Add the logic to dynamic_fmt.c proper, and change * the fake-salts.c, and options so that 'generic' regen-salts can be done. */ #include <string.h> #include <time.h> #if AC_BUILT #include "autoconfig.h" #endif #include "arch.h" #if defined(SIMD_COEF_32) && !ARCH_LITTLE_ENDIAN #undef SIMD_COEF_32 #undef SIMD_COEF_64 #undef SIMD_PARA_MD5 #undef SIMD_PARA_MD4 #undef SIMD_PARA_SHA1 #undef SIMD_PARA_SHA256 #undef SIMD_PARA_SHA512 #define BITS ARCH_BITS_STR #endif #if !FAST_FORMATS_OMP #ifdef _OPENMP #define FORCE_THREAD_MD5_body #endif #undef _OPENMP #endif #ifndef DYNAMIC_DISABLED #ifdef SIMD_COEF_32 #include "simd-intrinsics.h" #endif #include "misc.h" #include "common.h" #include "formats.h" #include "params.h" #include "md5.h" #include "md4.h" #include "dynamic.h" #include "options.h" #include "config.h" #include "sha.h" #include "sha2.h" #include "gost.h" #include "sph_haval.h" #include "sph_ripemd.h" #include "sph_tiger.h" #include "sph_md2.h" #include "sph_panama.h" #include "sph_skein.h" #include "sph_whirlpool.h" #include "memory.h" #include "unicode.h" #include "johnswap.h" #include "crc32.h" #include "aligned.h" #include "fake_salts.h" #include "base64_convert.h" #if (AC_BUILT && HAVE_WHIRLPOOL) || \ (!AC_BUILT && OPENSSL_VERSION_NUMBER >= 0x10000000 && !HAVE_NO_SSL_WHIRLPOOL) #include <openssl/whrlpool.h> #else // on my 32 bit cygwin builds, this code is about 4x slower than the oSSL code. #define WHIRLPOOL_CTX sph_whirlpool_context #define WHIRLPOOL_Init(a) sph_whirlpool_init(a) #define WHIRLPOOL_Update(a,b,c) sph_whirlpool(a,b,c) #define WHIRLPOOL_Final(a,b) sph_whirlpool_close(b,a) #endif #include "KeccakHash.h" #define KECCAK_CTX Keccak_HashInstance #define KECCAK_Update(a,b,c) Keccak_HashUpdate(a,b,(c)*8) #define KECCAK_Final(a,b) Keccak_HashFinal(b,a) #define KECCAK_256_Init(hash) Keccak_HashInitialize(hash, 1088, 512, 256, 0x01) #define KECCAK_512_Init(hash) Keccak_HashInitialize(hash, 576, 1024, 512, 0x01) // FIPS202 complient #define SHA3_224_Init(hash) Keccak_HashInitialize(hash, 1152, 448, 224, 0x06) #define SHA3_256_Init(hash) Keccak_HashInitialize(hash, 1088, 512, 256, 0x06) #define SHA3_384_Init(hash) Keccak_HashInitialize(hash, 832, 768, 384, 0x06) #define SHA3_512_Init(hash) Keccak_HashInitialize(hash, 576, 1024, 512, 0x06) #ifdef _OPENMP #include <omp.h> static unsigned int m_ompt; #endif #include "dynamic_types.h" #include "memdbg.h" #if (defined (_OPENMP)||defined(FORCE_THREAD_MD5_body)) && defined (_MSC_VER) unsigned DES_bs_max_kpc, DES_bs_min_kpc, DES_bs_all_p; #undef MD5_body extern void MD5_body(MD5_word x[15],MD5_word out[4]); #endif #define STRINGIZE2(s) #s #define STRINGIZE(s) STRINGIZE2(s) static struct fmt_main fmt_Dynamic; static struct fmt_main *pFmts; static int nFmts; static int nLocalFmts; static struct fmt_main *pLocalFmts; static int force_md5_ctx; static void dynamic_RESET(struct fmt_main *fmt); #define eLargeOut dyna_eLargeOut eLargeOut_t *eLargeOut; #define nLargeOff dyna_nLargeOff unsigned *nLargeOff; #if ARCH_LITTLE_ENDIAN #define MD5_swap(x, y, count) #define MD5_swap2(a,b,c,d,e) #else extern char *MD5_DumpHexStr(void *p); static void MD5_swap(MD5_word *x, MD5_word *y, int count) { do { *y++ = JOHNSWAP(*x++); } while (--count); } #if MD5_X2 static void MD5_swap2(MD5_word *x, MD5_word *x2, MD5_word *y, MD5_word *y2, int count) { do { *y++ = JOHNSWAP(*x++); *y2++ = JOHNSWAP(*x2++); } while (--count); } #endif #endif #define FORMAT_LABEL "dynamic" #define FORMAT_NAME "Generic MD5" #ifdef SIMD_COEF_32 #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3) )*SIMD_COEF_32 + ((i)&3) ) #define SHAGETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3) )*SIMD_COEF_32 + (3-((i)&3)) ) //for endianity conversion #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define CIPHERTEXT_LENGTH 32 #define BINARY_SIZE 16 #define BINARY_SIZE_SHA 20 #define BINARY_ALIGN MEM_ALIGN_WORD // Computation for 'salt_size' The salt (and salt2) is appended to the end of the hash entry. // The format of a salted entry is: $dynamic_#$hash$SALT_VAL[$$2SALT2_VAL] // salt 64 bytes, // salt2 64 bytes, // salt signature $ 1 byte // salt2 signature $$2 3 bytes // null termination 1 byte. This this allows 2 64 byte salt's. // Note, we now have up to 10 of these. #define SALT_SIZE (64*4+1+3+1) #define SALT_ALIGN MEM_ALIGN_WORD // slots to do 24 'tests'. Note, we copy the // same 3 tests over and over again. Simply to validate that // tests use 'multiple' blocks. static struct fmt_tests dynamic_tests[] = { {NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL}, {NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL}, {NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL},{NULL} }; #ifdef SIMD_COEF_32 // SSE2 works only with 54 byte keys. Thus, md5(md5($p).md5($s)) can NOT be used // with the SSE2, since that final md5 will be over a 64 byte block of data. static union SIMD_inpup { uint32_t w[(64*SIMD_COEF_32)/sizeof(uint32_t)]; unsigned char c[64*SIMD_COEF_32]; } *input_buf, *input_buf2; static union SIMD_crypt { uint32_t w[(BINARY_SIZE*SIMD_COEF_32)/sizeof(uint32_t)]; unsigned char c[BINARY_SIZE*SIMD_COEF_32]; } *crypt_key, *crypt_key2; static unsigned int (*total_len)[SIMD_COEF_32]; static unsigned int (*total_len2)[SIMD_COEF_32]; #define MMX_INP_BUF_SZ (sizeof(input_buf[0]) *BLOCK_LOOPS) #define MMX_INP_BUF2_SZ (sizeof(input_buf2[0])*BLOCK_LOOPS) #define MMX_TOT_LEN_SZ (sizeof(*total_len) *BLOCK_LOOPS) #define MMX_TOT_LEN2_SZ (sizeof(*total_len2)*BLOCK_LOOPS) #define MMX_INP_BUF_SZ (sizeof(input_buf[0]) *BLOCK_LOOPS) #define MMX_CRYPT_KEY_SZ (sizeof(crypt_key[0]) *BLOCK_LOOPS+sizeof(crypt_key[0])) #define MMX_CRYPT_KEY2_SZ (sizeof(crypt_key2[0])*BLOCK_LOOPS) #endif #define FLAT_INP_BUF_SZ (sizeof(MD5_IN)*(MAX_KEYS_PER_CRYPT_X86>>MD5_X2)) #define FLAT_TOT_LEN_SZ (sizeof(unsigned int)*(MAX_KEYS_PER_CRYPT_X86)) MD5_OUT *crypt_key_X86; MD5_OUT *crypt_key2_X86; MD5_IN *input_buf_X86; MD5_IN *input_buf2_X86; unsigned int *total_len_X86; unsigned int *total_len2_X86; BIG_HASH_OUT dynamic_BHO[4]; static int keys_dirty; // We store the salt here static unsigned char *cursalt; // length of salt (so we don't have to call strlen() all the time. static int saltlen; int get_dynamic_fmt_saltlen() { return saltlen; } // This array is for the 2nd salt in the hash. I know of no hashes with double salts, // but test type dynamic_16 (which is 'fake') has 2 salts, and this is the data/code to // handle double salts. static unsigned char *cursalt2; static int saltlen2; static unsigned char *username; static int usernamelen; static unsigned char *flds[10]; static int fld_lens[10]; const char *dynamic_itoa16 = itoa16; #if !defined (_DEBUG) #define itoa16_w2 __Dynamic_itoa_w2 #define itoa16_w2_u __Dynamic_itoa_w2_u #define itoa16_w2_l __Dynamic_itoa_w2_l #endif unsigned short itoa16_w2_u[256], itoa16_w2_l[256]; unsigned short *itoa16_w2=itoa16_w2_l; // array of the keys. Also lengths of the keys. NOTE if store_keys_in_input, then the // key array will NOT be used (but the length array still is). #ifndef MAX_KEYS_PER_CRYPT #define MAX_KEYS_PER_CRYPT MAX_KEYS_PER_CRYPT_X86 #endif #ifndef PLAINTEXT_LENGTH #define PLAINTEXT_LENGTH PLAINTEXT_LENGTH_X86 #endif #define EFFECTIVE_MKPC (MAX_KEYS_PER_CRYPT > MAX_KEYS_PER_CRYPT_X86 ? MAX_KEYS_PER_CRYPT : MAX_KEYS_PER_CRYPT_X86) #define EFFECTIVE_MAX_LENGTH (PLAINTEXT_LENGTH > PLAINTEXT_LENGTH_X86 ? PLAINTEXT_LENGTH : PLAINTEXT_LENGTH_X86) // Used to compute length of each string to clean. This is needed, since we have to clean a little more than // just the length, IF we are cleaning strings that are in different endianity than native for the CPU. // This is seen on SHA224 (etc) on Intel, or MD5 of BE systems. We still try to clean 'only' as much as // we need to, but that is usually MORE than what the length of the stored string is. 8 gives us 7 byte spill // over, plus 1 byte for the 0x80 #define COMPUTE_EX_LEN(a) ( (a) > (sizeof(input_buf_X86[0].x1.b)-8) ) ? sizeof(input_buf_X86[0].x1.b) : ((a)+8) // this new 'ENCODED_EFFECTIVE_MAX_LENGTH' needed, since we grab up to 125 bytes of data WHEN in -encode:utf8 mode for a unicode format. #define ENCODED_EFFECTIVE_MAX_LENGTH (EFFECTIVE_MAX_LENGTH > 125 ? EFFECTIVE_MAX_LENGTH : 125) static char saved_key[EFFECTIVE_MKPC][ENCODED_EFFECTIVE_MAX_LENGTH + 1]; static int saved_key_len[EFFECTIVE_MKPC]; // this is the max generic location we should target. This keeps us from having blown MD buffers or overwrite // when in utf8->utf16 mode, where we are handling data that likely is larger than we should handle. We have to // handle this larger data, so that we get as many strings with 1 byte utf8 that would convert to data that would // blow our buffers. But we want as many as possible for the 2 and 3 byte utf data. #define MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE (256-17) // Used in 'get_key' if we are running in store_keys_in_input mode static char out[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; // This is the GLOBAL count of keys. ALL of the primitives which deal with a count // will read from this variable. #if !defined (_DEBUG) #define m_count m_Dynamic_Count #endif unsigned int m_count; // If we are run in 'specific' mode (say, -format=dynamic -subformat=dynamic_0, then we // want to 'allow' bare hashes to be 'valid'. This is how we will do this. We have a boolean // that if set to true, we will perform a 1 time check within the valid function. If at // that time we find out that we are cracking (or showing, etc) that we will accept lines // that are either format of $dynamic_0$hhhhhh...32 or simply in the format of hhhhhhh..32 int dynamic_allow_rawhash_fixup = 0; // this one IS in the private_dat, but since it is accessed SO much, we pull it // out prior to 'internal' processing. The others are accessed right from // the structure, since there are accessed infrequently enough to not matter. static int dynamic_use_sse; // If set to 1, then do unicode conversion is many string setting functions. static int *md5_unicode_convert; #if !defined (_DEBUG) #define curdat Dynamic_curdat #endif private_subformat_data curdat; // Helper function that loads out 256 unsigned short array that does base-16 conversions // This function is called at the 'validation' call that loads our preloads (i.e. only // called one time, pre 'run' (but will be called multiple times when benchmarking, but // will NOT impact benchmark times.) Loading a word at a time (2 bytes), sped up // the overall run time of dynamic_2 almost 5%, thus this conversion is MUCH faster than // the fastest byte by byte I could put together. I tested several ways to access this // array of unsigned shorts, and the best way was a 2 step method into an array of long // integer pointers (thus, load 1/2 the 32 bit word, then the other 1/2, into a 32 bit word). /********************************************************************************* ********************************************************************************* * Start of the 'normal' *_fmt code for md5-gen ********************************************************************************* *********************************************************************************/ char *RemoveHEX(char *output, char *input) { char *cpi = input; char *cpo = output; char *cpH = strstr(input, "$HEX$"); if (!cpH) { // should never get here, we have a check performed before this function is called. strcpy(output, input); return output; } while (cpi < cpH) *cpo++ = *cpi++; *cpo++ = *cpi; cpi += 5; while (*cpi) { if (*cpi == '0' && cpi[1] == '0') { strcpy(output, input); return output; } if (atoi16[ARCH_INDEX(*cpi)] != 0x7f && atoi16[ARCH_INDEX(cpi[1])] != 0x7f) { *cpo++ = atoi16[ARCH_INDEX(*cpi)]*16 + atoi16[ARCH_INDEX(cpi[1])]; cpi += 2; } else if (*cpi == '$') { while (*cpi && strncmp(cpi, "$HEX$", 5)) { *cpo++ = *cpi++; } if (!strncmp(cpi, "$HEX$", 5)) { *cpo++ = *cpi; cpi += 5; } } else { strcpy(output, input); return output; } } *cpo = 0; return output; } /********************************************************************************* * Detects a 'valid' md5-gen format. This function is NOT locked to anything. It * takes its detection logic from the provided fmt_main pointer. Within there, * is a 'private' data pointer. When john first loads the md5-gen, it calls a * function which builds proper 'private' data for EACH type of md5-gen. Then * john will call valid on EACH of those formats, asking each one if a string is * valid. Each format has a 'private' properly setup data object. *********************************************************************************/ static int valid(char *ciphertext, struct fmt_main *pFmt) { unsigned int i, cipherTextLen; char *cp, fixed_ciphertext[1024]; private_subformat_data *pPriv = pFmt->private.data; if (!pPriv) return 0; if (strncmp(ciphertext, pPriv->dynamic_WHICH_TYPE_SIG, strlen(pPriv->dynamic_WHICH_TYPE_SIG))) return 0; /* Quick cancel of huge lines (eg. zip archives) */ if (strnlen(ciphertext, LINE_BUFFER_SIZE + 1) > LINE_BUFFER_SIZE) return 0; // this is now simply REMOVED totally, if we detect it. Doing this solves MANY other problems // of leaving it in there. The ONLY problem we still have is NULL bytes. if (strstr(ciphertext, "$HEX$")) { if (strnlen(ciphertext, sizeof(fixed_ciphertext) + 1) < sizeof(fixed_ciphertext)) ciphertext = RemoveHEX(fixed_ciphertext, ciphertext); } cp = &ciphertext[strlen(pPriv->dynamic_WHICH_TYPE_SIG)]; if (pPriv->dynamic_base64_inout == 1 || pPriv->dynamic_base64_inout == 3 || pPriv->dynamic_base64_inout == 5) { // jgypwqm.JsMssPLiS8YQ00$BaaaaaSX unsigned int len; len = base64_valid_length(cp, pPriv->dynamic_base64_inout==3?e_b64_mime:e_b64_crypt, flg_Base64_MIME_TRAIL_EQ_CNT, 0); if (len < 20 || len > pPriv->dynamic_SALT_OFFSET+4) return 0; if (pPriv->dynamic_FIXED_SALT_SIZE == 0) return !cp[len]; if (pPriv->dynamic_FIXED_SALT_SIZE && cp[len] != '$') return 0; if (pPriv->dynamic_FIXED_SALT_SIZE > 0 && strlen(&cp[len+1]) != pPriv->dynamic_FIXED_SALT_SIZE) return 0; else if (pPriv->dynamic_FIXED_SALT_SIZE < -1 && strlen(&cp[len+1]) > -(pPriv->dynamic_FIXED_SALT_SIZE)) return 0; return 1; } if (pPriv->dynamic_base64_inout == 2) { // h3mJrcH0901pqX/m$alex unsigned int i; for (i = 0; i < 16; ++i) { if (atoi64[ARCH_INDEX(cp[i])] == 0x7F) return 0; } if (pPriv->dynamic_FIXED_SALT_SIZE == 0) return !cp[i]; if (pPriv->dynamic_FIXED_SALT_SIZE && cp[16] != '$') return 0; if (pPriv->dynamic_FIXED_SALT_SIZE > 0 && strlen(&cp[17]) != pPriv->dynamic_FIXED_SALT_SIZE) return 0; else if (pPriv->dynamic_FIXED_SALT_SIZE < -1 && strlen(&cp[17]) > -(pPriv->dynamic_FIXED_SALT_SIZE)) return 0; if (strlen(cp) < 16) return 0; return 1; } if (strlen(cp) < 32) return 0; cipherTextLen = CIPHERTEXT_LENGTH; if (pPriv->dynamic_40_byte_input) { cipherTextLen = 40; } else if (pPriv->dynamic_48_byte_input) { cipherTextLen = 48; } else if (pPriv->dynamic_64_byte_input) { cipherTextLen = 64; } else if (pPriv->dynamic_56_byte_input) { cipherTextLen = 56; } else if (pPriv->dynamic_80_byte_input) { cipherTextLen = 80; } else if (pPriv->dynamic_96_byte_input) { cipherTextLen = 96; } else if (pPriv->dynamic_128_byte_input) { cipherTextLen = 128; } for (i = 0; i < cipherTextLen; i++) { if (atoi16[ARCH_INDEX(cp[i])] == 0x7f) return 0; } if ((pPriv->pSetup->flags&MGF_SALTED) == 0) { if (!cp[cipherTextLen]) return 1; return 0; } if (cp[cipherTextLen] && cp[cipherTextLen] != '$') return 0; // NOTE if looking at this in the future, this was not my fix. if (strlen(&cp[cipherTextLen]) > SALT_SIZE) return 0; // end NOTE. if (pPriv->dynamic_FIXED_SALT_SIZE > 0 && ciphertext[pPriv->dynamic_SALT_OFFSET-1] != '$') return 0; if (pPriv->dynamic_FIXED_SALT_SIZE > 0 && strlen(&ciphertext[pPriv->dynamic_SALT_OFFSET]) != pPriv->dynamic_FIXED_SALT_SIZE) { // first check to see if this salt has left the $HEX$ in the string (i.e. embedded nulls). If so, then // validate length with this in mind. if (!memcmp(&ciphertext[pPriv->dynamic_SALT_OFFSET], "HEX$", 4)) { int len = strlen(&ciphertext[pPriv->dynamic_SALT_OFFSET]); len = (len-4)>>1; if (len != pPriv->dynamic_FIXED_SALT_SIZE) return 0; } else { // check if there is a 'salt-2' or 'username', etc If that is the case, then this is still valid. if (strncmp(&ciphertext[pPriv->dynamic_SALT_OFFSET+pPriv->dynamic_FIXED_SALT_SIZE], "$$", 2)) return 0; } } else if (!regen_salts_options && pPriv->dynamic_FIXED_SALT_SIZE < -1 && strlen(&ciphertext[pPriv->dynamic_SALT_OFFSET]) > -(pPriv->dynamic_FIXED_SALT_SIZE)) { char *cpX; // first check to see if this salt has left the $HEX$ in the string (i.e. embedded nulls). If so, then // validate length with this in mind. if (!memcmp(&ciphertext[pPriv->dynamic_SALT_OFFSET], "HEX$", 4)) { int len = strlen(&ciphertext[pPriv->dynamic_SALT_OFFSET]); len = (len-4)>>1; if (len > -(pPriv->dynamic_FIXED_SALT_SIZE)) return 0; } else { // check if there is a 'salt-2' or 'username', etc If that is the case, then this is still 'valid' cpX = mem_alloc(-(pPriv->dynamic_FIXED_SALT_SIZE) + 3); strnzcpy(cpX, &ciphertext[pPriv->dynamic_SALT_OFFSET], -(pPriv->dynamic_FIXED_SALT_SIZE) + 3); if (!strstr(cpX, "$$")) { MEM_FREE(cpX); return 0; } MEM_FREE(cpX); } } if (pPriv->b2Salts==1 && !strstr(&ciphertext[pPriv->dynamic_SALT_OFFSET-1], "$$2")) return 0; if (pPriv->nUserName && !strstr(&ciphertext[pPriv->dynamic_SALT_OFFSET-1], "$$U")) return 0; if (pPriv->FldMask) { for (i = 0; i < 10; ++i) { if ((pPriv->FldMask & (MGF_FLDx_BIT<<i)) == (MGF_FLDx_BIT<<i)) { char Fld[8]; sprintf(Fld, "$$F%d", i); if (!strstr(&ciphertext[pPriv->dynamic_SALT_OFFSET-1], Fld)) return 0; } } } return 1; } static char *FixupIfNeeded(char *ciphertext, private_subformat_data *pPriv); static struct fmt_main *dynamic_Get_fmt_main(int which); static char *HandleCase(char *cp, int caseType); // 'wrapper' functions. These are here, so we can call these functions to work on ALL data (not simply within the // thead, which ONLY wants to work on a subset of the data. These functions should NOT be called by threading // code, EVER. But this functions KNOW what to do. Some actually have threads, others do not need them. #ifdef _OPENMP #ifndef SIMD_COEF_32 const unsigned int OMP_INC = (MD5_X2+1); const unsigned int OMP_MD5_INC = (MD5_X2+1); const unsigned int OMP_MD4_INC = (MD5_X2+1); const unsigned int OMP_SHA1_INC = (MD5_X2+1); #else const unsigned int OMP_INC = (MD5_X2+1); const unsigned int OMP_MD5_INC = (SIMD_PARA_MD5*SIMD_COEF_32); const unsigned int OMP_MD4_INC = (SIMD_PARA_MD4*SIMD_COEF_32); const unsigned int OMP_SHA1_INC = (SIMD_PARA_SHA1*SIMD_COEF_32); #endif // SIMD_COEF_32 #endif // _OPENMP inline static void __nonMP_DynamicFunc__SSEtoX86_switch_output2() { #ifdef _OPENMP DynamicFunc__SSEtoX86_switch_output2(0,m_count,0); #else DynamicFunc__SSEtoX86_switch_output2(); #endif } inline static void __nonMP_DynamicFunc__append_from_last_output2_to_input1_as_base16() { #ifdef _OPENMP DynamicFunc__append_from_last_output2_to_input1_as_base16(0,m_count,0); #else DynamicFunc__append_from_last_output2_to_input1_as_base16(); #endif } void __nonMP_eLargeOut(eLargeOut_t what) { #ifdef _OPENMP unsigned int i; for (i = 1; i < m_ompt; ++i) eLargeOut[i] = what; #endif eLargeOut[0] = what; } void __nonMP_nLargeOff(unsigned val) { #ifdef _OPENMP unsigned int i; for (i = 1; i < m_ompt; ++i) nLargeOff[i] = val; #endif nLargeOff[0] = val; } inline static void md5_unicode_convert_set(int what, int tid) { md5_unicode_convert[tid] = what; } inline static int md5_unicode_convert_get(int tid) { return md5_unicode_convert[tid]; } void __nonMP_md5_unicode_convert(int what) { #ifdef _OPENMP unsigned int i; for (i = 1; i < m_ompt; ++i) md5_unicode_convert[i] = what; #endif md5_unicode_convert[0] = what; } #if !defined (_OPENMP) #define md5_unicode_convert_set(what, tid) md5_unicode_convert_set(what, 0) #define md5_unicode_convert_get(tid) md5_unicode_convert_get(0) #define eLargeOut_set(what, tid) eLargeOut_set(what, 0) #define eLargeOut_get(tid) eLargeOut_get(0) #define nLargeOff_set(val, tid) nLargeOff_set(val, 0) #define nLargeOff_get(tid) nLargeOff_get(0) #endif inline static void __nonMP_DynamicFunc__append_keys2() { #ifdef _OPENMP DynamicFunc__append_keys2(0,m_count,0); #else DynamicFunc__append_keys2(); #endif } static void __possMP_DynamicFunc__crypt2_md5() { #ifdef _OPENMP int i; unsigned int inc = OMP_MD5_INC; // if (dynamic_use_sse!=1) // inc = OMP_INC; #pragma omp parallel for for (i = 0; i < m_count; i += inc) DynamicFunc__crypt2_md5(i,i+inc,omp_get_thread_num()); #else DynamicFunc__crypt2_md5(); #endif } static void __nonMP_DynamicFunc__clean_input() { unsigned int i=0; #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { memset(input_buf, 0, MMX_INP_BUF_SZ); memset(total_len, 0, MMX_TOT_LEN_SZ); return; } #endif for (; i < MAX_KEYS_PER_CRYPT_X86; ++i) { //if (total_len_X86[i]) { #if MD5_X2 if (i&1) memset(input_buf_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len_X86[i])); else #endif memset(input_buf_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len_X86[i])); total_len_X86[i] = 0; //} } return; } static void __nonMP_DynamicFunc__clean_input2() { unsigned int i=0; #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { memset(input_buf2, 0, MMX_INP_BUF2_SZ); memset(total_len2, 0, MMX_TOT_LEN2_SZ); return; } #endif if (curdat.using_flat_buffers_sse2_ok) { memset(total_len2_X86, 0, sizeof(total_len2_X86[0])*MAX_KEYS_PER_CRYPT_X86); return; } for (; i < MAX_KEYS_PER_CRYPT_X86; ++i) { //if (total_len2_X86[i]) { #if MD5_X2 if (i&1) memset(input_buf2_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len2_X86[i])); else #endif memset(input_buf2_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len2_X86[i])); total_len2_X86[i] = 0; //} } return; } static void __nonMP_DynamicFunc__clean_input_full() { #ifdef SIMD_COEF_32 memset(input_buf, 0, MMX_INP_BUF_SZ); memset(total_len, 0, MMX_TOT_LEN_SZ); #endif memset(input_buf_X86, 0, FLAT_INP_BUF_SZ); memset(total_len_X86, 0, FLAT_TOT_LEN_SZ); } static void __nonMP_DynamicFunc__clean_input2_full() { #ifdef SIMD_COEF_32 memset(input_buf2, 0, MMX_INP_BUF2_SZ); memset(total_len2, 0, MMX_TOT_LEN2_SZ); #endif memset(input_buf2_X86, 0, FLAT_INP_BUF_SZ); memset(total_len2_X86, 0, FLAT_TOT_LEN_SZ); } static void __nonMP_DynamicFunc__clean_input_kwik() { #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { memset(total_len, 0, MMX_TOT_LEN_SZ); return; } #endif memset(total_len_X86, 0, FLAT_TOT_LEN_SZ); #if !ARCH_LITTLE_ENDIAN memset(input_buf_X86, 0, FLAT_INP_BUF_SZ); #endif } #ifndef _OPENMP static void __nonMP_DynamicFunc__clean_input2_kwik() { #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { memset(total_len2, 0, MMX_TOT_LEN2_SZ); return; } #endif memset(total_len2_X86, 0, FLAT_TOT_LEN_SZ); #if !ARCH_LITTLE_ENDIAN memset(input_buf2_X86, 0, FLAT_INP_BUF_SZ); #endif } #endif /********************************************************************************* * init() here does nothing. NOTE many formats LINKING into us will have a valid * that DOES do something, but ours does nothing. *********************************************************************************/ static void init(struct fmt_main *pFmt) { private_subformat_data *pPriv = pFmt->private.data; unsigned int i; //fprintf(stderr, "init(%s)\n", pPriv->dynamic_WHICH_TYPE_SIG); /* first off, SAVE the original format structure (owned by JtR). We may need this later */ pPriv->pFmtMain = pFmt; #ifdef _OPENMP m_ompt = omp_get_max_threads(); if (!md5_unicode_convert) { md5_unicode_convert = (int*)mem_calloc(m_ompt, sizeof(int)); eLargeOut = (eLargeOut_t*)mem_calloc(m_ompt, sizeof(eLargeOut_t)); nLargeOff = (unsigned*)mem_calloc(m_ompt, sizeof(unsigned)); for (i = 0; i < m_ompt; ++i) { eLargeOut[i] = eBase16; nLargeOff[i] = 0; } } #else if (!md5_unicode_convert) { md5_unicode_convert = (int*)mem_calloc(1, sizeof(int)); eLargeOut = (eLargeOut_t*)mem_calloc(1, sizeof(eLargeOut_t)); eLargeOut[0] = eBase16; nLargeOff = (unsigned*)mem_calloc(1, sizeof(unsigned)); nLargeOff[0] = 0; } #endif #ifdef SIMD_COEF_32 if (!input_buf) { input_buf = mem_calloc_align(1, MMX_INP_BUF_SZ, MEM_ALIGN_SIMD); total_len = mem_calloc_align(1, MMX_TOT_LEN_SZ, MEM_ALIGN_SIMD); total_len2 = mem_calloc_align(1, MMX_TOT_LEN2_SZ, MEM_ALIGN_SIMD); input_buf2 = mem_calloc_align(1, MMX_INP_BUF2_SZ, MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(1, MMX_CRYPT_KEY_SZ, MEM_ALIGN_SIMD); crypt_key2 = mem_calloc_align(1, MMX_CRYPT_KEY2_SZ, MEM_ALIGN_SIMD); } #endif if (!crypt_key_X86) { crypt_key_X86 = (MD5_OUT *)mem_calloc(((MAX_KEYS_PER_CRYPT_X86>>MD5_X2)+1), sizeof(*crypt_key_X86)); crypt_key2_X86 = (MD5_OUT *)mem_calloc(((MAX_KEYS_PER_CRYPT_X86>>MD5_X2)+1), sizeof(*crypt_key2_X86)); input_buf_X86 = (MD5_IN *)mem_calloc(((MAX_KEYS_PER_CRYPT_X86>>MD5_X2)+1), sizeof(*input_buf_X86)); input_buf2_X86 = (MD5_IN *)mem_calloc(((MAX_KEYS_PER_CRYPT_X86>>MD5_X2)+1), sizeof(*input_buf2_X86)); total_len_X86 = (unsigned int *)mem_calloc((MAX_KEYS_PER_CRYPT_X86+1), sizeof(*total_len_X86)); total_len2_X86 = (unsigned int *)mem_calloc((MAX_KEYS_PER_CRYPT_X86+1), sizeof(*total_len2_X86)); } for (i = 0; i < 4; ++i) dynamic_BHO[i].dat = mem_calloc_align(BLOCK_LOOPS, sizeof(*(dynamic_BHO[0].dat)), MEM_ALIGN_SIMD); gost_init_table(); if (!pPriv || (pPriv->init == 1 && !strcmp(curdat.dynamic_WHICH_TYPE_SIG, pPriv->dynamic_WHICH_TYPE_SIG))) return; __nonMP_DynamicFunc__clean_input_full(); __nonMP_DynamicFunc__clean_input2_full(); // Some builds (omp vs non omp, etc) do not call these functions, so to avoid 'unused' warnings, we simply // call them here. __nonMP_DynamicFunc__clean_input_kwik(); dynamic_RESET(pFmt); if (!pPriv) return; pPriv->init = 1; memcpy(&curdat, pPriv, sizeof(private_subformat_data)); dynamic_use_sse = curdat.dynamic_use_sse; force_md5_ctx = curdat.force_md5_ctx; fmt_Dynamic.params.max_keys_per_crypt = pFmt->params.max_keys_per_crypt; fmt_Dynamic.params.min_keys_per_crypt = pFmt->params.max_keys_per_crypt; if (pFmt->params.min_keys_per_crypt > 64) pFmt->params.min_keys_per_crypt = 64; fmt_Dynamic.params.flags = pFmt->params.flags; fmt_Dynamic.params.format_name = pFmt->params.format_name; fmt_Dynamic.params.algorithm_name = pFmt->params.algorithm_name; fmt_Dynamic.params.benchmark_comment = pFmt->params.benchmark_comment; fmt_Dynamic.params.benchmark_length = pFmt->params.benchmark_length; // we allow for 3 bytes of utf8 data to make up the number of plaintext_length unicode chars. if ( (pFmt->params.flags&FMT_UNICODE) && options.target_enc == UTF_8 ) { //printf("Here pFmt->params.plaintext_length=%d pPriv->pSetup->MaxInputLen=%d\n", pFmt->params.plaintext_length, pPriv->pSetup->MaxInputLen); pFmt->params.plaintext_length = MIN(125, pFmt->params.plaintext_length * 3); } else fmt_Dynamic.params.plaintext_length = pFmt->params.plaintext_length; fmt_Dynamic.params.salt_size = pFmt->params.salt_size; fmt_Dynamic.params.flags = pFmt->params.flags; fmt_Dynamic.methods.cmp_all = pFmt->methods.cmp_all; fmt_Dynamic.methods.cmp_one = pFmt->methods.cmp_one; fmt_Dynamic.methods.cmp_exact = pFmt->methods.cmp_exact; fmt_Dynamic.methods.set_salt = pFmt->methods.set_salt; fmt_Dynamic.methods.salt = pFmt->methods.salt; fmt_Dynamic.methods.salt_hash = pFmt->methods.salt_hash; fmt_Dynamic.methods.split = pFmt->methods.split; fmt_Dynamic.methods.set_key = pFmt->methods.set_key; fmt_Dynamic.methods.get_key = pFmt->methods.get_key; fmt_Dynamic.methods.clear_keys = pFmt->methods.clear_keys; fmt_Dynamic.methods.crypt_all = pFmt->methods.crypt_all; for (i = 0; i < PASSWORD_HASH_SIZES; ++i) { fmt_Dynamic.methods.binary_hash[i] = pFmt->methods.binary_hash[i]; fmt_Dynamic.methods.get_hash[i] = pFmt->methods.get_hash[i]; } #if !MD5_IMM { extern void MD5_std_init(struct fmt_main *pFmt); MD5_std_init(pFmt); } #endif if (curdat.input2_set_len32) { for (i = 0; i < MAX_KEYS_PER_CRYPT_X86; ++i) total_len2_X86[i] = 32; #ifdef SIMD_COEF_32 for (i = 0; i < BLOCK_LOOPS; ++i) { unsigned int j; for (j = 0; j < SIMD_COEF_32; j++) { input_buf2[i].c[GETPOS(32, j)] = 0x80; input_buf2[i].c[GETPOS(57, j)] = 0x1; total_len2[i][j] = 0x20; } } #endif } } static void done(void) { int i; MEM_FREE(total_len2_X86); MEM_FREE(total_len_X86); MEM_FREE(input_buf2_X86); MEM_FREE(input_buf_X86); MEM_FREE(crypt_key2_X86); MEM_FREE(crypt_key_X86); #ifdef SIMD_COEF_32 MEM_FREE(crypt_key2); MEM_FREE(crypt_key); MEM_FREE(input_buf2); MEM_FREE(total_len2); MEM_FREE(total_len); MEM_FREE(input_buf); #endif MEM_FREE(nLargeOff); MEM_FREE(eLargeOut); MEM_FREE(md5_unicode_convert); for (i = 0; i < 4; ++i) MEM_FREE(dynamic_BHO[i].dat); } /********************************************************************************* * This function will add a $dynamic_#$ IF there is not one, and if we have a specific * format requested. Also, it will add things like UserID, Domain, Fld3, Fld4, * Fld5, etc. *********************************************************************************/ static char *prepare(char *split_fields[10], struct fmt_main *pFmt) { private_subformat_data *pPriv = pFmt->private.data; char Tmp[80]; int i; int trim_u=0; char *cpBuilding=split_fields[1]; if (!pPriv) return split_fields[1]; // ANY field[1] longer than 490 will simply be ignored, and returned 'as is'. // the rest of this function makes this assumption. if (!cpBuilding || strnlen(cpBuilding, 491) > 490) return cpBuilding; // mime. We want to strip off ALL trailing '=' characters to 'normalize' them if (pPriv->dynamic_base64_inout == 3 && !strncmp(cpBuilding, "$dynamic_", 9)) { static char ct[496]; int len; char *cp = strchr(&cpBuilding[9], '$'), *cp2; if (!cp) return cpBuilding; ++cp; len = base64_valid_length(cp, e_b64_mime, flg_Base64_MIME_TRAIL_EQ_CNT, 0); if (len && cp[len-1] == '=') { strnzcpy(ct, cpBuilding, cp-cpBuilding+len+1); cp2 = &ct[strlen(ct)-1]; while (*cp2 == '=') *cp2-- = 0; if (cp[len]) strcat(cp2, &cp[len]); cpBuilding = ct; } } if (pFmt->params.salt_size && !strchr(split_fields[1], '$')) { if (!pPriv->nUserName && !pPriv->FldMask && options.regen_lost_salts == 0) return split_fields[1]; } // handle 'older' md5_gen(x) signature, by simply converting to $dynamic_x$ signature // Thus older md5_gen() is a valid input (or from john.pot), but ONLY the newer // $dynamic_x$ will be written out (into .pot, output lines, etc). if (!strncmp(cpBuilding, "md5_gen(", 8)) { static char ct[496]; char *cp = &cpBuilding[8], *cpo = &ct[sprintf(ct, "$dynamic_")]; while (*cp >= '0' && *cp <= '9') *cpo++ = *cp++; *cpo++ = '$'; ++cp; strcpy(cpo, cp); cpBuilding = ct; } // At this point, max length of cpBuilding is 491 (if it was a md5_gen signature) // allow a raw hash, if there is a $u but no salt if (pPriv->nUserName && split_fields[0][0] && !strchr(cpBuilding, '$') && strcmp(split_fields[0], "?")) { static char ct[496]; strcpy(ct, cpBuilding); strcat(ct, "$$U"); cpBuilding = ct; trim_u=1; } cpBuilding = FixupIfNeeded(cpBuilding, pPriv); if (trim_u) cpBuilding[strlen(cpBuilding)-3] = 0; // at this point max length is still < 512. 491 + strlen($dynamic_xxxxx$) is 506 if (strncmp(cpBuilding, "$dynamic_", 9)) { // ok, here we add the 'generic' regen salt code if (options.regen_lost_salts && !strchr(cpBuilding, '$')) { char *cp = load_regen_lost_salt_Prepare(cpBuilding); if (cp) return cp; } return split_fields[1]; } if ( (pPriv->pSetup->flags&MGF_SALTED) == 0) return cpBuilding; /* at this point, we want to convert ANY and all $HEX$hex into values */ /* the reason we want to do this, is so that things read from john.pot file will be in proper 'native' format */ /* the ONE exception to this, is if there is a NULL byte in the $HEX$ string, then we MUST leave that $HEX$ string */ /* alone, and let the later calls in dynamic.c handle them. */ if (strstr(cpBuilding, "$HEX$")) { char *cp, *cpo; int bGood=1; static char ct[512]; strcpy(ct, cpBuilding); cp = strstr(ct, "$HEX$"); cpo = cp; *cpo++ = *cp; cp += 5; while (*cp && bGood) { if (*cp == '0' && cp[1] == '0') { bGood = 0; break; } if (atoi16[ARCH_INDEX(*cp)] != 0x7f && atoi16[ARCH_INDEX(cp[1])] != 0x7f) { *cpo++ = atoi16[ARCH_INDEX(*cp)]*16 + atoi16[ARCH_INDEX(cp[1])]; *cpo = 0; cp += 2; } else if (*cp == '$') { while (*cp && strncmp(cp, "$HEX$", 5)) { *cpo++ = *cp++; } *cpo = 0; if (!strncmp(cp, "$HEX$", 5)) { *cpo++ = *cp; cp += 5; } } else { return split_fields[1]; } } if (bGood) cpBuilding = ct; // if we came into $HEX$ removal, then cpBuilding will always be shorter } // at this point max length is still < 512. 491 + strlen($dynamic_xxxxx$) is 506 if (pPriv->nUserName && !strstr(cpBuilding, "$$U")) { if (split_fields[0] && split_fields[0][0] && strcmp(split_fields[0], "?")) { char *userName=split_fields[0], *cp; static char ct[1024]; // assume field[0] is in format: username OR DOMAIN\\username If we find a \\, then use the username 'following' it. cp = strchr(split_fields[0], '\\'); if (cp) userName = &cp[1]; userName = HandleCase(userName, pPriv->nUserName); snprintf(ct, sizeof(ct), "%s$$U%s", cpBuilding, userName); cpBuilding = ct; } } if (pPriv->FldMask) { for (i = 0; i < 10; ++i) { if (pPriv->FldMask&(MGF_FLDx_BIT<<i)) { sprintf(Tmp, "$$F%d", i); if (split_fields[i] && split_fields[i][0] && strcmp(split_fields[i], "/") && !strstr(cpBuilding, Tmp)) { static char ct[1024]; char ct2[1024]; snprintf(ct2, sizeof(ct2), "%s$$F%d%s", cpBuilding, i, split_fields[i]); strcpy(ct, ct2); cpBuilding = ct; } } } } return cpBuilding; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[1024]; private_subformat_data *pPriv = pFmt->private.data; if (strnlen(ciphertext, 951) > 950) return ciphertext; // mime. We want to strip off ALL trailing '=' characters to 'normalize' them if (pPriv->dynamic_base64_inout == 3 && !strncmp(ciphertext, "$dynamic_", 9)) { static char ct[496]; unsigned int len; char *cp = strchr(&ciphertext[9], '$'), *cp2; if (cp) { ++cp; len = base64_valid_length(cp, e_b64_mime, flg_Base64_MIME_TRAIL_EQ_CNT, 0); if (len && cp[len-1] == '=') { strnzcpy(ct, ciphertext, cp-ciphertext+len+1); cp2 = &ct[strlen(ct)-1]; while (*cp2 == '=') *cp2-- = 0; if (cp[len]) strcat(cp2, &cp[len]); ciphertext = ct; } } } if (!strncmp(ciphertext, "$dynamic", 8)) { if (strstr(ciphertext, "$HEX$")) return RemoveHEX(out, ciphertext); return ciphertext; } if (!strncmp(ciphertext, "md5_gen(", 8)) { ciphertext += 8; do ++ciphertext; while (*ciphertext != ')') ; ++ciphertext; } if (strstr(ciphertext, "$HEX$")) { char *cp = out + sprintf(out, "%s", pPriv->dynamic_WHICH_TYPE_SIG); RemoveHEX(cp, ciphertext); } else snprintf(out, sizeof(out), "%s%s", pPriv->dynamic_WHICH_TYPE_SIG, ciphertext); return out; } // This split unifies case. static char *split_UC(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[1024]; private_subformat_data *pPriv = pFmt->private.data; if (!strncmp(ciphertext, "$dynamic", 8)) { if (strstr(ciphertext, "$HEX$")) RemoveHEX(out, ciphertext); else strcpy(out, ciphertext); } else { if (!strncmp(ciphertext, "md5_gen(", 8)) { ciphertext += 8; do ++ciphertext; while (*ciphertext != ')') ; ++ciphertext; } if (strstr(ciphertext, "$HEX$")) { char *cp = out + sprintf(out, "%s", pPriv->dynamic_WHICH_TYPE_SIG); RemoveHEX(cp, ciphertext); } else sprintf(out, "%s%s", pPriv->dynamic_WHICH_TYPE_SIG, ciphertext); } ciphertext = strchr(&out[8], '$')+1; while (*ciphertext && *ciphertext != '$') { if (*ciphertext >= 'A' && *ciphertext <= 'Z') *ciphertext += 0x20; // ASCII specific, but I really do not care. ++ciphertext; } // printf("%s\n", out); return out; } /********************************************************************************* * Stores the new salt provided into our 'working' salt *********************************************************************************/ static void set_salt(void *salt) { unsigned char *cpsalt; unsigned int todo_bits=0, i, bit; if (!salt || curdat.dynamic_FIXED_SALT_SIZE == 0) { saltlen = 0; return; } #if ARCH_ALLOWS_UNALIGNED cpsalt = *((unsigned char**)salt); #else memcpy(((void*)&(cpsalt)), ((unsigned char **)salt), sizeof(void*)); #endif saltlen = *cpsalt++ - '0'; saltlen <<= 3; saltlen += *cpsalt++ - '0'; #if ARCH_ALLOWS_UNALIGNED if (*((uint32_t*)cpsalt) != 0x30303030) #else if (memcmp(cpsalt, "0000", 4)) #endif { // this is why we used base-8. Takes an extra byte, but there is NO conditional // logic, building this number, and no multiplication. We HAVE added one conditional // check, to see if we can skip the entire load, if it is 0000. todo_bits = *cpsalt++ - '0'; todo_bits <<= 3; todo_bits += *cpsalt++ - '0'; todo_bits <<= 3; todo_bits += *cpsalt++ - '0'; todo_bits <<= 3; todo_bits += *cpsalt++ - '0'; } else cpsalt += 4; cursalt = cpsalt; if (!todo_bits) return; cpsalt += saltlen; if (todo_bits & 1) { todo_bits ^= 1; // clear that bit. saltlen2 = *cpsalt++; cursalt2 = cpsalt; if (todo_bits == 0) return; cpsalt += saltlen2; } if (todo_bits & 2) { todo_bits ^= 2; // clear that bit. usernamelen = *cpsalt++; username = cpsalt; if (todo_bits == 0) return; cpsalt += usernamelen; } bit = 4; for (i = 0; i < 10; ++i, bit<<=1) { if (todo_bits & bit) { todo_bits ^= bit; // clear that bit. fld_lens[i] = *cpsalt++; flds[i] = cpsalt; if (todo_bits == 0) return; cpsalt += fld_lens[i]; } } } /********************************************************************************* * Sets this key. It will either be dropped DIRECTLY into the input buffer * number 1, or put into an array of keys. Which one happens depends upon * HOW the generic functions were laid out for this type. Not all types can * load into the input. If not they MUST use the key array. Using the input * buffer is faster, when it can be safely done. *********************************************************************************/ static void set_key(char *key, int index) { unsigned int len; //printf("idx=%d key=%s\n", index, key); #ifdef SIMD_COEF_32 if (curdat.store_keys_in_input==2) dynamic_use_sse = 3; else if (curdat.md5_startup_in_x86) dynamic_use_sse = 2; else if (dynamic_use_sse==2) dynamic_use_sse = 1; #endif if (curdat.nPassCase>1) key = HandleCase(key, curdat.nPassCase); // Ok, if the key is in unicode/utf8, we switch it here one time, and are done with it. if (curdat.store_keys_in_input) { #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { // code derived from rawMD5_fmt_plug.c code from magnum #if ARCH_ALLOWS_UNALIGNED const uint32_t *key32 = (uint32_t*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint32_t)); const uint32_t *key32 = is_aligned(key, sizeof(uint32_t)) ? (uint32_t*)key : (uint32_t*)strcpy(buf_aligned, key); #endif unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); uint32_t *keybuffer = &input_buf[idx].w[index&(SIMD_COEF_32-1)]; uint32_t *keybuf_word = keybuffer; unsigned int len; uint32_t temp; len = 0; while((temp = *key32++) & 0xff) { if (!(temp & 0xff00)) { *keybuf_word = (temp & 0xff) | (0x80 << 8); ++len; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = (temp & 0xffff) | (0x80 << 16); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = temp | (0x80U << 24); len+=3; goto key_cleaning; } *keybuf_word = temp; len += 4; keybuf_word += SIMD_COEF_32; } *keybuf_word = 0x80; key_cleaning: keybuf_word += SIMD_COEF_32; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } keybuffer[14*SIMD_COEF_32] = len << 3; return; } #endif len = strlen(key); if (len > 110) // we never do UTF-8 -> UTF-16 in this mode len = 110; // if (index==0) { // we 'have' to use full clean here. NOTE 100% sure why, but 10 formats fail if we do not. // __nonMP_DynamicFunc__clean_input_full(); // } #if MD5_X2 if (index & 1) memcpy(input_buf_X86[index>>MD5_X2].x2.b2, key, len); else #endif memcpy(input_buf_X86[index>>MD5_X2].x1.b, key, len); saved_key_len[index] = total_len_X86[index] = len; } else { len = strlen(key); if (len > 110 && !(fmt_Dynamic.params.flags & FMT_UNICODE)) len = 110; // if (index==0) { // __nonMP_DynamicFunc__clean_input_full(); // } keys_dirty = 1; memcpy(((char*)(saved_key[index])), key, len); saved_key_len[index] = len; } } static void clear_keys(void) { #ifdef SIMD_COEF_32 if (curdat.pSetup->flags & MGF_FULL_CLEAN_REQUIRED) { __nonMP_DynamicFunc__clean_input_full(); return; } if (curdat.store_keys_in_input==1 || curdat.store_keys_in_input==3) return; if (curdat.md5_startup_in_x86) __nonMP_DynamicFunc__clean_input_full(); // This clean was causing failures (dirty buffers left) for dyna_51, 61 and formspring. // once commented out, dyna fully passes. I see no reason to keep this here at all. // else // __nonMP_DynamicFunc__clean_input_kwik(); #else __nonMP_DynamicFunc__clean_input_full(); #endif } /********************************************************************************* * Returns the key. NOTE how it gets it depends upon if we are storing * into the array of keys (there we simply return it), or if we are * loading into input buffer #1. If in input buffer, we have to re-create * the key, prior to returning it. *********************************************************************************/ static char *get_key(int index) { if (curdat.store_keys_in_input) { unsigned int i; unsigned char *cp; #ifdef SIMD_COEF_32 //if (dynamic_use_sse==1) { // Note, if we are not in if (dynamic_use_sse && !curdat.md5_startup_in_x86) { unsigned int s; unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); //if (curdat.store_keys_in_input && dynamic_use_sse==1) // s = saved_key_len[index]; // NOTE, we now have to get the length from the buffer, we do NOT store it into a saved_key_len buffer. uint32_t *keybuffer = &input_buf[idx].w[index&(SIMD_COEF_32-1)]; s = keybuffer[14*SIMD_COEF_32] >> 3; for (i=0;i<s;i++) out[i] = input_buf[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; out[i] = 0; return (char*)out; } #endif #if MD5_X2 if (index & 1) cp = input_buf_X86[index>>MD5_X2].x2.B2; else #endif cp = input_buf_X86[index>>MD5_X2].x1.B; for (i=0;i<saved_key_len[index];++i) out[i] = cp[i]; out[i] = 0; return (char*)out; } else { saved_key[index][saved_key_len[index]] = '\0'; return saved_key[index]; } } /********************************************************************************* * Looks for ANY key that was cracked. *********************************************************************************/ static int cmp_all(void *binary, int count) { unsigned int i; #ifdef SIMD_COEF_32 unsigned int j; if (dynamic_use_sse&1) { unsigned int cnt = ( ((unsigned int)count+SIMD_COEF_32-1)/SIMD_COEF_32); for (i = 0; i < cnt; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) if ( *((uint32_t *)binary) == crypt_key[i].w[j]) return 1; } return 0; } #endif for (i = 0; i < count; i++) { #if MD5_X2 if (i&1) { if (!(((uint32_t *)binary)[0] - crypt_key_X86[i>>MD5_X2].x2.w2[0])) return 1; } else #endif if (!(((uint32_t *)binary)[0] - crypt_key_X86[i>>MD5_X2].x1.w[0])) return 1; } return 0; } #if ARCH_LITTLE_ENDIAN #define MASK_4x6 0x00ffffff #else #define MASK_4x6 0xffffff00 #endif static int cmp_all_64_4x6(void *binary, int count) { unsigned int i; #ifdef SIMD_COEF_32 unsigned int j; if (dynamic_use_sse==1) { unsigned int cnt = ( ((unsigned int)count+SIMD_COEF_32-1)/SIMD_COEF_32); for (i = 0; i < cnt; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) if ( *((uint32_t *)binary) == (crypt_key[i].w[j] & MASK_4x6)) return 1; } return 0; } #endif for (i = 0; i < count; i++) { #if MD5_X2 if (i&1) { if (!(((uint32_t *)binary)[0] - (crypt_key_X86[i>>MD5_X2].x2.w2[0]&MASK_4x6))) return 1; } else #endif if (!(((uint32_t *)binary)[0] - (crypt_key_X86[i>>MD5_X2].x1.w[0]&MASK_4x6))) return 1; } return 0; } /********************************************************************************* * In this code, we always do exact compare, so if this function is called, it * simply returns true. *********************************************************************************/ static int cmp_exact(char *binary, int index) { return 1; } /********************************************************************************* * There was 'something' that was possibly hit. Now john will ask us to check * each one of the data items, for an 'exact' match. *********************************************************************************/ static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); if ( (((uint32_t *)binary)[0] == ((uint32_t *)&(crypt_key[idx].c))[0*SIMD_COEF_32+(index&(SIMD_COEF_32-1))]) && (((uint32_t *)binary)[1] == ((uint32_t *)&(crypt_key[idx].c))[1*SIMD_COEF_32+(index&(SIMD_COEF_32-1))]) && (((uint32_t *)binary)[2] == ((uint32_t *)&(crypt_key[idx].c))[2*SIMD_COEF_32+(index&(SIMD_COEF_32-1))]) && (((uint32_t *)binary)[3] == ((uint32_t *)&(crypt_key[idx].c))[3*SIMD_COEF_32+(index&(SIMD_COEF_32-1))])) return 1; return 0; } #endif #if MD5_X2 if (index & 1) { if ( (((uint32_t *)binary)[0] == crypt_key_X86[index>>MD5_X2].x2.w2[0] ) && (((uint32_t *)binary)[1] == crypt_key_X86[index>>MD5_X2].x2.w2[1] ) && (((uint32_t *)binary)[2] == crypt_key_X86[index>>MD5_X2].x2.w2[2] ) && (((uint32_t *)binary)[3] == crypt_key_X86[index>>MD5_X2].x2.w2[3] ) ) return 1; return 0; } #endif if ( (((uint32_t *)binary)[0] == crypt_key_X86[index>>MD5_X2].x1.w[0] ) && (((uint32_t *)binary)[1] == crypt_key_X86[index>>MD5_X2].x1.w[1] ) && (((uint32_t *)binary)[2] == crypt_key_X86[index>>MD5_X2].x1.w[2] ) && (((uint32_t *)binary)[3] == crypt_key_X86[index>>MD5_X2].x1.w[3] ) ) return 1; return 0; } static int cmp_one_64_4x6(void *binary, int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); if ( (((uint32_t *)binary)[0] == (((uint32_t *)&(crypt_key[idx].c))[0*SIMD_COEF_32+(index&(SIMD_COEF_32-1))] & MASK_4x6)) && (((uint32_t *)binary)[1] == (((uint32_t *)&(crypt_key[idx].c))[1*SIMD_COEF_32+(index&(SIMD_COEF_32-1))] & MASK_4x6)) && (((uint32_t *)binary)[2] == (((uint32_t *)&(crypt_key[idx].c))[2*SIMD_COEF_32+(index&(SIMD_COEF_32-1))] & MASK_4x6)) && (((uint32_t *)binary)[3] == (((uint32_t *)&(crypt_key[idx].c))[3*SIMD_COEF_32+(index&(SIMD_COEF_32-1))] & MASK_4x6))) return 1; return 0; } #endif #if MD5_X2 if (index & 1) { if ( (((uint32_t*)binary)[0] == (crypt_key_X86[index>>MD5_X2].x2.w2[0] & MASK_4x6)) && (((uint32_t*)binary)[1] == (crypt_key_X86[index>>MD5_X2].x2.w2[1] & MASK_4x6)) && (((uint32_t*)binary)[2] == (crypt_key_X86[index>>MD5_X2].x2.w2[2] & MASK_4x6)) && (((uint32_t*)binary)[3] == (crypt_key_X86[index>>MD5_X2].x2.w2[3] & MASK_4x6)) ) return 1; return 0; } #endif if ( (((uint32_t*)binary)[0] == (crypt_key_X86[index>>MD5_X2].x1.w[0] & MASK_4x6)) && (((uint32_t*)binary)[1] == (crypt_key_X86[index>>MD5_X2].x1.w[1] & MASK_4x6)) && (((uint32_t*)binary)[2] == (crypt_key_X86[index>>MD5_X2].x1.w[2] & MASK_4x6)) && (((uint32_t*)binary)[3] == (crypt_key_X86[index>>MD5_X2].x1.w[3] & MASK_4x6)) ) return 1; return 0; } /********************************************************************************* ********************************************************************************* * This is the real 'engine'. It simply calls functions one * at a time from the array of functions. ********************************************************************************* *********************************************************************************/ static int crypt_all(int *pcount, struct db_salt *salt) { // set m_count. This is our GLOBAL value, used by ALL of the script functions to know how // many keys are loaded, and how much work we do. m_count = *pcount; __nonMP_eLargeOut(eBase16); __nonMP_nLargeOff(0); #ifdef SIMD_COEF_32 // If this format is MMX built, but is supposed to start in X86 (but be switchable), then we // set that value here. if (curdat.store_keys_in_input==2) dynamic_use_sse = 3; else if (curdat.md5_startup_in_x86) dynamic_use_sse = 2; else if (dynamic_use_sse==2) dynamic_use_sse = 1; #endif __nonMP_md5_unicode_convert(0); if (curdat.dynamic_base16_upcase) { dynamic_itoa16 = itoa16u; itoa16_w2 = itoa16_w2_u; } else { dynamic_itoa16 = itoa16; itoa16_w2 = itoa16_w2_l; } // There may have to be some 'prelim' work done with the keys. This is so that if we 'know' that keys were // loaded into the keys[] array, but that we should do something like md5 and base-16 put them into an // input slot, then we do that FIRST, prior to calling the script functions. Thus for a format such as // md5(md5($p).$s) we could md5 the pass, and base-16 put it into a input buffer. Then when john sets salt // and calls crypt all, the crypt script would simply set the input len to 32, append the salt and call a // single crypt. That eliminates almost 1/2 of the calls to md5_crypt() for the format show in this example. if (keys_dirty) { if (curdat.store_keys_normal_but_precompute_hash_to_output2) { keys_dirty = 0; if (curdat.pSetup->flags & MGF_FULL_CLEAN_REQUIRED2) __nonMP_DynamicFunc__clean_input2_full(); else __nonMP_DynamicFunc__clean_input2(); if (curdat.store_keys_in_input_unicode_convert) __nonMP_md5_unicode_convert(1); __nonMP_DynamicFunc__append_keys2(); __nonMP_md5_unicode_convert(0); //if (curdat.using_flat_buffers_sse2_ok) { if (curdat.dynamic_use_sse == 0) { if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1) { #ifdef _OPENMP #define CASE(H) case MGF__##H: DynamicFunc__##H##_crypt_input2_overwrite_input1(0,m_count,0); break #else #define CASE(H) case MGF__##H: DynamicFunc__##H##_crypt_input2_overwrite_input1(); break #endif switch(curdat.store_keys_normal_but_precompute_hash_to_output2_base16_type) { CASE(MD5); CASE(MD4); CASE(SHA1); CASE(SHA224); CASE(SHA256); CASE(SHA384); CASE(SHA512); CASE(GOST); CASE(WHIRLPOOL); CASE(Tiger); CASE(RIPEMD128); CASE(RIPEMD160); CASE(RIPEMD256); CASE(RIPEMD320); CASE(HAVAL128_3); CASE(HAVAL128_4); CASE(HAVAL128_5); CASE(HAVAL160_3); CASE(HAVAL160_4); CASE(HAVAL160_5); CASE(HAVAL192_3); CASE(HAVAL192_4); CASE(HAVAL192_5); CASE(HAVAL224_3); CASE(HAVAL224_4); CASE(HAVAL224_5); CASE(HAVAL256_3); CASE(HAVAL256_4); CASE(HAVAL256_5); CASE(MD2); CASE(PANAMA); CASE(SKEIN224); CASE(SKEIN256); CASE(SKEIN384); CASE(SKEIN512); CASE(SHA3_224); CASE(SHA3_256); CASE(SHA3_384); CASE(SHA3_512); CASE(KECCAK_256); CASE(KECCAK_512); // LARGE_HASH_EDIT_POINT } } else if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX) { unsigned int i; for (i = 0; i < m_count; ++i) total_len_X86[i] = curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX; #undef CASE #ifdef _OPENMP #define CASE(H) case MGF__##H: DynamicFunc__##H##_crypt_input2_append_input1(0,m_count,0); break #else #define CASE(H) case MGF__##H: DynamicFunc__##H##_crypt_input2_append_input1(); break #endif switch(curdat.store_keys_normal_but_precompute_hash_to_output2_base16_type) { CASE(MD5); CASE(MD4); CASE(SHA1); CASE(SHA224); CASE(SHA256); CASE(SHA384); CASE(SHA512); CASE(GOST); CASE(WHIRLPOOL); CASE(Tiger); CASE(RIPEMD128); CASE(RIPEMD160); CASE(RIPEMD256); CASE(RIPEMD320); CASE(HAVAL128_3); CASE(HAVAL128_4); CASE(HAVAL128_5); CASE(HAVAL160_3); CASE(HAVAL160_4); CASE(HAVAL160_5); CASE(HAVAL192_3); CASE(HAVAL192_4); CASE(HAVAL192_5); CASE(HAVAL224_3); CASE(HAVAL224_4); CASE(HAVAL224_5); CASE(HAVAL256_3); CASE(HAVAL256_4); CASE(HAVAL256_5); CASE(MD2); CASE(PANAMA); CASE(SKEIN224); CASE(SKEIN256); CASE(SKEIN384); CASE(SKEIN512); CASE(SHA3_224); CASE(SHA3_256); CASE(SHA3_384); CASE(SHA3_512); CASE(KECCAK_256); CASE(KECCAK_512); // LARGE_HASH_EDIT_POINT } } else { // calls 'old' code (ossl, sorry :( We should FIND and remove any format // written this way, if it is __possMP_DynamicFunc__crypt2_md5(); } } else { __possMP_DynamicFunc__crypt2_md5(); if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1) { if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1==2) __nonMP_DynamicFunc__SSEtoX86_switch_output2(); __nonMP_DynamicFunc__clean_input(); __nonMP_DynamicFunc__append_from_last_output2_to_input1_as_base16(); } } } } // Ok, now we 'run' the script. We simply call 1 function right after the other. // ALL functions are void f(void). They use the globals: // input_buf1[] input_buf2[] (requires thread safety) // total_len1[] total_len2[] (requires thread safety) // crypt1[] crypt2[] (requires thread safety) // md5_unicode_convert (requires thread safety, had to change to array) // saved_key[] (const?) // saved_key_len[] (const) // cursalt, cursalt2 (const) // saltlen, saltlen2 (const) // m_count (const) // nConsts (const) // Consts[], ConstsLen[] (const) // Since this array is in a structure, we assign a simple pointer to it // before walking. Trivial improvement, but every cycle counts :) { #ifdef _OPENMP if ((curdat.pFmtMain->params.flags & FMT_OMP) == FMT_OMP) { int j; unsigned int inc = (m_count+m_ompt-1) / m_ompt; //printf("maxkeys=%d m_count=%d inc1=%d granularity=%d inc2=%d\n", curdat.pFmtMain->params.max_keys_per_crypt, m_count, inc, curdat.omp_granularity, ((inc + curdat.omp_granularity-1)/curdat.omp_granularity)*curdat.omp_granularity); inc = ((inc + curdat.omp_granularity-1)/curdat.omp_granularity)*curdat.omp_granularity; #pragma omp parallel for shared(curdat, inc, m_count) for (j = 0; j < m_count; j += inc) { unsigned int i; unsigned int top=j+inc; /* The last block may 'appear' to have more keys than we have in the entire buffer space. This is due to the granularity. If so, reduce that last one to stop at end of our buffers. NOT doing this is causes a huge buffer overflow. */ if (top > curdat.pFmtMain->params.max_keys_per_crypt) top = curdat.pFmtMain->params.max_keys_per_crypt; // we now run a full script in this thread, using only a subset of // the data, from [j,top) The next thread will run from [top,top+inc) // each thread will take the next inc values, until we get to m_count for (i = 0; curdat.dynamic_FUNCTIONS[i]; ++i) (*(curdat.dynamic_FUNCTIONS[i]))(j,top,omp_get_thread_num()); } } else { unsigned int i; // same code (almost), but without the threads. for (i = 0; curdat.dynamic_FUNCTIONS[i]; ++i) (*(curdat.dynamic_FUNCTIONS[i]))(0,m_count,0); } #else unsigned int i; for (i = 0; curdat.dynamic_FUNCTIONS[i]; ++i) { (*(curdat.dynamic_FUNCTIONS[i]))(); #if 0 // Dump state (for debugging help) if (i==0) printf("\npassword=%.*s\n", saved_key_len[0], saved_key[0]); printf("\nState after function: %s\n", dynamic_Find_Function_Name(curdat.dynamic_FUNCTIONS[i])); // dump input 1 #ifdef SIMD_COEF_32 dump_stuff_mmx_msg("input_buf[0]", input_buf[0].c, 64, 0); dump_stuff_mmx_msg("input_buf[1]", input_buf[0].c, 64, 1); dump_stuff_mmx_msg("input_buf[2]", input_buf[0].c, 64, 2); dump_stuff_mmx_msg("input_buf[3]", input_buf[0].c, 64, 3); #endif printf("input_buf86[0] : %*.*s\n", total_len_X86[0],total_len_X86[0],input_buf_X86[0].x1.b); printf("input_buf86[1] : %*.*s\n", total_len_X86[1],total_len_X86[1],input_buf_X86[1].x1.b); printf("input_buf86[2] : %*.*s\n", total_len_X86[2],total_len_X86[2],input_buf_X86[2].x1.b); printf("input_buf86[3] : %*.*s\n", total_len_X86[3],total_len_X86[3],input_buf_X86[3].x1.b); // dump crypt 1 #ifdef SIMD_COEF_32 dump_stuff_mmx_msg("crypt_key[0]", crypt_key[0].c, 16, 0); dump_stuff_mmx_msg("crypt_key[1]", crypt_key[0].c, 16, 1); dump_stuff_mmx_msg("crypt_key[2]", crypt_key[0].c, 16, 2); dump_stuff_mmx_msg("crypt_key[3]", crypt_key[0].c, 16, 3); #endif dump_stuff_be_msg("crypt_key_X86[0]", crypt_key_X86[0].x1.b, 16); dump_stuff_be_msg("crypt_key_X86[1]", crypt_key_X86[1].x1.b, 16); dump_stuff_be_msg("crypt_key_X86[2]", crypt_key_X86[2].x1.b, 16); dump_stuff_be_msg("crypt_key_X86[3]", crypt_key_X86[3].x1.b, 16); // dump input 2 #ifdef SIMD_COEF_32 dump_stuff_mmx_msg("input_buf2[0]", input_buf2[0].c, 64, 0); dump_stuff_mmx_msg("input_buf2[1]", input_buf2[0].c, 64, 1); dump_stuff_mmx_msg("input_buf2[2]", input_buf2[0].c, 64, 2); dump_stuff_mmx_msg("input_buf2[3]", input_buf2[0].c, 64, 3); #endif printf("input2_buf86[0] : %*.*s\n", total_len2_X86[0],total_len2_X86[0],input_buf2_X86[0].x1.b); printf("input2_buf86[1] : %*.*s\n", total_len2_X86[1],total_len2_X86[1],input_buf2_X86[1].x1.b); printf("input2_buf86[2] : %*.*s\n", total_len2_X86[2],total_len2_X86[2],input_buf2_X86[2].x1.b); printf("input2_buf86[3] : %*.*s\n", total_len2_X86[3],total_len2_X86[3],input_buf2_X86[3].x1.b); // dump crypt 2 #ifdef SIMD_COEF_32 dump_stuff_mmx_msg("crypt_key2[0]", crypt_key2[0].c, 16, 0); dump_stuff_mmx_msg("crypt_key2[1]", crypt_key2[0].c, 16, 1); dump_stuff_mmx_msg("crypt_key2[2]", crypt_key2[0].c, 16, 2); dump_stuff_mmx_msg("crypt_key2[3]", crypt_key2[0].c, 16, 3); #endif dump_stuff_be_msg("crypt_key2_X86[0]", crypt_key2_X86[0].x1.b, 16); dump_stuff_be_msg("crypt_key2_X86[1]", crypt_key2_X86[1].x1.b, 16); dump_stuff_be_msg("crypt_key2_X86[2]", crypt_key2_X86[2].x1.b, 16); dump_stuff_be_msg("crypt_key2_X86[3]", crypt_key2_X86[3].x1.b, 16); #endif } #endif } return m_count; } /********************************************************************************* * 'normal' hashing functions *********************************************************************************/ extern char *MD5_DumpHexStr(void *p); #if !ARCH_LITTLE_ENDIAN // the lower 8 bits is zero on the binary (but filled in on the hash). We need to dump the low 8 static int binary_hash_0_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_0; } static int binary_hash_1_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_1; } static int binary_hash_2_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_2; } static int binary_hash_3_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_3; } static int binary_hash_4_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_4; } static int binary_hash_5_64x4(void * binary) { return (((uint32_t *)binary)[0]>>8) & PH_MASK_5; } static int get_hash_0_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_0; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_0;} static int get_hash_1_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_1; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_1;} static int get_hash_2_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_2; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_2;} static int get_hash_3_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_3; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_3;} static int get_hash_4_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_4; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_4;} static int get_hash_5_64x4(int index) { #if MD5_X2 if (index & 1) return (crypt_key_X86[index>>MD5_X2].x2.w2[0]>>8) & PH_MASK_5; #endif return (crypt_key_X86[index>>MD5_X2].x1.w[0]>>8) & PH_MASK_5;} #endif static int get_hash_0(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_0; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_0; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_0; } static int get_hash_1(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_1; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_1; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_1; } static int get_hash_2(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_2; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_2; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_2; } static int get_hash_3(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_3; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_3; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_3; } static int get_hash_4(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_4; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_4; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_4; } static int get_hash_5(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_5; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_5; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_5; } static int get_hash_6(int index) { #ifdef SIMD_COEF_32 if (dynamic_use_sse&1) { unsigned int idx = ( ((unsigned int)index)/SIMD_COEF_32); return ((uint32_t *)&(crypt_key[idx].c))[index&(SIMD_COEF_32-1)] & PH_MASK_6; } #endif #if MD5_X2 if (index & 1) return crypt_key_X86[index>>MD5_X2].x2.w2[0] & PH_MASK_6; #endif return crypt_key_X86[index>>MD5_X2].x1.w[0] & PH_MASK_6; } /************************************************************************ * We now fully handle all hashing of salts, here in the format. We * return a pointer ot an allocated salt record. Thus, we search all * of the salt records, looking for the same salt. If we find it, we * want to return THAT pointer, and not allocate a new pointer. * This works great, but forces us to do salt comparision here. ***********************************************************************/ #define DYNA_SALT_HASH_BITS SALT_HASH_LOG #define DYNA_SALT_HASH_SIZE (1<<DYNA_SALT_HASH_BITS) #define DYNA_SALT_HASH_MOD (DYNA_SALT_HASH_SIZE-1) typedef struct dyna_salt_list_entry { struct dyna_salt_list_entry *next; unsigned len; unsigned char *salt; } dyna_salt_list_entry; typedef struct { dyna_salt_list_entry *head, *tail; int count; } dyna_salt_list_main; typedef struct { dyna_salt_list_main List; } SaltHashTab_t; static SaltHashTab_t *SaltHashTab=NULL; static dyna_salt_list_entry *pSaltHashData=NULL, *pSaltHashDataNext=NULL; static int dyna_salt_list_count=0; static unsigned char *pSaltDataBuf=NULL, *pNextSaltDataBuf=NULL; static int nSaltDataBuf=0; static unsigned char *AddSaltHash(unsigned char *salt, unsigned int len, unsigned int idx) { unsigned char *pRet; if (dyna_salt_list_count == 0) { pSaltHashDataNext = pSaltHashData = mem_calloc_tiny(sizeof(dyna_salt_list_entry) * 25000, MEM_ALIGN_WORD); dyna_salt_list_count = 25000; } if (nSaltDataBuf < len) { pSaltDataBuf = pNextSaltDataBuf = mem_alloc_tiny(0x60000, MEM_ALIGN_NONE); nSaltDataBuf = 0x60000; } pRet = pNextSaltDataBuf; pSaltHashDataNext->salt = pNextSaltDataBuf; memcpy(pSaltHashDataNext->salt, salt, len); pSaltHashDataNext->len = len; pNextSaltDataBuf += len; nSaltDataBuf -= len; if (SaltHashTab[idx].List.count == 0) SaltHashTab[idx].List.tail = SaltHashTab[idx].List.head = pSaltHashDataNext; else { SaltHashTab[idx].List.tail->next = pSaltHashDataNext; SaltHashTab[idx].List.tail = pSaltHashDataNext; } ++SaltHashTab[idx].List.count; ++pSaltHashDataNext; --dyna_salt_list_count; return pRet; } static unsigned char *FindSaltHash(unsigned char *salt, unsigned int len, CRC32_t crc) { unsigned int idx = crc & DYNA_SALT_HASH_MOD; dyna_salt_list_entry *p; if (!SaltHashTab) SaltHashTab = mem_calloc_tiny(sizeof(SaltHashTab_t) * DYNA_SALT_HASH_SIZE, MEM_ALIGN_WORD); if (!SaltHashTab[idx].List.count) { return AddSaltHash(salt, len, idx); } // Ok, we have some salts in this hash list. Now walk the list, searching for an EQUAL salt. p = SaltHashTab[idx].List.head; while (p) { if (len == p->len && !memcmp((char*)salt, (char*)p->salt, len)) { return p->salt; // found it! return this one, so we do not allocate another. } p = p->next; } return AddSaltHash(salt, len, idx); } static unsigned char *HashSalt(unsigned char *salt, unsigned int len) { CRC32_t crc = 0xffffffff, i; unsigned char *ret_hash; // compute the hash. for (i = 0; i < len; ++i) crc = jtr_crc32(crc,salt[i]); crc = ~crc; ret_hash = FindSaltHash(salt, len, crc); return ret_hash; } static int ConvertFromHex(unsigned char *p, int len) { unsigned char *cp; unsigned int i, x; if (!p || memcmp(p, "HEX$", 4)) return len; // Ok, do a convert, and return 'new' len. len -= 4; len >>= 1; cp = p; x = len; for (i=4; x; --x, i+= 2) { *cp++ = atoi16[ARCH_INDEX(p[i])]*16 + atoi16[ARCH_INDEX(p[i+1])]; } *cp = 0; return len; } static unsigned int salt_external_to_internal_convert(unsigned char *extern_salt, unsigned char *Buffer) { // Ok, we get this: extern_salt = salt_data$$2salt2$$Uuser ... where anything can be missing or in any order // the any order has 1 exception of salt_data MUST be first. So if we get $$2salt2, then we know there is no salt-1 value. unsigned char *salt2=0, *userid=0, *Flds[10]; int i, nsalt2=0, nuserid=0, nFlds[10]={0,0,0,0,0,0,0,0,0,0}; unsigned int len = strlen((char*)extern_salt), bit; unsigned int bit_array=0; unsigned int the_real_len = 6; // 2 bytes base-8 length, and 4 bytes base-8 bitmap. // work from back of string to front, looking for the $$X signatures. for (i = len-3; i >= 0; --i) { if (extern_salt[i] == '$' && extern_salt[i+1] == '$') { // a 'likely' extra salt value. switch(extern_salt[i+2]) { case '2': if (curdat.b2Salts) { salt2 = &extern_salt[i+3]; nsalt2 = strlen((char*)salt2); nsalt2 = ConvertFromHex(salt2, nsalt2); extern_salt[i] = 0; bit_array |= 1; the_real_len += (nsalt2+1); } break; case 'U': if (curdat.nUserName) { userid = &extern_salt[i+3]; nuserid = strlen((char*)userid); nuserid = ConvertFromHex(userid, nuserid); extern_salt[i] = 0; bit_array |= 2; the_real_len += (nuserid+1); } break; case 'F': { if (extern_salt[i+3] >= '0' && extern_salt[i+3] <= '9') { if (curdat.FldMask && (curdat.FldMask & (MGF_FLDx_BIT<<(extern_salt[i+3]-'0'))) == (MGF_FLDx_BIT<<(extern_salt[i+3]-'0'))) { Flds[extern_salt[i+3]-'0'] = &extern_salt[i+4]; nFlds[extern_salt[i+3]-'0'] = strlen((char*)(Flds[extern_salt[i+3]-'0'])); nFlds[extern_salt[i+3]-'0'] = ConvertFromHex(Flds[extern_salt[i+3]-'0'], nFlds[extern_salt[i+3]-'0']); extern_salt[i] = 0; bit_array |= (1<<(2+extern_salt[i+3]-'0')); the_real_len += (nFlds[extern_salt[i+3]-'0']+1); } break; } } } } } // We have now ripped the data apart. Now put it into Buffer, in proper ORDER // Length of salt (salt1) These 2 are stored as base-8 numbers. len = strlen((char*)extern_salt); len = ConvertFromHex(extern_salt, len); the_real_len += len; *Buffer++ = (len>>3) + '0'; *Buffer++ = (len&7) + '0'; // bit array *Buffer++ = (bit_array>>9) + '0'; *Buffer++ = ((bit_array>>6)&7) + '0'; *Buffer++ = ((bit_array>>3)&7) + '0'; *Buffer++ = (bit_array&7) + '0'; memcpy((char*)Buffer, (char*)extern_salt, len); Buffer += len; if (!bit_array) return the_real_len; if (nsalt2) { *Buffer++ = nsalt2; memcpy((char*)Buffer, (char*)salt2, nsalt2); Buffer += nsalt2; bit_array &= ~1; if (!bit_array) return the_real_len; } if (nuserid) { *Buffer++ = nuserid; memcpy((char*)Buffer, (char*)userid, nuserid); if (curdat.nUserName==2) { Buffer[nuserid] = 0; strupr((char*)Buffer); } else if (curdat.nUserName==2) { Buffer[nuserid] = 0; strlwr((char*)Buffer); } Buffer += nuserid; bit_array &= ~2; if (!bit_array) return the_real_len; } bit = 4; for (i = 0; i < 10; ++i, bit<<=1) { if (nFlds[i]) { *Buffer++ = nFlds[i]; memcpy((char*)Buffer, (char*)(Flds[i]), nFlds[i]); Buffer += nFlds[i]; bit_array &= ~bit; if (!bit_array) return the_real_len; } } return the_real_len; } /********************************************************************************* * This salt function has been TOTALLY re-written. Now, we do these things: * 1. convert from external format ($salt$$Uuser$$2HEX$salt2_in_hex, etc, into * our internal format. Our internal format is 2 base-8 numbers (2 digit and 4 * digit), followed by the 'raw' salt bytes, followed by pascal strings of any * other special salt values (salt2, user, flields 0 to 9). The first 2 digit * base 8 number is the length of the binary bytes of the 'real' salt. The * 2nd base-8 4 digit number, is a bit mask of what 'extra' salt types are * contained. * 2. We allocate and 'own' the salt buffers here, so that: * 3. We detect duplicate salts. NOTE, we have normalized the salts, so 2 salts that * appear different (external format), appear exactly the same on internal format. * Thus, we dupe remove them here. * 4. We allocation storage for the salts. The ONLY thing we return to john, is * a 4 (or 8 byte in 64 bit builds) pointer to the salt. Thus, when we find * a dupe, we do not have to allocate ANY memory, and simply return the pointer * to the original salt (which is the same as the one we are working on now). * * this is much more complex, however, it allows us to use much less memory, to * have the set_salt function operate VERY quickly (all processing is done here). * It also allows john load time to happen FASTER (yes faster), that it was happening * due to smaller memory footprint, and john's external salt collision to have * less work to do. The memory footprint was also reduced, because now we store * JUST the require memory, and a pointer. Before, often we stored a LOT of memory * for many format types. For a few types, we do use more memory with this method * than before, but for more the memory usage is way down. *********************************************************************************/ static void *get_salt(char *ciphertext) { char Salt[SALT_SIZE+1], saltIntBuf[SALT_SIZE+1]; int off, possible_neg_one=0; unsigned char *saltp; unsigned int the_real_len; static union x { unsigned char salt_p[sizeof(unsigned char*)]; ARCH_WORD p[1]; } union_x; if ( (curdat.pSetup->flags&MGF_SALTED) == 0) { memset(union_x.salt_p, 0, sizeof(union_x.salt_p)); return union_x.salt_p; } memset(Salt, 0, SALT_SIZE+1); // Ok, see if the wrong dynamic type is loaded (such as the 'last' dynamic type). if (!strncmp(ciphertext, "$dynamic_", 9)) { char *cp1 = &ciphertext[9]; char *cp2 = &curdat.dynamic_WHICH_TYPE_SIG[9]; while (*cp2 && *cp2 == *cp1) { ++cp1; ++cp2; } if (*cp2) { char subformat[17]; struct fmt_main *pFmtLocal; int nFmtNum; memcpy(subformat, ciphertext, 16); subformat[16] = 0; cp2 = &subformat[9]; while (*cp2 && *cp2 != '$') ++cp2; *cp2 = 0; nFmtNum = -1; sscanf(subformat, "$dynamic_%d", &nFmtNum); if (nFmtNum==-1) return union_x.salt_p; pFmtLocal = dynamic_Get_fmt_main(nFmtNum); memcpy(&curdat, pFmtLocal->private.data, sizeof(private_subformat_data)); } } if (curdat.dynamic_FIXED_SALT_SIZE==0 && !curdat.nUserName && !curdat.FldMask) return union_x.salt_p; if (!strncmp(ciphertext, "$dynamic_", 9)) off=curdat.dynamic_SALT_OFFSET; else off=curdat.dynamic_SALT_OFFSET-strlen(curdat.dynamic_WHICH_TYPE_SIG); if (ciphertext[off] == '$') { if (ciphertext[off+1]=='U' && curdat.nUserName) possible_neg_one = -1; else if (ciphertext[off+1]=='2' && curdat.b2Salts) possible_neg_one = -1; else if (ciphertext[off+1]=='F' && ciphertext[off+2]>='0' && ciphertext[off+2]<='9' && curdat.FldMask) { if ((curdat.FldMask & (MGF_FLDx_BIT<<(ciphertext[off+2]-'0'))) == (MGF_FLDx_BIT<<(ciphertext[off+2]-'0'))) possible_neg_one = -1; } } strnzcpy(Salt, &ciphertext[off + possible_neg_one], SALT_SIZE); if (curdat.dynamic_salt_as_hex) { unsigned char Buf[128]; unsigned int slen=strlen(Salt); switch (curdat.dynamic_salt_as_hex_format_type) { // TODO: Come up with some way to put these into a CASE(HASH) #define #define SPH_CASE(H,F,S) case MGF__##H: {sph_##F##_context c;sph_##F##_init(&c);sph_##F(&c,(const unsigned char*)Salt,slen);sph_##F##_close(&c,Buf); \ memset(Salt,0,SALT_SIZE+1);base64_convert(Buf,e_b64_raw,S,Salt,e_b64_hex,SALT_SIZE, 0, 0);break; } #define OSSL_CASE(H,C,S) case MGF__##H: {C##_CTX c;H##_Init(&c);H##_Update(&c,Salt,slen);H##_Final(Buf,&c); \ memset(Salt,0,SALT_SIZE+1);base64_convert(Buf,e_b64_raw,S,Salt,e_b64_hex,SALT_SIZE, 0, 0);break; } #define KECCAK_CASE(H,S) case MGF__##H: {KECCAK_CTX c;H##_Init(&c);KECCAK_Update(&c,(BitSequence*)Salt,slen);KECCAK_Final(Buf,&c); \ memset(Salt,0,SALT_SIZE+1);base64_convert(Buf,e_b64_raw,S,Salt,e_b64_hex,SALT_SIZE, 0, 0);break; } case MGF__MD5: { // Do not 'worry' about SSE/MMX, Only do 'generic' md5. This is ONLY done // at the start of the run. We will NEVER see this run, once john starts. MD5_CTX ctx; int i; char *cpo; MD5_Init(&ctx); if (curdat.dynamic_salt_as_hex & 0x100) { char *s2 = mem_alloc(slen*2+1); for (i = 0; i < slen; ++i) { s2[i<<1] = Salt[i]; s2[(i<<1)+1] = 0; } MD5_Update(&ctx, s2, slen*2); MEM_FREE(s2); } else MD5_Update(&ctx, Salt, slen); MD5_Final(Buf, &ctx); if ( (curdat.dynamic_salt_as_hex&3) == 2) { strcat(Salt, "$$2"); cpo = &Salt[slen+3]; } else { cpo = Salt; memset(Salt, 0, SALT_SIZE+1); } base64_convert(Buf, e_b64_raw, 16, cpo, e_b64_hex, SALT_SIZE, 0, 0); break; } OSSL_CASE(MD4,MD4,16) OSSL_CASE(SHA1,SHA,20) OSSL_CASE(SHA224,SHA256,28) OSSL_CASE(SHA256,SHA256,32) OSSL_CASE(SHA384,SHA512,48) OSSL_CASE(SHA512,SHA512,64) OSSL_CASE(WHIRLPOOL,WHIRLPOOL,64) case MGF__GOST: { gost_ctx ctx; john_gost_init(&ctx); john_gost_update(&ctx, (const unsigned char*)Salt, slen); john_gost_final(&ctx, (unsigned char*)Buf); memset(Salt, 0, SALT_SIZE+1); base64_convert(Buf, e_b64_raw, 32, Salt, e_b64_hex, SALT_SIZE, 0, 0); break; } SPH_CASE(Tiger,tiger,24) SPH_CASE(RIPEMD128,ripemd128,16) SPH_CASE(RIPEMD160,ripemd160,20) SPH_CASE(RIPEMD256,ripemd256,32) SPH_CASE(RIPEMD320,ripemd320,40) SPH_CASE(HAVAL128_3,haval128_3,16) SPH_CASE(HAVAL128_4,haval128_4,16) SPH_CASE(HAVAL128_5,haval128_5,16) SPH_CASE(HAVAL160_3,haval160_3,20) SPH_CASE(HAVAL160_4,haval160_4,20) SPH_CASE(HAVAL160_5,haval160_5,20) SPH_CASE(HAVAL192_3,haval192_3,24) SPH_CASE(HAVAL192_4,haval192_4,24) SPH_CASE(HAVAL192_5,haval192_5,24) SPH_CASE(HAVAL224_3,haval224_3,28) SPH_CASE(HAVAL224_4,haval224_4,28) SPH_CASE(HAVAL224_5,haval224_5,28) SPH_CASE(HAVAL256_3,haval256_3,32) SPH_CASE(HAVAL256_4,haval256_4,32) SPH_CASE(HAVAL256_5,haval256_5,32) SPH_CASE(MD2,md2,16) SPH_CASE(PANAMA,panama,32) SPH_CASE(SKEIN224,skein224,28) SPH_CASE(SKEIN256,skein256,32) SPH_CASE(SKEIN384,skein384,48) SPH_CASE(SKEIN512,skein512,64) KECCAK_CASE(SHA3_224,28) KECCAK_CASE(SHA3_256,32) KECCAK_CASE(SHA3_384,48) KECCAK_CASE(SHA3_512,64) KECCAK_CASE(KECCAK_256,32) KECCAK_CASE(KECCAK_512,64) // LARGE_HASH_EDIT_POINT default: { error_msg("Invalid dynamic flags seen. Data type not yet defined\n"); } } } the_real_len = salt_external_to_internal_convert((unsigned char*)Salt, (unsigned char*)saltIntBuf); // Now convert this into a stored salt, or find the 'already' stored same salt. saltp = HashSalt((unsigned char*)saltIntBuf, the_real_len); memcpy(union_x.salt_p, &saltp, sizeof(saltp)); return union_x.salt_p; } /********************************************************************************* * Now our salt is returned only as a pointer. We *********************************************************************************/ static int salt_hash(void *salt) { unsigned long H; if (!salt) return 0; if ( (curdat.pSetup->flags&MGF_SALTED) == 0) return 0; // salt is now a pointer, but WORD aligned. We remove that word alingment, and simply use the next bits #if ARCH_ALLOWS_UNALIGNED H = *((unsigned long*)salt); #else memcpy(&H, salt, 8); #endif // Mix up the pointer value (H^(H>>9)) so that if we have a fixed sized allocation // that things do get 'stirred' up better. return ( (H^(H>>9)) & (SALT_HASH_SIZE-1) ); } static unsigned dynamic_this_salt_length(const void *v) { const unsigned char *s = (unsigned char*)v; unsigned l = *s++ - '0'; unsigned bits; l <<= 3; l += *s++ - '0'; #if ARCH_ALLOWS_UNALIGNED if (*((uint32_t*)s) == 0x30303030) #else if (!memcmp(s, "0000", 4)) #endif return l; bits = *s++ - '0'; bits <<= 3; bits += *s++ - '0'; bits <<= 3; bits += *s++ - '0'; bits <<= 3; bits += *s++ - '0'; s += l; while(bits) { if (bits & 1) { l += *s; s += *s; ++s; } bits >>= 1; } return l; } /* * dyna compare is required, to get all the shortest * salt strings first, then the next longer, then the * next, and finally the longest. Without this change * there are many dyna formats which will miss finding * hashes, because old dirty salt information gets left * over, blowing the next runs. There are many formats * which try to not clear buffers if they do not need * to, BUT this only works if salts are taken shortest * to longest. This sort builds the list of salts that way */ static int salt_compare(const void *x, const void *y) { /* this is all that is needed in dyna salt_compare(). Dyna is a pointer to a string, NOT the actual string. The first 2 bytes of string are length (base 8 ascii) */ const char *X = *((const char**)x); const char *Y = *((const char**)y); int l1, l2, l; if (*X<*Y) return -1; if (*X>*Y) return 1; if (X[1]<Y[1]) return -1; if (X[1]>Y[1]) return 1; // we had to make the salt order 100% deterministic, so that intersalt-restore l = l1 = dynamic_this_salt_length(X); l2 = dynamic_this_salt_length(Y); if (l2 < l) l = l2; l = memcmp(&X[6], &Y[6], l); if (l) return l; if (l1==l2) return 0; if (l1 > l2) return 1; return -1; } void dynamic_salt_md5(struct db_salt *s) { MD5_CTX ctx; int len; const char *S = *((const char**)s->salt); MD5_Init(&ctx); len = dynamic_this_salt_length(S); MD5_Update(&ctx, S + 6, len); MD5_Final((unsigned char*)(s->salt_md5), &ctx); } /********************************************************************************* * Gets the binary value from a base-16 hash. *********************************************************************************/ static void *get_binary(char *_ciphertext) { static char *realcipher; unsigned int i; char *ciphertext = _ciphertext; if (!realcipher) realcipher = mem_alloc_tiny(BINARY_SIZE_SHA, MEM_ALIGN_WORD); if (!strncmp(_ciphertext, "$dynamic_", 9)) { ciphertext += 9; while (*ciphertext++ != '$') ; } for (i=0;i<BINARY_SIZE;i++) { realcipher[i] = atoi16[ARCH_INDEX(ciphertext[i*2])]*16 + atoi16[ARCH_INDEX(ciphertext[i*2+1])]; } return (void *)realcipher; } // NOTE NOTE NOTE, we have currently ONLY implemented a non-salted function!!! static char *source(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 16; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_20_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 20; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_28_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 28; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_32_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 32; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_40_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 40; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_48_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 48; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } static char *source_64_hex(char *source, void *binary) { static char Buf[256]; unsigned char *cpi= (unsigned char*)(binary); char *cpo = Buf; unsigned int i; cpo += sprintf(Buf, "%s", curdat.dynamic_WHICH_TYPE_SIG); for (i = 0; i < 64; ++i) { *cpo++ = itoa16[(*cpi)>>4]; *cpo++ = itoa16[*cpi&0xF]; ++cpi; } *cpo = 0; return Buf; } /********************************************************************************* * Gets the binary value from a base-64 hash *********************************************************************************/ static void * binary_b64m(char *ciphertext) { unsigned int i; static unsigned char *b; char *pos; if (!b) b = mem_alloc_tiny(64+3, MEM_ALIGN_WORD); pos = ciphertext; if (!strncmp(pos, "$dynamic_", 9)) { pos += 9; while (*pos++ != '$') ; } i = base64_valid_length(pos, e_b64_mime, 0, 0); base64_convert(pos, e_b64_mime, i, b, e_b64_raw, 64+3, 0, 0); //printf("\nciphertext=%s\n", ciphertext); //dump_stuff_msg("binary", b, 16); return b; } static void * binary_b64(char *ciphertext) { unsigned int i; static unsigned char *b; char *pos; if (!b) b = mem_alloc_tiny(64+3, MEM_ALIGN_WORD); pos = ciphertext; if (!strncmp(pos, "$dynamic_", 9)) { pos += 9; while (*pos++ != '$') ; } i = base64_valid_length(pos, e_b64_crypt, 0, 0); base64_convert(pos, e_b64_cryptBS, i, b, e_b64_raw, 64+3, 0, 0); //printf("\nciphertext=%s\n", ciphertext); //dump_stuff_msg("binary", b, 16); return b; } static void * binary_b64b(char *ciphertext) { unsigned int i; static unsigned char *b; char *pos; if (!b) b = mem_alloc_tiny(64+3, MEM_ALIGN_WORD); pos = ciphertext; if (!strncmp(pos, "$dynamic_", 9)) { pos += 9; while (*pos++ != '$') ; } i = base64_valid_length(pos, e_b64_crypt, 0, 0); base64_convert(pos, e_b64_crypt, i, b, e_b64_raw, 64+3, 0, 0); //printf("\nciphertext=%s\n", ciphertext); //dump_stuff_msg("binary", b, 16); return b; } #define TO_BINARY(b1, b2, b3) \ value = \ (MD5_word)atoi64[ARCH_INDEX(pos[0])] | \ ((MD5_word)atoi64[ARCH_INDEX(pos[1])] << 6) | \ ((MD5_word)atoi64[ARCH_INDEX(pos[2])] << 12) | \ ((MD5_word)atoi64[ARCH_INDEX(pos[3])] << 18); \ pos += 4; \ b[b1] = value >> 16; \ b[b2] = value >> 8; \ b[b3] = value; static void * binary_b64a(char *ciphertext) { static unsigned char *b; char *pos; MD5_word value; if (!b) b = mem_alloc_tiny(16, MEM_ALIGN_WORD); pos = ciphertext; if (!strncmp(pos, "$dynamic_", 9)) { pos += 9; while (*pos++ != '$') ; } TO_BINARY(0, 6, 12); TO_BINARY(1, 7, 13); TO_BINARY(2, 8, 14); TO_BINARY(3, 9, 15); TO_BINARY(4, 10, 5); b[11] = (MD5_word)atoi64[ARCH_INDEX(pos[0])] | ((MD5_word)atoi64[ARCH_INDEX(pos[1])] << 6); MD5_swap((MD5_word*)b,(MD5_word*)b, 4); return b; } /********************************************************************************* * Gets the binary value from a base-64 hash (such as cisco PIX) *********************************************************************************/ static void * binary_b64_4x6(char *ciphertext) { static uint32_t *b; unsigned int i; char *pos; if (!b) b = mem_alloc_tiny(16, MEM_ALIGN_WORD); pos = ciphertext; if (!strncmp(pos, "$dynamic_", 9)) { pos += 9; while (*pos++ != '$') ; } for (i = 0; i < 4; i++) { b[i] = atoi64[ARCH_INDEX(pos[i*4 + 0])] + (atoi64[ARCH_INDEX(pos[i*4 + 1])] << 6) + (atoi64[ARCH_INDEX(pos[i*4 + 2])] << 12) + (atoi64[ARCH_INDEX(pos[i*4 + 3])] << 18); } MD5_swap(b,b, 4); return (void *)b; } /********************************************************************************* * Here is the main mdg_generic fmt_main. NOTE in its default settings, it is * ready to handle base-16 hashes. *********************************************************************************/ static struct fmt_main fmt_Dynamic = { { FORMAT_LABEL, FORMAT_NAME, #ifdef SIMD_COEF_32 ALGORITHM_NAME, #else ALGORITHM_NAME_X86, #endif BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, #ifdef SIMD_COEF_32 PLAINTEXT_LENGTH, #else PLAINTEXT_LENGTH_X86, #endif BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, #ifdef SIMD_COEF_32 MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #else MIN_KEYS_PER_CRYPT_X86, MAX_KEYS_PER_CRYPT_X86, #endif #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT, { NULL }, { NULL }, dynamic_tests }, { init, done, fmt_default_reset, prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, salt_compare, set_salt, set_key, get_key, clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; /************************************************************** ************************************************************** ************************************************************** ************************************************************** * These are the md5 'primitive' functions that are used by * the build-in expressions, and by the expression generator * They load passwords, salts, user ids, do crypts, convert * crypts into base-16, etc. They are pretty encompassing, * and have been found to be able to do most anything with * a standard 'base-16' md5 hash, salted or unsalted that * fits a 'simple' php style expression. ************************************************************** ************************************************************** ************************************************************** *************************************************************/ static void Dynamic_Load_itoa16_w2() { char buf[3]; unsigned int i; for (i = 0; i < 256; ++i) { sprintf(buf, "%X%X", i>>4, i&0xF); memcpy(&(itoa16_w2_u[i]), buf, 2); sprintf(buf, "%x%x", i>>4, i&0xF); memcpy(&(itoa16_w2_l[i]), buf, 2); } } #ifdef SIMD_COEF_32 /************************************************************** ************************************************************** * Here are some 'helpers' to our helpers, when it comes to * loading data into the mmx/sse buffers. We have several * of these common helper functions, and use them in 'most' * of the helper primitives, instead of having the same * code being inlined in each of them. ************************************************************** *************************************************************/ static void __SSE_append_output_base16_to_input(uint32_t *IPBdw, unsigned char *CRY, unsigned int idx_mod) { // #3 // 5955K (core2, $dynamic_2$) // 1565K (core2, $dynamic_1006$) // 3381K (ath64, $dynamic_2$) // 824.7k (ath64, $dynamic_1006$) #undef inc #define inc ((SIMD_COEF_32-1) * 2) unsigned short *IPBw = (unsigned short*)IPBdw; IPBw += (idx_mod<<1); CRY += (idx_mod<<2); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw = 0x80; #undef inc } static void __SSE_overwrite_output_base16_to_input(uint32_t *IPBdw, unsigned char *CRY, unsigned int idx_mod) { // #3 // 5955K (core2, $dynamic_2$) // 1565K (core2, $dynamic_1006$) // 3381K (ath64, $dynamic_2$) // 824.7k (ath64, $dynamic_1006$) #undef inc #define inc ((SIMD_COEF_32-1) * 2) unsigned short *IPBw = (unsigned short *)IPBdw; IPBw += (idx_mod<<1); CRY += (idx_mod<<2); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; CRY += (inc<<1); *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; *IPBw++ = itoa16_w2[*CRY++]; *IPBw++ = itoa16_w2[*CRY++]; IPBw += inc; #undef inc } static void __SSE_append_output_base16_to_input_semi_aligned_2(unsigned int ip, uint32_t *IPBdw, unsigned char *CRY, unsigned int idx_mod) { // #1 // 9586k/4740k (core2, $dynamic_9$) // 5113k/4382k (core2,$dynamic_10$) // (ath64, $dynamic_9$) // (ath64, $dynamic_10$) #define inc SIMD_COEF_32 #define incCRY ((SIMD_COEF_32 - 1) * 4) // Ok, here we are 1/2 off. We are starting in the 'middle' of a DWORD (and end // in the middle of the last one). // start our pointers out at the right 32 bit offset into the first MMX/SSE buffer IPBdw += idx_mod; IPBdw += (ip>>2)*SIMD_COEF_32; CRY += (idx_mod<<2); // first byte handled here. *IPBdw &= 0xFFFF; *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); CRY += incCRY; *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); CRY += incCRY; *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); CRY += incCRY; *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); *IPBdw |= (((uint32_t)(itoa16_w2[*CRY++]))<<16); IPBdw += inc; *IPBdw = (itoa16_w2[*CRY++]); // Add the 0x80 at the proper location (offset 0x21) *IPBdw |= 0x800000; #undef inc #undef incCRY } static void __SSE_append_output_base16_to_input_semi_aligned_0(unsigned int ip, uint32_t *IPBdw, unsigned char *CRY, unsigned int idx_mod) { // #2 // 6083k (core2, $dynamic_2$) // 1590K (core2, $dynamic_1006$) // 3537K (ath64, $dynamic_2$) // 890.3K (ath64, $dynamic_1006$) #undef inc #define inc SIMD_COEF_32 #define incCRY (4*SIMD_COEF_32-2) // start our pointers out at the right 32 bit offset into the first MMX/SSE buffer IPBdw += idx_mod; IPBdw += (ip>>2)*SIMD_COEF_32; CRY += (idx_mod<<2); *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; CRY += 2; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; // CRY += (inc*3)+2; CRY += incCRY; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; CRY += 2; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; // CRY += (inc*3)+2; CRY += incCRY; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; CRY += 2; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; // CRY += (inc*3)+2; CRY += incCRY; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); IPBdw += inc; CRY += 2; *IPBdw = (((uint32_t)(itoa16_w2[*(CRY+1)]))<<16)|(itoa16_w2[*CRY]); // Add the 0x80 at the proper location (offset 0x21) IPBdw += inc; *IPBdw = 0x80; #undef inc #undef incCRY } static void __SSE_append_string_to_input_unicode(unsigned char *IPB, unsigned int idx_mod, unsigned char *cp, unsigned int len, unsigned int bf_ptr, unsigned int bUpdate0x80) { unsigned char *cpO; #if ARCH_LITTLE_ENDIAN // if big-endian, we gain nothing from this function (since we would have to byte swap) if (len>1&&!(bf_ptr&1)) { unsigned int w32_cnt; if (bf_ptr&2) { cpO = &IPB[GETPOS(bf_ptr, idx_mod)]; bf_ptr += 2; *cpO = *cp++; cpO[1] = 0; --len; } w32_cnt = len>>1; if (w32_cnt) { uint32_t *wpO; wpO = (uint32_t*)&IPB[GETPOS(bf_ptr, idx_mod)]; len -= (w32_cnt<<1); bf_ptr += (w32_cnt<<2); do { uint32_t x = 0; x = cp[1]; x <<= 16; x += cp[0]; *wpO = x; cp += 2; wpO += SIMD_COEF_32; } while (--w32_cnt); } } #endif cpO = &IPB[GETPOS(bf_ptr, idx_mod)]; while (len--) { *cpO++ = *cp++; if ( ((++bf_ptr)&3) == 0) cpO += ((SIMD_COEF_32-1)*4); *cpO++ = 0; if ( ((++bf_ptr)&3) == 0) cpO += ((SIMD_COEF_32-1)*4); } if (bUpdate0x80) *cpO = 0x80; } static void __SSE_append_string_to_input(unsigned char *IPB, unsigned int idx_mod, unsigned char *cp, unsigned int len, unsigned int bf_ptr, unsigned int bUpdate0x80) { unsigned char *cpO; // if our insertion point is on an 'even' DWORD, then we use DWORD * copying, as long as we can // This provides quite a nice speedup. #if ARCH_LITTLE_ENDIAN && ARCH_ALLOWS_UNALIGNED // if big-endian, we gain nothing from this function (since we would have to byte swap) if (len>3&&(bf_ptr&3)) { cpO = &IPB[GETPOS(bf_ptr, idx_mod)]; while (len--) { *cpO++ = *cp++; if ( ((++bf_ptr)&3) == 0) { if (!len) { if (bUpdate0x80) *cpO = 0x80; return; } break; } } } if (len>3&&!(bf_ptr&3)) { unsigned int w32_cnt = len>>2; if (w32_cnt) { uint32_t *wpO; wpO = (uint32_t*)&IPB[GETPOS(bf_ptr, idx_mod)]; len -= (w32_cnt<<2); bf_ptr += (w32_cnt<<2); do { *wpO = *((uint32_t*)cp); cp += 4; wpO += SIMD_COEF_32; } while (--w32_cnt); } if (!len) { if (bUpdate0x80) IPB[GETPOS(bf_ptr, idx_mod)] = 0x80; return; } } #endif cpO = &IPB[GETPOS(bf_ptr, idx_mod)]; while (len--) { *cpO++ = *cp++; if ( ((++bf_ptr)&3) == 0) cpO += ((SIMD_COEF_32-1)*4); } if (bUpdate0x80) *cpO = 0x80; } #endif // #ifdef SIMD_COEF_32 from way above. inline static void __append_string(DYNA_OMP_PARAMSm unsigned char *Str, unsigned int len) { unsigned int j; unsigned int til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { if (!utf16) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; total_len[idx][idx_mod] += len; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,Str,len,bf_ptr,1); } } else { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, 27, Str, len) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, 27, Str, len) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; total_len[idx][idx_mod] += outlen; // note we use the 'non' unicode variant, since we have already computed the unicode, and length properly __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)utf16Str,outlen,bf_ptr,1); } } else { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; total_len[idx][idx_mod] += len << 1; __SSE_append_string_to_input_unicode(input_buf[idx].c,idx_mod,Str,len,bf_ptr,1); } } } return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, Str, len) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, Str, len) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int z; unsigned char *cp; unsigned char *cpi = (unsigned char*)utf16Str; if (total_len_X86[j] + outlen <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); else #endif cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); for (z = 0; z < outlen; ++z) { *cp++ = *cpi++; } total_len_X86[j] += outlen; } } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp; unsigned char *cpi = Str; if (total_len_X86[j] + (len<<1) <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); else #endif cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); for (z = 0; z < len; ++z) { *cp++ = *cpi++; *cp++ = 0; } total_len_X86[j] += (len<<1); } } } } else { for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(&(input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]]), Str, len); else #endif memcpy(&(input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]]), Str, len); total_len_X86[j] += len; } } } inline static void __append2_string(DYNA_OMP_PARAMSm unsigned char *Str, unsigned int len) { unsigned int j; unsigned int til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { if (!utf16) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len2[idx][idx_mod]; total_len2[idx][idx_mod] += len; __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,Str,len,bf_ptr,1); } } else { if (options.target_enc != ASCII && options.target_enc != ISO_8859_1) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, 27, Str, len) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, 27, Str, len) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len2[idx][idx_mod]; total_len2[idx][idx_mod] += outlen; // note we use the 'non' unicode variant of __SSE_append_string_to_input(), since it's already unicode, and length properly __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,(unsigned char*)utf16Str,outlen,bf_ptr,1); } } else { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len2[idx][idx_mod]; total_len2[idx][idx_mod] += len << 1; __SSE_append_string_to_input_unicode(input_buf2[idx].c,idx_mod,Str,len,bf_ptr,1); } } } return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, Str, len) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, Str, len) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int z; unsigned char *cp; unsigned char *cpi = (unsigned char*)utf16Str; if (total_len2_X86[j] + outlen <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf2_X86[j>>MD5_X2].x2.B2[total_len2_X86[j]]); else #endif cp = &(input_buf2_X86[j>>MD5_X2].x1.B[total_len2_X86[j]]); for (z = 0; z < outlen; ++z) { *cp++ = *cpi++; } total_len2_X86[j] += outlen; } } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp; unsigned char *cpi = Str; if (total_len2_X86[j] + (len<<1) <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf2_X86[j>>MD5_X2].x2.B2[total_len2_X86[j]]); else #endif cp = &(input_buf2_X86[j>>MD5_X2].x1.B[total_len2_X86[j]]); for (z = 0; z < len; ++z) { *cp++ = *cpi++; *cp++ = 0; } total_len2_X86[j] += (len<<1); } } } } else { for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(&(input_buf2_X86[j>>MD5_X2].x2.b2[total_len2_X86[j]]), Str, len); else #endif memcpy(&(input_buf2_X86[j>>MD5_X2].x1.b[total_len2_X86[j]]), Str, len); total_len2_X86[j] += len; } } } void DynamicFunc__setmode_unicodeBE(DYNA_OMP_PARAMS) // DYNA_OMP_PARAMS not used. We use omp_thread_num() instead. { md5_unicode_convert_set(2,tid); } void DynamicFunc__setmode_unicode(DYNA_OMP_PARAMS) // DYNA_OMP_PARAMS not used. We use omp_thread_num() instead. { md5_unicode_convert_set(1,tid); } void DynamicFunc__setmode_normal (DYNA_OMP_PARAMS) // DYNA_OMP_PARAMS not used. We use omp_thread_num() instead. { md5_unicode_convert_set(0,tid); } /************************************************************** * DYNAMIC primitive helper function * Clears the input variable, and input 'lengths' *************************************************************/ void DynamicFunc__clean_input(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input(); #else unsigned int i=0; #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) { memset(input_buf[x].c, 0, sizeof(input_buf[0])); memset(total_len[x], 0, SIMD_COEF_32 * sizeof(total_len[0][0])); ++x; } return; } #endif for (i = first; i < last; ++i) { #if MD5_X2 if (i&1) memset(input_buf_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len_X86[i])); else #endif memset(input_buf_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len_X86[i])); total_len_X86[i] = 0; } #endif } void DynamicFunc__clean_input2(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input2(); #else unsigned int i=0; #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) { memset(input_buf2[x].c, 0, sizeof(input_buf2[0])); memset(total_len2[x], 0, SIMD_COEF_32 * sizeof(total_len2[0][0])); ++x; } return; } #endif for (i = first; i < last; ++i) { #if MD5_X2 if (i&1) memset(input_buf2_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len2_X86[i])); else #endif memset(input_buf2_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len2_X86[i])); total_len2_X86[i] = 0; } #endif } void DynamicFunc__clean_input_full(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input_full(); #else unsigned int i; #ifdef SIMD_COEF_32 unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) { memset(input_buf[x].c, 0, sizeof(input_buf[0])); memset(total_len[x], 0, SIMD_COEF_32 * sizeof(total_len[0][0])); ++x; } #endif for (i = first; i < last; ++i) { #if MD5_X2 if (i&1) memset(input_buf_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len_X86[i])); else #endif memset(input_buf_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len_X86[i])); total_len_X86[i] = 0; } #endif } void DynamicFunc__clean_input2_full(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input2_full(); #else unsigned int i; #ifdef SIMD_COEF_32 unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) { memset(input_buf2[x].c, 0, sizeof(input_buf2[0])); memset(total_len2[x], 0, SIMD_COEF_32 * sizeof(total_len2[0][0])); ++x; } #endif for (i = first; i < last; ++i) { #if MD5_X2 if (i&1) memset(input_buf2_X86[i>>MD5_X2].x2.b2, 0, COMPUTE_EX_LEN(total_len2_X86[i])); else #endif memset(input_buf2_X86[i>>MD5_X2].x1.b, 0, COMPUTE_EX_LEN(total_len2_X86[i])); total_len2_X86[i] = 0; } #endif } void DynamicFunc__clean_input_kwik(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input_kwik(); #else #ifdef SIMD_COEF_32 unsigned int i; if (dynamic_use_sse==1) { unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) memset(total_len[x++], 0, SIMD_COEF_32 * sizeof(total_len[0][0])); return; } #else unsigned int i; #endif for (i = first; i < last; ++i) { #if !ARCH_LITTLE_ENDIAN #if MD5_X2 if (i&1) memset(input_buf_X86[i>>MD5_X2].x2.b2, 0, total_len_X86[i]+5); else #endif memset(input_buf_X86[i>>MD5_X2].x1.b, 0, total_len_X86[i]+5); #endif total_len_X86[i] = 0; } #endif } void DynamicFunc__clean_input2_kwik(DYNA_OMP_PARAMS) { #ifndef _OPENMP __nonMP_DynamicFunc__clean_input2_kwik(); #else #ifdef SIMD_COEF_32 unsigned int i; if (dynamic_use_sse==1) { unsigned int x = first / SIMD_COEF_32; unsigned int y = (last+SIMD_COEF_32-1) / SIMD_COEF_32; while (x < y) memset(total_len2[x++], 0, SIMD_COEF_32 * sizeof(total_len2[0][0])); return; } #else unsigned int i; #endif for (i = first; i < last; ++i) { #if !ARCH_LITTLE_ENDIAN #if MD5_X2 if (i&1) memset(input_buf2_X86[i>>MD5_X2].x2.b2, 0, total_len2_X86[i]+5); else #endif memset(input_buf2_X86[i>>MD5_X2].x1.b, 0, total_len2_X86[i]+5); #endif total_len2_X86[i] = 0; } #endif } /************************************************************** * DYNAMIC primitive helper function * Appends all keys to the end of the input variables, and * updates lengths *************************************************************/ void DynamicFunc__append_keys(DYNA_OMP_PARAMS) { unsigned int j; unsigned int til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; int maxlen=27; if (curdat.pSetup->MaxInputLen < maxlen) maxlen = curdat.pSetup->MaxInputLen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, maxlen, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, maxlen, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); if (outlen <= 0) { saved_key_len[j] = -outlen / sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); } total_len[idx][idx_mod] += outlen; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)utf16Str,outlen,bf_ptr,1); } else { total_len[idx][idx_mod] += (saved_key_len[j] << 1); __SSE_append_string_to_input_unicode(input_buf[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } else { total_len[idx][idx_mod] += saved_key_len[j]; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi; UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); if (outlen <= 0) { saved_key_len[j] = -outlen / sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); } // only copy data if it will NOT trash the buffer if (total_len_X86[j] + outlen <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); else #endif cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); for (cpi = (unsigned char*)utf16Str, z = 0; z < outlen; ++z) *cp++ = *cpi++; total_len_X86[j] += outlen; } } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)saved_key[j]; if (total_len_X86[j] + (saved_key_len[j]<<1) <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); else #endif cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); for (z = 0; z < saved_key_len[j]; ++z) { *cp++ = *cpi++; *cp++ = 0; } total_len_X86[j] += (saved_key_len[j]<<1); } } } } else { for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(&(input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]]), saved_key[j], saved_key_len[j]); else #endif memcpy(&(input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]]), saved_key[j], saved_key_len[j]); total_len_X86[j] += saved_key_len[j]; } } } // DynamicFunc__append_keys_pad16 // append the array of keys to the array input1[], padding with nulls to 16 bytes, if input shorter. // Needed for net-md5 and net-sha1 formats. void DynamicFunc__append_keys_pad16(DYNA_OMP_PARAMS) { unsigned int j; unsigned int til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; saved_key[j][saved_key_len[j]] = 0; // so strncpy 'works' if (saved_key_len[j] < 16) { char buf[24]; strncpy(buf, saved_key[j], 18); total_len[idx][idx_mod] += 16; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)buf,16,bf_ptr,1); } else { total_len[idx][idx_mod] += saved_key_len[j]; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } return; } #endif for (; j < til; ++j) { saved_key[j][saved_key_len[j]] = 0; // so strncpy 'works' #if MD5_X2 if (j&1) strncpy(&(input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]]), saved_key[j], 17); else #endif strncpy(&(input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]]), saved_key[j], 17); total_len_X86[j] += 16; } } void DynamicFunc__append_keys_pad20(DYNA_OMP_PARAMS) { unsigned int j; unsigned int til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len[idx][idx_mod]; saved_key[j][saved_key_len[j]] = 0; // so strncpy 'works' if (saved_key_len[j] < 20) { char buf[28]; strncpy(buf, saved_key[j], 22); total_len[idx][idx_mod] += 20; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)buf,20,bf_ptr,1); } else { total_len[idx][idx_mod] += saved_key_len[j]; __SSE_append_string_to_input(input_buf[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } return; } #endif for (; j < til; ++j) { saved_key[j][saved_key_len[j]] = 0; // so strncpy 'works' #if MD5_X2 if (j&1) strncpy(&(input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]]), saved_key[j], 21); else #endif strncpy(&(input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]]), saved_key[j], 21); total_len_X86[j] += 20; } } /************************************************************** * DYNAMIC primitive helper function * Appends all keys to the end of the 2nd input variables, and * updates lengths *************************************************************/ void DynamicFunc__append_keys2(DYNA_OMP_PARAMS) { unsigned int j, til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { for (; j < til; ++j) { unsigned int idx = j/SIMD_COEF_32; unsigned int idx_mod = j&(SIMD_COEF_32-1); unsigned int bf_ptr = total_len2[idx][idx_mod]; if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; int maxlen=27; if (curdat.pSetup->MaxInputLen < maxlen) maxlen = curdat.pSetup->MaxInputLen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, maxlen, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, maxlen, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); if (outlen <= 0) { saved_key_len[j] = -outlen / sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); } total_len2[idx][idx_mod] += outlen; __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,(unsigned char*)utf16Str,outlen,bf_ptr,1); } else { total_len2[idx][idx_mod] += (saved_key_len[j] << 1); __SSE_append_string_to_input_unicode(input_buf2[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } else { total_len2[idx][idx_mod] += saved_key_len[j]; __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,(unsigned char*)saved_key[j],saved_key_len[j],bf_ptr,1); } } return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi; UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)saved_key[j], saved_key_len[j]) * sizeof(UTF16); if (outlen <= 0) { saved_key_len[j] = -outlen / sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); } // only copy data if it will NOT trash the buffer if (total_len_X86[j] + outlen <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf2_X86[j>>MD5_X2].x2.B2[total_len2_X86[j]]); else #endif cp = &(input_buf2_X86[j>>MD5_X2].x1.B[total_len2_X86[j]]); for (cpi = (unsigned char*)utf16Str, z = 0; z < outlen; ++z) *cp++ = *cpi++; total_len2_X86[j] += outlen; } } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)saved_key[j]; if (total_len2_X86[j] + (saved_key_len[j]<<1) <= MAX_BUFFER_OFFSET_AVOIDING_OVERWRITE) { #if MD5_X2 if (j&1) cp = &(input_buf2_X86[j>>MD5_X2].x2.B2[total_len2_X86[j]]); else #endif cp = &(input_buf2_X86[j>>MD5_X2].x1.B[total_len2_X86[j]]); for (z = 0; z < saved_key_len[j]; ++z) { *cp++ = *cpi++; *cp++ = 0; } total_len2_X86[j] += (saved_key_len[j]<<1); } } } } else { for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(&(input_buf2_X86[j>>MD5_X2].x2.b2[total_len2_X86[j]]), saved_key[j], saved_key_len[j]); else #endif memcpy(&(input_buf2_X86[j>>MD5_X2].x1.b[total_len2_X86[j]]), saved_key[j], saved_key_len[j]); total_len2_X86[j] += saved_key_len[j]; } } } void DynamicFunc__set_input_len_16(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int k; j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { // If length is < 16, then remove existing end of buffer marker, and then set // one at offset 16 for (k = 0; k < SIMD_COEF_32; ++k) { unsigned int this_item_len = total_len[j][k]; if (this_item_len < 16) input_buf[j].c[GETPOS(this_item_len, k&(SIMD_COEF_32-1))] = 0x00; input_buf[j].c[GETPOS(16, k&(SIMD_COEF_32-1))] = 0x80; total_len[j][k] = 16; } } return; } #endif for (; j < til; ++j) { // TODO: this code MAY need buffer cleaned up if we are using md5_go code!!! #if MD5_X2 if (j&1) { while (total_len_X86[j] < 16) input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]++] = 0; } else #endif {while (total_len_X86[j] < 16) input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]++] = 0;} total_len_X86[j] = 16; } } void DynamicFunc__set_input2_len_16(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int k; j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { // If length is < 16, then remove existing end of buffer marker, and then set // one at offset 16 for (k = 0; k < SIMD_COEF_32; ++k) { unsigned int this_item_len = total_len2[j][k]; if (this_item_len < 16) input_buf2[j].c[GETPOS(this_item_len, k&(SIMD_COEF_32-1))] = 0x00; input_buf2[j].c[GETPOS(16, k&(SIMD_COEF_32-1))] = 0x80; total_len2[j][k] = 16; } } return; } #endif for (; j < til; ++j) { // TODO: this code MAY need buffer cleaned up if we are using md5_go code!!! #if MD5_X2 if (j&1) { while (total_len2_X86[j] < 16) input_buf2_X86[j>>MD5_X2].x2.b2[total_len2_X86[j]++] = 0; } else #endif {while (total_len2_X86[j] < 16) input_buf2_X86[j>>MD5_X2].x1.b[total_len2_X86[j]++] = 0;} total_len2_X86[j] = 16; } } void DynamicFunc__set_input_len_20(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int k; j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { // If length is < 20, then remove existing end of buffer marker, and then set // one at offset 20 for (k = 0; k < SIMD_COEF_32; ++k) { unsigned int this_item_len = total_len[j][k]; if (this_item_len < 20) input_buf[j].c[GETPOS(this_item_len, k&(SIMD_COEF_32-1))] = 0x00; input_buf[j].c[GETPOS(20, k&(SIMD_COEF_32-1))] = 0x80; total_len[j][k] = 20; } } return; } #endif for (; j < til; ++j) { #if MD5_X2 if (j&1) { while (total_len_X86[j] < 20) input_buf_X86[j>>MD5_X2].x2.b2[total_len_X86[j]++] = 0; } else #endif {while (total_len_X86[j] < 20) input_buf_X86[j>>MD5_X2].x1.b[total_len_X86[j]++] = 0;} total_len_X86[j] = 20; } } void DynamicFunc__set_input2_len_20(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int k; j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { // If length is < 20, then remove existing end of buffer marker, and then set // one at offset 20 for (k = 0; k < SIMD_COEF_32; ++k) { unsigned int this_item_len = total_len2[j][k]; if (this_item_len < 20) input_buf2[j].c[GETPOS(this_item_len, k&(SIMD_COEF_32-1))] = 0x00; input_buf2[j].c[GETPOS(20, k&(SIMD_COEF_32-1))] = 0x80; total_len2[j][k] = 20; } } return; } #endif for (; j < til; ++j) { #if MD5_X2 if (j&1) { while (total_len2_X86[j] < 20) input_buf2_X86[j>>MD5_X2].x2.b2[total_len2_X86[j]++] = 0; } else #endif {while (total_len2_X86[j] < 20) input_buf2_X86[j>>MD5_X2].x1.b[total_len2_X86[j]++] = 0;} total_len2_X86[j] = 20; } } void DynamicFunc__set_input_len_32(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif for (; j < til; ++j) total_len_X86[j] = 32; } void DynamicFunc__set_input_len_32_cleartop(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { unsigned int k; for (k = 0; k < SIMD_COEF_32; ++k) { input_buf[j].c[GETPOS(32, k&(SIMD_COEF_32-1))] = 0x80; total_len[j][k] = 32; } } return; } #endif for (; j < til; ++j) { total_len_X86[j] = 32; #if !ARCH_LITTLE_ENDIAN #if MD5_X2 if (j&1) { //MD5_swap(input_buf_X86[j>>MD5_X2].x2.w2, input_buf2_X86[j>>MD5_X2].x2.w2, 8); memset(&(input_buf_X86[j>>MD5_X2].x2.B2[32]), 0, 24); } else #endif { //MD5_swap(input_buf_X86[j>>MD5_X2].x1.w, input_buf2_X86[j>>MD5_X2].x1.w, 8); memset(&(input_buf_X86[j>>MD5_X2].x1.B[32]), 0, 24); } #endif } } void DynamicFunc__set_input2_len_32(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif for (; j < til; ++j) total_len2_X86[j] = 32; } void DynamicFunc__set_input2_len_32_cleartop(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { unsigned int k; for (k = 0; k < SIMD_COEF_32; ++k) { input_buf2[j].c[GETPOS(32, k&(SIMD_COEF_32-1))] = 0x80; total_len2[j][k] = 32; } } return; } #endif for (; j < til; ++j) { total_len2_X86[j] = 32; #if !ARCH_LITTLE_ENDIAN #if MD5_X2 if (j&1) { //MD5_swap(input_buf2_X86[j>>MD5_X2].x2.w2, input_buf2_X86[j>>MD5_X2].x2.w2, 8); memset(&(input_buf2_X86[j>>MD5_X2].x2.B2[32]), 0, 24); } else #endif { //MD5_swap(input_buf2_X86[j>>MD5_X2].x1.w, input_buf2_X86[j>>MD5_X2].x1.w, 8); memset(&(input_buf2_X86[j>>MD5_X2].x1.B[32]), 0, 24); } #endif } } void DynamicFunc__set_input_len_40(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif for (; j < til; ++j) total_len_X86[j] = 40; } void DynamicFunc__set_input2_len_40(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif for (; j < til; ++j) total_len2_X86[j] = 40; } void DynamicFunc__set_input2_len_40_cleartop(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { j /= SIMD_COEF_32; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; for (; j < til; ++j) { unsigned int k; for (k = 0; k < SIMD_COEF_32; ++k) { input_buf2[j].c[GETPOS(40, k&(SIMD_COEF_32-1))] = 0x80; total_len2[j][k] = 40; } } return; } #endif for (; j < til; ++j) { total_len2_X86[j] = 40; #if !ARCH_LITTLE_ENDIAN #if MD5_X2 if (j&1) { memset(&(input_buf2_X86[j>>MD5_X2].x2.B2[40]), 0, 16); } else #endif { memset(&(input_buf2_X86[j>>MD5_X2].x1.B[40]), 0, 16); } #endif } } void DynamicFunc__set_input_len_64(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_64 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 64; } void DynamicFunc__set_input2_len_64(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_64 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 64; } void DynamicFunc__set_input_len_100(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_100 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) { unsigned char *cp; #if MD5_X2 if (j&1) cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); else #endif cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); while (*cp) *cp++ = 0; total_len_X86[j] = 100; } } void DynamicFunc__set_input_len_24(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_24 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 24; } void DynamicFunc__set_input_len_28(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_28 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 28; } void DynamicFunc__set_input_len_48(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_48 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 48; } void DynamicFunc__set_input_len_56(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_56 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 56; } void DynamicFunc__set_input_len_80(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_80 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 80; } void DynamicFunc__set_input_len_96(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_96 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 96; } void DynamicFunc__set_input_len_112(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_112 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 112; } void DynamicFunc__set_input_len_128(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_128 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 128; } void DynamicFunc__set_input_len_160(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_160 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 160; } void DynamicFunc__set_input_len_192(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_192 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 192; } void DynamicFunc__set_input_len_256(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input_len_256 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len_X86[j] = 256; } void DynamicFunc__set_input2_len_24(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_24 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 24; } void DynamicFunc__set_input2_len_28(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_28 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 28; } void DynamicFunc__set_input2_len_48(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_48 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 48; } void DynamicFunc__set_input2_len_56(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_56 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 56; } void DynamicFunc__set_input2_len_80(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_80 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 80; } void DynamicFunc__set_input2_len_96(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_96 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 96; } void DynamicFunc__set_input2_len_112(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_112 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 112; } void DynamicFunc__set_input2_len_128(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_128 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 128; } void DynamicFunc__set_input2_len_160(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_160 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 160; } void DynamicFunc__set_input2_len_192(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_192 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 192; } void DynamicFunc__set_input2_len_256(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP til = last; j = first; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse == 1) error_msg("Error, in your DYNAMIC script.\nIt is NOT valid to call DynamicFunc__set_input2_len_256 in SSE2/MMX mode\n"); #endif for (; j < til; ++j) total_len2_X86[j] = 256; } /************************************************************** * DYNAMIC primitive helper function * Appends the salt to the end of the input variables, and * updates lengths *************************************************************/ void DynamicFunc__append_salt(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm cursalt, saltlen); } /************************************************************** * DYNAMIC primitive helper function * Appends the salt to the end of the 2nd input variables, and * updates lengths *************************************************************/ void DynamicFunc__append_salt2(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm cursalt, saltlen); } void DynamicFunc__append_input_from_input2(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int j, k; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) { unsigned int start_len = total_len[i][j]; unsigned int len1 = total_len2[i][j]; for (k = 0; k < len1; ++k) input_buf[i].c[GETPOS((k+start_len), j)] = input_buf2[i].c[GETPOS(k,j)]; input_buf[i].c[GETPOS((len1+start_len), j)] = 0x80; total_len[i][j] += len1; } } return; } #endif for (; i < til; ++i) { #if MD5_X2 if (i&1) memcpy(&(input_buf_X86[i>>MD5_X2].x2.b2[total_len_X86[i]]), input_buf2_X86[i>>MD5_X2].x2.b2, total_len2_X86[i]); else #endif memcpy(&(input_buf_X86[i>>MD5_X2].x1.b[total_len_X86[i]]), input_buf2_X86[i>>MD5_X2].x1.b, total_len2_X86[i]); total_len_X86[i] += total_len2_X86[i]; } } void DynamicFunc__append_input2_from_input(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int j, k; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) { unsigned int start_len = total_len2[i][j]; unsigned int len1 = total_len[i][j]; for (k = 0; k < len1; ++k) input_buf2[i].c[GETPOS((k+start_len), j)] = input_buf[i].c[GETPOS(k,j)]; input_buf2[i].c[GETPOS((len1+start_len), j)] = 0x80; total_len2[i][j] += len1; } } return; } #endif for (; i < til; ++i) { #if MD5_X2 if (i&1) memcpy(&(input_buf2_X86[i>>MD5_X2].x2.b2[total_len2_X86[i]]), input_buf_X86[i>>MD5_X2].x2.b2, total_len_X86[i]); else #endif memcpy(&(input_buf2_X86[i>>MD5_X2].x1.b[total_len2_X86[i]]), input_buf_X86[i>>MD5_X2].x1.b, total_len_X86[i]); total_len2_X86[i] += total_len_X86[i]; } } void DynamicFunc__append_input_from_input(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int j, k; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) { unsigned int start_len = total_len[i][j]; for (k = 0; k < start_len; ++k) input_buf[i].c[GETPOS((k+start_len), j)] = input_buf[i].c[GETPOS(k,j)]; input_buf[i].c[GETPOS((start_len+start_len), j)] = 0x80; total_len[i][j] += start_len; } } return; } #endif for (; i < til; ++i) { #if MD5_X2 if (i&1) memcpy(&(input_buf_X86[i>>MD5_X2].x2.b2[total_len_X86[i]]), input_buf_X86[i>>MD5_X2].x2.b2, total_len_X86[i]); else #endif memcpy(&(input_buf_X86[i>>MD5_X2].x1.b[total_len_X86[i]]), input_buf_X86[i>>MD5_X2].x1.b, total_len_X86[i]); total_len_X86[i] <<= 1; } } void DynamicFunc__append_input2_from_input2(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int j, k; til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; ++i) { for (j = 0; j < SIMD_COEF_32; ++j) { unsigned int start_len = total_len2[i][j]; for (k = 0; k < start_len; ++k) input_buf2[i].c[GETPOS((k+start_len), j)] = input_buf2[i].c[GETPOS(k,j)]; input_buf2[i].c[GETPOS((start_len+start_len), j)] = 0x80; total_len2[i][j] += start_len; } } return; } #endif for (; i < til; ++i) { #if MD5_X2 if (i&1) memcpy(&(input_buf2_X86[i>>MD5_X2].x2.b2[total_len2_X86[i]]), input_buf2_X86[i>>MD5_X2].x2.b2, total_len2_X86[i]); else #endif memcpy(&(input_buf2_X86[i>>MD5_X2].x1.b[total_len2_X86[i]]), input_buf2_X86[i>>MD5_X2].x1.b, total_len2_X86[i]); total_len2_X86[i] <<= 1; } } #ifdef SIMD_PARA_MD5 static void SSE_Intrinsics_LoadLens_md5(int side, int i) { uint32_t *p; unsigned int j, k; if (side == 0) { for (j = 0; j < SIMD_PARA_MD5; j++) { p = input_buf[i+j].w; for (k = 0; k < SIMD_COEF_32; k++) p[14*SIMD_COEF_32+k] = total_len[i+j][k] << 3; } } else { for (j = 0; j < SIMD_PARA_MD5; j++) { p = input_buf2[i+j].w; for (k = 0; k < SIMD_COEF_32; k++) p[14*SIMD_COEF_32+k] = total_len2[i+j][k] << 3; } } } #endif #ifdef SIMD_PARA_MD4 static void SSE_Intrinsics_LoadLens_md4(int side, int i) { uint32_t *p; unsigned int j, k; if (side == 0) { for (j = 0; j < SIMD_PARA_MD4; j++) { p = input_buf[i+j].w; for (k = 0; k < SIMD_COEF_32; k++) p[14*SIMD_COEF_32+k] = total_len[i+j][k] << 3; } } else { for (j = 0; j < SIMD_PARA_MD4; j++) { p = input_buf2[i+j].w; for (k = 0; k < SIMD_COEF_32; k++) p[14*SIMD_COEF_32+k] = total_len2[i+j][k] << 3; } } } #endif /************************************************************** * DYNAMIC primitive helper function * Encrypts the data in the first input field. The data is * still in the binary encrypted format, in the crypt_key. * we do not yet convert to base-16. This is so we can output * as base-16, or later, if we add base-64, we can output to * that format instead. *************************************************************/ void DynamicFunc__crypt_md5(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; if (curdat.store_keys_in_input) { for (; i < til; i += SIMD_PARA_MD5) { SIMDmd5body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); } } else { for (; i < til; i += SIMD_PARA_MD5) { SSE_Intrinsics_LoadLens_md5(0, i); SIMDmd5body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); } } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD5(input_buf_X86[i>>MD5_X2], len, crypt_key_X86[i>>MD5_X2]); } } void DynamicFunc__crypt_md4(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; if (curdat.store_keys_in_input) { for (; i < til; i += SIMD_PARA_MD4) { SIMDmd4body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); } } else { for (; i < til; i += SIMD_PARA_MD4) { SSE_Intrinsics_LoadLens_md4(0, i); SIMDmd4body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); } } return; } #endif for (; i < til; ++i) { // MD5_X2 sets our input buffers and crypt keys up in 'double' format. Thus, we HAVE // to treat them just like we do in MD5. The macro hides the details. #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD4(input_buf_X86[i>>MD5_X2], len, crypt_key_X86[i>>MD5_X2]); } } void DynamicFunc__POCrypt(DYNA_OMP_PARAMS) { unsigned int i, j; unsigned int til, len; unsigned char *pBuf; #if MD5_X2 unsigned char *pBuf2; unsigned int lens[2]; #endif #ifdef _OPENMP til = last; i = first; #else i = 0; til = m_count; #endif //DynamicFunc__clean_input_kwik(); //DynamicFunc__append_salt, //DynamicFunc__append_input1_from_CONST1, //DynamicFunc__append_keys, //DynamicFunc__append_input1_from_CONST2, //DynamicFunc__append_salt, //DynamicFunc__crypt_md5, pBuf = input_buf_X86[i>>MD5_X2].x1.B; #if MD5_X2 pBuf2 = input_buf_X86[i>>MD5_X2].x2.B2; memset(pBuf2, 0, sizeof(input_buf_X86[i>>MD5_X2].x2.B2)); memcpy(pBuf2, cursalt, 32); pBuf2[32] = 'Y'; #endif memset(pBuf, 0, sizeof(input_buf_X86[i>>MD5_X2].x1.b)); memcpy(pBuf, cursalt, 32); pBuf[32] = 'Y'; for (j = i; j < til; ++j) { len = saved_key_len[j]; memcpy(&pBuf[33], saved_key[j], len); pBuf[33+len] = 0xf7; memcpy(&pBuf[34+len], cursalt, 32); #if MD5_X2 lens[0] = len+66; // len from the 'first' ++j; if (j < m_count) { len = saved_key_len[j]; memcpy(&pBuf2[33], saved_key[j], len); pBuf2[33+len] = 0xf7; memcpy(&pBuf2[34+len], cursalt, 32); lens[1] = len+66; } else { lens[1] = 0; } DoMD5(input_buf_X86[i>>MD5_X2], lens, crypt_key_X86[j>>MD5_X2]); #else DoMD5(input_buf_X86[i>>MD5_X2], (len+66), crypt_key_X86[j]); #endif } } /************************************************************** * DYNAMIC primitive helper function * Encrypts the data in the 2nd input field into crypt_keys2. *************************************************************/ void DynamicFunc__crypt2_md5(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD5) { SSE_Intrinsics_LoadLens_md5(1, i); SIMDmd5body(input_buf2[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len2_X86[i++]; if (i < m_count) len[1] = total_len2_X86[i]; else len[1] = 0; #else unsigned int len = total_len2_X86[i]; #endif DoMD5(input_buf2_X86[i>>MD5_X2], len, crypt_key2_X86[i>>MD5_X2]); } } void DynamicFunc__crypt2_md4(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD4) { SSE_Intrinsics_LoadLens_md4(1, i); SIMDmd4body(input_buf2[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } return; } #endif for (; i < til; ++i) { // MD5_X2 sets our input buffers and crypt keys up in 'double' format. Thus, we HAVE // to treat them just like we do in MD5. The macro hides the details. #if MD5_X2 unsigned int len[2]; len[0] = total_len2_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len2_X86[i]; #else unsigned int len = total_len2_X86[i]; #endif DoMD4(input_buf2_X86[i>>MD5_X2], len, crypt_key2_X86[i>>MD5_X2]); } } /************************************************************** * DYNAMIC primitive helper function * Encrypts the data in the 1st input field crypt_keys2. *************************************************************/ void DynamicFunc__crypt_md5_in1_to_out2(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; if (curdat.store_keys_in_input) { for (; i < til; i += SIMD_PARA_MD5) { SIMDmd5body(input_buf[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } } else { for (; i < til; i += SIMD_PARA_MD5) { SSE_Intrinsics_LoadLens_md5(0, i); SIMDmd5body(input_buf[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD5(input_buf_X86[i>>MD5_X2], len, crypt_key2_X86[i>>MD5_X2]); } } void DynamicFunc__crypt_md4_in1_to_out2(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; if (curdat.store_keys_in_input) { for (; i < til; i += SIMD_PARA_MD4) { SIMDmd4body(input_buf[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } } else { for (; i < til; i += SIMD_PARA_MD4) { SSE_Intrinsics_LoadLens_md4(0, i); SIMDmd4body(input_buf[i].c, crypt_key2[i].w, NULL, SSEi_MIXED_IN); } } return; } #endif for (; i < til; ++i) { // MD5_X2 sets our input buffers and crypt keys up in 'double' format. Thus, we HAVE // to treat them just like we do in MD5. The macro hides the details. #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD4(input_buf_X86[i>>MD5_X2], len, crypt_key2_X86[i>>MD5_X2]); } } /************************************************************** * DYNAMIC primitive helper function * Encrypts the data in the 2nd input field into crypt_keys. *************************************************************/ void DynamicFunc__crypt_md5_in2_to_out1(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD5) { SSE_Intrinsics_LoadLens_md5(1, i); SIMDmd5body(input_buf2[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); //dump_stuff_mmx_msg("DynamicFunc__crypt_md5_in2_to_out1", input_buf2[i].c,64,m_count-1); } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len2_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len2_X86[i]; #else unsigned int len = total_len2_X86[i]; #endif DoMD5(input_buf2_X86[i>>MD5_X2], len, crypt_key_X86[i>>MD5_X2]); } } void DynamicFunc__crypt_md4_in2_to_out1(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD4) { SSE_Intrinsics_LoadLens_md4(1, i); SIMDmd4body(input_buf2[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); } return; } #endif for (; i < til; ++i) { // MD5_X2 sets our input buffers and crypt keys up in 'double' format. Thus, we HAVE // to treat them just like we do in MD5. The macro hides the details. #if MD5_X2 unsigned int len[2]; len[0] = total_len2_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len2_X86[i]; #else unsigned int len = total_len2_X86[i]; #endif DoMD4(input_buf2_X86[i>>MD5_X2], len, crypt_key_X86[i>>MD5_X2]); } } void DynamicFunc__crypt_md5_to_input_raw(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD5) { unsigned int j, k; SSE_Intrinsics_LoadLens_md5(0, i); // NOTE, since crypt_key array is 16 bytes each, and input_buf is 64 bytes // each, and we are doing 3 at a time, we can NOT directly write to the // input buff, but have to use the crypt_key buffer, and then memcpy when done. SIMDmd5body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); for (j = 0; j < SIMD_PARA_MD5; ++j) { memset(input_buf[i+j].c, 0, sizeof(input_buf[0])); memcpy(input_buf[i+j].c, crypt_key[i+j].c, 16*SIMD_COEF_32); for (k = 0; k < SIMD_COEF_32; k++) total_len[i+j][k] = 16; } } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i]; total_len_X86[i++] = 0x10; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD5(input_buf_X86[i>>MD5_X2], len, input_buf_X86[i>>MD5_X2]); total_len_X86[i] = 0x10; } } void DynamicFunc__crypt_md5_to_input_raw_Overwrite_NoLen_but_setlen_in_SSE(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD5) { unsigned int j; SSE_Intrinsics_LoadLens_md5(0, i); // NOTE, since crypt_key array is 16 bytes each, and input_buf is 64 bytes // each, and we are doing 3 at a time, we can NOT directly write to the // input buff, but have to use the crypt_key buffer, and then memcpy when done. SIMDmd5body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); for (j = 0; j < SIMD_PARA_MD5; ++j) memcpy(input_buf[i+j].c, crypt_key[i+j].c, 16*SIMD_COEF_32); } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif DoMD5(input_buf_X86[i>>MD5_X2], len, input_buf_X86[i>>MD5_X2]); } } void DynamicFunc__crypt_md5_to_input_raw_Overwrite_NoLen(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { til = (til+SIMD_COEF_32-1)/SIMD_COEF_32; i /= SIMD_COEF_32; for (; i < til; i += SIMD_PARA_MD5) { unsigned int j; // NOTE, since crypt_key array is 16 bytes each, and input_buf is 64 bytes // each, and we are doing 3 at a time, we can NOT directly write to the // input buff, but have to use the crypt_key buffer, and then memcpy when done. SIMDmd5body(input_buf[i].c, crypt_key[i].w, NULL, SSEi_MIXED_IN); for (j = 0; j < SIMD_PARA_MD5; ++j) memcpy(input_buf[i+j].c, crypt_key[i+j].c, 16*SIMD_COEF_32); } return; } #endif for (; i < til; ++i) { #if MD5_X2 unsigned int len[2]; len[0] = total_len_X86[i++]; if (i == m_count) len[1] = 0; else len[1] = total_len_X86[i]; #else unsigned int len = total_len_X86[i]; #endif // we call DoMD5o so as to 'not' change then length (it was already set) DoMD5o(input_buf_X86[i>>MD5_X2], len, input_buf_X86[i>>MD5_X2]); } } void DynamicFunc__overwrite_salt_to_input1_no_size_fix(DYNA_OMP_PARAMS) { unsigned int j, til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP j = first; til = last; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, 27, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, 27, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { __SSE_append_string_to_input(input_buf[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),(unsigned char*)utf16Str,outlen,0,0); } } else { for (; j < til; ++j) __SSE_append_string_to_input_unicode(input_buf[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),(unsigned char*)cursalt,saltlen,0,0); } return; } for (; j < til; ++j) __SSE_append_string_to_input(input_buf[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),cursalt,saltlen,0,0); return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)utf16Str; #if MD5_X2 if (j&1) cp = input_buf_X86[j>>MD5_X2].x2.B2; else #endif cp = input_buf_X86[j>>MD5_X2].x1.B; for (z = 0; z < outlen; ++z) *cp++ = *cpi++; } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)cursalt; #if MD5_X2 if (j&1) cp = input_buf_X86[j>>MD5_X2].x2.B2; else #endif cp = input_buf_X86[j>>MD5_X2].x1.B; for (z = 0; z < saltlen; ++z) { *cp++ = *cpi++; *cp++ = 0; } } } return; } for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(input_buf_X86[j>>MD5_X2].x2.b2, cursalt, saltlen); else #endif memcpy(input_buf_X86[j>>MD5_X2].x1.b, cursalt, saltlen); } } void DynamicFunc__overwrite_salt_to_input2_no_size_fix(DYNA_OMP_PARAMS) { unsigned int j, til; int utf16 = md5_unicode_convert_get(tid); #ifdef _OPENMP j = first; til = last; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[27+1]; // 27 chars is 'max' that fits in SSE without overflow, so that is where we limit it at now int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, 27, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, 27, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { __SSE_append_string_to_input(input_buf2[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),(unsigned char*)utf16Str,outlen,0,0); } } else { for (; j < til; ++j) __SSE_append_string_to_input_unicode(input_buf2[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),(unsigned char*)cursalt,saltlen,0,0); } return; } for (; j < til; ++j) __SSE_append_string_to_input(input_buf2[j/SIMD_COEF_32].c,j&(SIMD_COEF_32-1),cursalt,saltlen,0,0); return; } #endif if (utf16) { if (utf16 == 2 || (options.target_enc != ASCII && options.target_enc != ISO_8859_1)) { UTF16 utf16Str[ENCODED_EFFECTIVE_MAX_LENGTH + 1]; int outlen; if (utf16 == 1) outlen = enc_to_utf16(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); else outlen = enc_to_utf16_be(utf16Str, ENCODED_EFFECTIVE_MAX_LENGTH, (unsigned char*)cursalt, saltlen) * sizeof(UTF16); if (outlen < 0) outlen = strlen16(utf16Str) * sizeof(UTF16); for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)utf16Str; #if MD5_X2 if (j&1) cp = input_buf2_X86[j>>MD5_X2].x2.B2; else #endif cp = input_buf2_X86[j>>MD5_X2].x1.B; for (z = 0; z < outlen; ++z) *cp++ = *cpi++; } } else { for (; j < til; ++j) { unsigned int z; unsigned char *cp, *cpi = (unsigned char*)cursalt; #if MD5_X2 if (j&1) cp = input_buf2_X86[j>>MD5_X2].x2.B2; else #endif cp = input_buf2_X86[j>>MD5_X2].x1.B; for (z = 0; z < saltlen; ++z) { *cp++ = *cpi++; *cp++ = 0; } } } return; } for (; j < til; ++j) { #if MD5_X2 if (j&1) memcpy(input_buf2_X86[j>>MD5_X2].x2.b2, cursalt, saltlen); else #endif memcpy(input_buf2_X86[j>>MD5_X2].x1.b, cursalt, saltlen); } } /************************************************************** * DYNAMIC primitive helper function * overwrites start of input1 from the output2 data using base-16 *************************************************************/ void DynamicFunc__overwrite_from_last_output2_to_input1_as_base16_no_size_fix(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP j = first; til = last; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; j < til; ++j) { idx = ( ((unsigned int)j)/SIMD_COEF_32); __SSE_overwrite_output_base16_to_input(input_buf[idx].w, crypt_key2[idx].c, j&(SIMD_COEF_32-1)); } return; } #endif for (; j < til; ++j) { unsigned char *cpo, *cpi; unsigned int i; /* MD5_word *w; */ #if MD5_X2 if (j&1) {cpo = input_buf_X86[j>>MD5_X2].x2.B2; cpi = crypt_key2_X86[j>>MD5_X2].x2.B2; /* w=input_buf_X86[j>>MD5_X2].x2.w2; */} else #endif {cpo = input_buf_X86[j>>MD5_X2].x1.B; cpi = crypt_key2_X86[j>>MD5_X2].x1.B; /* w=input_buf_X86[j>>MD5_X2].x1.w; */ } for (i = 0; i < 16; ++i, ++cpi) { *cpo++ = dynamic_itoa16[*cpi>>4]; *cpo++ = dynamic_itoa16[*cpi&0xF]; } //MD5_swap(w,w,4); } } /************************************************************** * DYNAMIC primitive helper function * overwrites start of input1 from the output1 data using base-16 *************************************************************/ void DynamicFunc__overwrite_from_last_output_as_base16_no_size_fix(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP j = first; til = last; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; j < til; ++j) { idx = ( ((unsigned int)j)/SIMD_COEF_32); __SSE_overwrite_output_base16_to_input(input_buf[idx].w, crypt_key[idx].c, j&(SIMD_COEF_32-1)); } return; } #endif for (; j < til; ++j) { unsigned char *cpo, *cpi; unsigned int i; /* MD5_word *w; */ #if MD5_X2 if (j&1) {cpo = input_buf_X86[j>>MD5_X2].x2.B2; cpi = crypt_key_X86[j>>MD5_X2].x2.B2; /* w=input_buf_X86[j>>MD5_X2].x2.w2; */} else #endif {cpo = input_buf_X86[j>>MD5_X2].x1.B; cpi = crypt_key_X86[j>>MD5_X2].x1.B; /* w=input_buf_X86[j>>MD5_X2].x1.w; */ } for (i = 0; i < 16; ++i, ++cpi) { *cpo++ = dynamic_itoa16[*cpi>>4]; *cpo++ = dynamic_itoa16[*cpi&0xF]; } //MD5_swap(w,w,4); } } /************************************************************** * DYNAMIC primitive helper function * This will take the data stored in the crypt_keys (the encrypted * 'first' key variable), and use a base-16 text formatting, and * append this to the first input buffer (adjusting the lengths) *************************************************************/ void DynamicFunc__append_from_last_output_as_base16(DYNA_OMP_PARAMS) { unsigned int j, til; #ifdef _OPENMP j = first; til = last; #else j = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; j < til; ++j) { unsigned int ip; idx = ( ((unsigned int)j)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len[idx][j & (SIMD_COEF_32 - 1)]; total_len[idx][j & (SIMD_COEF_32 - 1)] += 32; if (!ip) __SSE_append_output_base16_to_input(input_buf[idx].w, crypt_key[idx].c, j&(SIMD_COEF_32-1)); else if (ip&1) { // Note we are 100% unaligned, and it seems fastest to handle byte/byte (at this time). unsigned int k; for (k = 0; k < 16; ++k) { unsigned char v = crypt_key[idx].c[GETPOS(k, j&(SIMD_COEF_32-1))]; input_buf[idx].c[GETPOS(ip+(k<<1), j&(SIMD_COEF_32-1))] = dynamic_itoa16[v>>4]; input_buf[idx].c[GETPOS(ip+(k<<1)+1, j&(SIMD_COEF_32-1))] = dynamic_itoa16[v&0xF]; } input_buf[idx].c[GETPOS(ip+32, j&(SIMD_COEF_32-1))] = 0x80; } else if ((ip&3)==0) __SSE_append_output_base16_to_input_semi_aligned_0(ip, input_buf[idx].w, crypt_key[idx].c, j&(SIMD_COEF_32-1)); else __SSE_append_output_base16_to_input_semi_aligned_2(ip, input_buf[idx].w, crypt_key[idx].c, j&(SIMD_COEF_32-1)); } return; } #endif for (; j < til; ++j) { unsigned char *cp, *cpi; unsigned int i; #if MD5_X2 if (j&1) {cp = &(input_buf_X86[j>>MD5_X2].x2.B2[total_len_X86[j]]); cpi = crypt_key_X86[j>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf_X86[j>>MD5_X2].x1.B[total_len_X86[j]]); cpi = crypt_key_X86[j>>MD5_X2].x1.B; } for (i = 0; i < 16; ++i) { #if ARCH_ALLOWS_UNALIGNED *((unsigned short*)cp) = itoa16_w2[*cpi++]; cp += 2; #else unsigned char b = *cpi++; *cp++ = dynamic_itoa16[b>>4]; *cp++ = dynamic_itoa16[b&0xF]; #endif } *cp = 0; total_len_X86[j] += 32; } } /************************************************************** * DYNAMIC primitive helper function * This will take the data stored in the crypt_keys2 (the encrypted * 'second' key variable), and base-16 appends to the 2nd input *************************************************************/ void DynamicFunc__append_from_last_output2_as_base16(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; i < til; ++i) { unsigned int ip, j; idx = ( ((unsigned int)i)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len2[idx][i&(SIMD_COEF_32-1)]; total_len2[idx][i&(SIMD_COEF_32-1)] += 32; if (!ip) __SSE_append_output_base16_to_input(input_buf2[idx].w, crypt_key2[idx].c, i&(SIMD_COEF_32-1)); else if (ip&1) { // Note we are 100% unaligned, and it seems fastest to handle byte/byte (at this time). for (j = 0; j < 16; ++j) { unsigned char v = crypt_key2[idx].c[GETPOS(j, i&(SIMD_COEF_32-1))]; input_buf2[idx].c[GETPOS(ip+(j<<1), i&(SIMD_COEF_32-1))] = dynamic_itoa16[v>>4]; input_buf2[idx].c[GETPOS(ip+(j<<1)+1, i&(SIMD_COEF_32-1))] = dynamic_itoa16[v&0xF]; } input_buf2[idx].c[GETPOS(ip+32, i&(SIMD_COEF_32-1))] = 0x80; } else if ((ip&3)==0) __SSE_append_output_base16_to_input_semi_aligned_0(ip, input_buf2[idx].w, crypt_key2[idx].c, i&(SIMD_COEF_32-1)); else __SSE_append_output_base16_to_input_semi_aligned_2(ip, input_buf2[idx].w, crypt_key2[idx].c, i&(SIMD_COEF_32-1)); } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf2_X86[i>>MD5_X2].x2.B2[total_len2_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf2_X86[i>>MD5_X2].x1.B[total_len2_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) { #if ARCH_ALLOWS_UNALIGNED *((unsigned short*)cp) = itoa16_w2[*cpi++]; cp += 2; #else unsigned char b = *cpi++; *cp++ = dynamic_itoa16[b>>4]; *cp++ = dynamic_itoa16[b&0xF]; #endif } *cp = 0; total_len2_X86[i] += 32; } } /************************************************************** * DYNAMIC primitive helper function * overwrites start of input2 from the output1 data using base-16 * an optimization, if the same thing is done over and over * again, such as md5(md5(md5(md5($p)))) There, we would only * call the copy and set length once, then simply call copy. *************************************************************/ void DynamicFunc__overwrite_from_last_output_to_input2_as_base16_no_size_fix(DYNA_OMP_PARAMS) { unsigned int i, til,j; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; i < til; ++i) { idx = ( ((unsigned int)i)/SIMD_COEF_32); __SSE_overwrite_output_base16_to_input(input_buf2[idx].w, crypt_key[idx].c, i&(SIMD_COEF_32-1)); } return; } #endif j = i; for (; j < til; ++j) { unsigned char *cpo, *cpi; /* MD5_word *w; */ #if MD5_X2 if (j&1) {cpo = input_buf2_X86[j>>MD5_X2].x2.B2; cpi = crypt_key_X86[j>>MD5_X2].x2.B2; /* w=input_buf_X86[j>>MD5_X2].x2.w2; */} else #endif {cpo = input_buf2_X86[j>>MD5_X2].x1.B; cpi = crypt_key_X86[j>>MD5_X2].x1.B; /* w=input_buf_X86[j>>MD5_X2].x1.w; */ } for (i = 0; i < 16; ++i, ++cpi) { *cpo++ = dynamic_itoa16[*cpi>>4]; *cpo++ = dynamic_itoa16[*cpi&0xF]; } //MD5_swap(w,w,4); } } void DynamicFunc__overwrite_from_last_output2_to_input2_as_base16_no_size_fix(DYNA_OMP_PARAMS) { unsigned int i, til,j; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; i < til; ++i) { idx = ( ((unsigned int)i)/SIMD_COEF_32); __SSE_overwrite_output_base16_to_input(input_buf2[idx].w, crypt_key2[idx].c, i&(SIMD_COEF_32-1)); } return; } #endif j = i; for (; j < til; ++j) { unsigned char *cpo, *cpi; /* MD5_word *w; */ #if MD5_X2 if (j&1) {cpo = input_buf2_X86[j>>MD5_X2].x2.B2; cpi = crypt_key2_X86[j>>MD5_X2].x2.B2; /* w=input_buf2_X86[j>>MD5_X2].x2.w2; */} else #endif {cpo = input_buf2_X86[j>>MD5_X2].x1.B; cpi = crypt_key2_X86[j>>MD5_X2].x1.B; /* w=input_buf2_X86[j>>MD5_X2].x1.w; */ } for (i = 0; i < 16; ++i, ++cpi) { *cpo++ = dynamic_itoa16[*cpi>>4]; *cpo++ = dynamic_itoa16[*cpi&0xF]; } //MD5_swap(w,w,4); } } /************************************************************** * DYNAMIC primitive helper function * overwrites start of input2 from the output2 data using base-16 *************************************************************/ void DynamicFunc__overwrite_from_last_output2_as_base16_no_size_fix(DYNA_OMP_PARAMS) { unsigned int i, til,j; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int idx; for (; i < til; ++i) { idx = ( ((unsigned int)i)/SIMD_COEF_32); __SSE_overwrite_output_base16_to_input(input_buf2[idx].w, crypt_key2[idx].c, i&(SIMD_COEF_32-1)); } return; } #endif j=i; for (; j < til; ++j) { unsigned char *cpo, *cpi; /* MD5_word *w; */ #if MD5_X2 if (j&1) {cpo = input_buf2_X86[j>>MD5_X2].x2.B2; cpi = crypt_key2_X86[j>>MD5_X2].x2.B2; /* w=input_buf_X86[j>>MD5_X2].x2.w2; */} else #endif {cpo = input_buf2_X86[j>>MD5_X2].x1.B; cpi = crypt_key2_X86[j>>MD5_X2].x1.B; /* w=input_buf_X86[j>>MD5_X2].x1.w; */ } for (i = 0; i < 16; ++i, ++cpi) { *cpo++ = dynamic_itoa16[*cpi>>4]; *cpo++ = dynamic_itoa16[*cpi&0xF]; } //MD5_swap(w,w,4); } } /************************************************************** * DYNAMIC primitive helper function * This will take the data stored in the crypt_keys1 (the encrypted * 'first' key variable), and base-16 appends to the 2nd input *************************************************************/ void DynamicFunc__append_from_last_output_to_input2_as_base16(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index=i, idx; for (; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len2[idx][index&(SIMD_COEF_32-1)]; total_len2[idx][index&(SIMD_COEF_32-1)] += 32; if (!ip) __SSE_append_output_base16_to_input(input_buf2[idx].w, crypt_key[idx].c, index&(SIMD_COEF_32-1)); else if (ip&1) { // Note we are 100% unaligned, and it seems fastest to handle byte/byte (at this time). for (i = 0; i < 16; ++i) { unsigned char v = crypt_key[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf2[idx].c[GETPOS(ip+(i<<1), index&(SIMD_COEF_32-1))] = dynamic_itoa16[v>>4]; input_buf2[idx].c[GETPOS(ip+(i<<1)+1, index&(SIMD_COEF_32-1))] = dynamic_itoa16[v&0xF]; } input_buf2[idx].c[GETPOS(ip+32, index&(SIMD_COEF_32-1))] = 0x80; } else if ((ip&3)==0) __SSE_append_output_base16_to_input_semi_aligned_0(ip, input_buf2[idx].w, crypt_key[idx].c, index&(SIMD_COEF_32-1)); else __SSE_append_output_base16_to_input_semi_aligned_2(ip, input_buf2[idx].w, crypt_key[idx].c, index&(SIMD_COEF_32-1)); } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cpi = crypt_key_X86[i>>MD5_X2].x2.B2; cp = &(input_buf2_X86[i>>MD5_X2].x2.B2[total_len2_X86[i]]); } else #endif {cpi = crypt_key_X86[i>>MD5_X2].x1.B; cp = &(input_buf2_X86[i>>MD5_X2].x1.B[total_len2_X86[i]]);} for (j = 0; j < 16; ++j) { #if ARCH_ALLOWS_UNALIGNED *((unsigned short*)cp) = itoa16_w2[*cpi++]; cp += 2; #else unsigned char b = *cpi++; *cp++ = dynamic_itoa16[b>>4]; *cp++ = dynamic_itoa16[b&0xF]; #endif } *cp = 0; total_len2_X86[i] += 32; } } /************************************************************** * DYNAMIC primitive helper function * This will take the data stored in the crypt_keys2 (the encrypted * 'second' key variable), and base-16 appends to the 1st input *************************************************************/ void DynamicFunc__append_from_last_output2_to_input1_as_base16(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index=i, idx; for (; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len[idx][index&(SIMD_COEF_32-1)]; total_len[idx][index&(SIMD_COEF_32-1)] += 32; if (!ip) __SSE_append_output_base16_to_input(input_buf[idx].w, crypt_key2[idx].c, index&(SIMD_COEF_32-1)); else if (ip&1) { // Note we are 100% unaligned, and it seems fastest to handle byte/byte (at this time). for (i = 0; i < 16; ++i) { unsigned char v = crypt_key2[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf[idx].c[GETPOS(ip+(i<<1), index&(SIMD_COEF_32-1))] = dynamic_itoa16[v>>4]; input_buf[idx].c[GETPOS(ip+(i<<1)+1, index&(SIMD_COEF_32-1))] = dynamic_itoa16[v&0xF]; } input_buf[idx].c[GETPOS(ip+32, index&(SIMD_COEF_32-1))] = 0x80; } else if ((ip&3)==0) __SSE_append_output_base16_to_input_semi_aligned_0(ip, input_buf[idx].w, crypt_key2[idx].c, index&(SIMD_COEF_32-1)); else __SSE_append_output_base16_to_input_semi_aligned_2(ip, input_buf[idx].w, crypt_key2[idx].c, index&(SIMD_COEF_32-1)); } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf_X86[i>>MD5_X2].x2.B2[total_len_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf_X86[i>>MD5_X2].x1.B[total_len_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) { #if ARCH_ALLOWS_UNALIGNED *((unsigned short*)cp) = itoa16_w2[*cpi++]; cp += 2; #else unsigned char b = *cpi++; *cp++ = dynamic_itoa16[b>>4]; *cp++ = dynamic_itoa16[b&0xF]; #endif } *cp = 0; total_len_X86[i] += 32; } } void DynamicFunc__append_from_last_output2_as_raw(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index=i, idx; for (; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len[idx][index&(SIMD_COEF_32-1)]; if (!ip) { uint32_t *po = input_buf[idx].w; uint32_t *pi = crypt_key2[idx].w; po += (index&(SIMD_COEF_32-1)); pi += (index&(SIMD_COEF_32-1)); for (i = 0; i < 4; i++) { *po = *pi; po += SIMD_COEF_32; pi += SIMD_COEF_32; } input_buf[idx].c[GETPOS(16, index&(SIMD_COEF_32-1))] = 0x80; } else { for (i = 0; i < 16; ++i) input_buf[idx].c[GETPOS(ip+i, index&(SIMD_COEF_32-1))] = crypt_key2[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf[idx].c[GETPOS(ip+16, index&(SIMD_COEF_32-1))] = 0x80; } total_len[idx][index&(SIMD_COEF_32-1)] += 16; } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf_X86[i>>MD5_X2].x2.B2[total_len_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf_X86[i>>MD5_X2].x1.B[total_len_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) *cp++ = *cpi++; *cp = 0; total_len_X86[i] += 16; } } void DynamicFunc__append2_from_last_output2_as_raw(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index=i, idx; for (; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len2[idx][index&(SIMD_COEF_32-1)]; if (!ip) { uint32_t *po = input_buf2[idx].w; uint32_t *pi = crypt_key2[idx].w; po += (index&(SIMD_COEF_32-1)); pi += (index&(SIMD_COEF_32-1)); for (i = 0; i < 4; i++) { *po = *pi; po += SIMD_COEF_32; pi += SIMD_COEF_32; } input_buf2[idx].c[GETPOS(16, index&(SIMD_COEF_32-1))] = 0x80; } else { for (i = 0; i < 16; ++i) input_buf2[idx].c[GETPOS(ip+i, index&(SIMD_COEF_32-1))] = crypt_key2[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf2[idx].c[GETPOS(ip+16, index&(SIMD_COEF_32-1))] = 0x80; } total_len2[idx][index&(SIMD_COEF_32-1)] += 16; } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf2_X86[i>>MD5_X2].x2.B2[total_len2_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf2_X86[i>>MD5_X2].x1.B[total_len2_X86[i]]); cpi = crypt_key2_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) *cp++ = *cpi++; *cp = 0; total_len2_X86[i] += 16; } } void DynamicFunc__append_from_last_output1_as_raw(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index, idx; for (index = i; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len[idx][index&(SIMD_COEF_32-1)]; if (!ip) { uint32_t *po = input_buf[idx].w; uint32_t *pi = crypt_key[idx].w; po += (index&(SIMD_COEF_32-1)); pi += (index&(SIMD_COEF_32-1)); for (i = 0; i < 4; i++) { *po = *pi; po += SIMD_COEF_32; pi += SIMD_COEF_32; } input_buf[idx].c[GETPOS(16, index&(SIMD_COEF_32-1))] = 0x80; } else { for (i = 0; i < 16; ++i) input_buf[idx].c[GETPOS(ip+i, index&(SIMD_COEF_32-1))] = crypt_key[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf[idx].c[GETPOS(ip+16, index&(SIMD_COEF_32-1))] = 0x80; } total_len[idx][index&(SIMD_COEF_32-1)] += 16; } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf_X86[i>>MD5_X2].x2.B2[total_len_X86[i]]); cpi = crypt_key_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf_X86[i>>MD5_X2].x1.B[total_len_X86[i]]); cpi = crypt_key_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) *cp++ = *cpi++; *cp = 0; total_len_X86[i] += 16; } } void DynamicFunc__append2_from_last_output1_as_raw(DYNA_OMP_PARAMS) { unsigned int i, til; #ifdef _OPENMP i = first; til = last; #else i = 0; til = m_count; #endif #ifdef SIMD_COEF_32 if (dynamic_use_sse==1) { unsigned int index, idx; for (index = i; index < til; ++index) { unsigned int ip; idx = ( ((unsigned int)index)/SIMD_COEF_32); // This is the 'actual' work. ip = total_len2[idx][index&(SIMD_COEF_32-1)]; if (!ip) { uint32_t *po = input_buf2[idx].w; uint32_t *pi = crypt_key[idx].w; po += (index&(SIMD_COEF_32-1)); pi += (index&(SIMD_COEF_32-1)); for (i = 0; i < 4; i++) { *po = *pi; po += SIMD_COEF_32; pi += SIMD_COEF_32; } input_buf2[idx].c[GETPOS(16, index&(SIMD_COEF_32-1))] = 0x80; } else { for (i = 0; i < 16; ++i) input_buf2[idx].c[GETPOS(ip+i, index&(SIMD_COEF_32-1))] = crypt_key[idx].c[GETPOS(i, index&(SIMD_COEF_32-1))]; input_buf2[idx].c[GETPOS(ip+16, index&(SIMD_COEF_32-1))] = 0x80; } total_len2[idx][index&(SIMD_COEF_32-1)] += 16; } return; } #endif for (; i < til; ++i) { unsigned int j; unsigned char *cp, *cpi; #if MD5_X2 if (i&1) {cp = &(input_buf2_X86[i>>MD5_X2].x2.B2[total_len2_X86[i]]); cpi = crypt_key_X86[i>>MD5_X2].x2.B2; } else #endif {cp = &(input_buf2_X86[i>>MD5_X2].x1.B[total_len2_X86[i]]); cpi = crypt_key_X86[i>>MD5_X2].x1.B; } for (j = 0; j < 16; ++j) *cp++ = *cpi++; *cp = 0; total_len2_X86[i] += 16; } } /************************************************************** * DYNAMIC primitive helper function * Append salt #2 into input 1 *************************************************************/ void DynamicFunc__append_2nd_salt(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm cursalt2, saltlen2); } /************************************************************** * DYNAMIC primitive helper function * Append salt #2 into input 2 *************************************************************/ void DynamicFunc__append_2nd_salt2(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm cursalt2, saltlen2); } /************************************************************** * DYNAMIC primitive helper function * Append UserID into input 1 *************************************************************/ void DynamicFunc__append_userid(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm username, usernamelen); } /************************************************************** * DYNAMIC primitive helper function * Append UserID into input 2 *************************************************************/ void DynamicFunc__append_userid2(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm username, usernamelen); } void DynamicFunc__append_input1_from_CONST1(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[0], curdat.ConstsLen[0]); } void DynamicFunc__append_input1_from_CONST2(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[1], curdat.ConstsLen[1]); } void DynamicFunc__append_input1_from_CONST3(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[2], curdat.ConstsLen[2]); } void DynamicFunc__append_input1_from_CONST4(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[3], curdat.ConstsLen[3]); } void DynamicFunc__append_input1_from_CONST5(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[4], curdat.ConstsLen[4]); } void DynamicFunc__append_input1_from_CONST6(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[5], curdat.ConstsLen[5]); } void DynamicFunc__append_input1_from_CONST7(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[6], curdat.ConstsLen[6]); } void DynamicFunc__append_input1_from_CONST8(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm curdat.Consts[7], curdat.ConstsLen[7]); } void DynamicFunc__append_input2_from_CONST1(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[0], curdat.ConstsLen[0]); } void DynamicFunc__append_input2_from_CONST2(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[1], curdat.ConstsLen[1]); } void DynamicFunc__append_input2_from_CONST3(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[2], curdat.ConstsLen[2]); } void DynamicFunc__append_input2_from_CONST4(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[3], curdat.ConstsLen[3]); } void DynamicFunc__append_input2_from_CONST5(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[4], curdat.ConstsLen[4]); } void DynamicFunc__append_input2_from_CONST6(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[5], curdat.ConstsLen[5]); } void DynamicFunc__append_input2_from_CONST7(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[6], curdat.ConstsLen[6]); } void DynamicFunc__append_input2_from_CONST8(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm curdat.Consts[7], curdat.ConstsLen[7]); } void DynamicFunc__append_fld0(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[0], fld_lens[0]); } void DynamicFunc__append_fld1(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[1], fld_lens[1]); } void DynamicFunc__append_fld2(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[2], fld_lens[2]); } void DynamicFunc__append_fld3(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[3], fld_lens[3]); } void DynamicFunc__append_fld4(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[4], fld_lens[4]); } void DynamicFunc__append_fld5(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[5], fld_lens[5]); } void DynamicFunc__append_fld6(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[6], fld_lens[6]); } void DynamicFunc__append_fld7(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[7], fld_lens[7]); } void DynamicFunc__append_fld8(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[8], fld_lens[8]); } void DynamicFunc__append_fld9(DYNA_OMP_PARAMS) { __append_string(DYNA_OMP_PARAMSdm flds[9], fld_lens[9]); } void DynamicFunc__append2_fld0(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[0], fld_lens[0]); } void DynamicFunc__append2_fld1(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[1], fld_lens[1]); } void DynamicFunc__append2_fld2(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[2], fld_lens[2]); } void DynamicFunc__append2_fld3(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[3], fld_lens[3]); } void DynamicFunc__append2_fld4(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[4], fld_lens[4]); } void DynamicFunc__append2_fld5(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[5], fld_lens[5]); } void DynamicFunc__append2_fld6(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[6], fld_lens[6]); } void DynamicFunc__append2_fld7(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[7], fld_lens[7]); } void DynamicFunc__append2_fld8(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[8], fld_lens[8]); } void DynamicFunc__append2_fld9(DYNA_OMP_PARAMS) { __append2_string(DYNA_OMP_PARAMSdm flds[9], fld_lens[9]); } void DynamicFunc__SSEtoX86_switch_input1(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx, max; if (dynamic_use_sse == 0) return; dynamic_use_sse = 2; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = input_buf_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = input_buf_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = input_buf_X86[j+i].x1.w; #endif idx = j / SIMD_COEF_32; cpi = input_buf[idx].w; max = total_len_X86[j] = (total_len[idx][0]); for (i = 1; i < SIMD_COEF_32; i++) if (max < (total_len_X86[j+i] = total_len[idx][j])) max = total_len_X86[j+i]; max = (max+3)>>2; for (k = 0; k < max; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpo[i]++ = *cpi++; } #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { input_buf_X86[(j>>1)+(i>>1)].x1.b[total_len_X86[j+i]] = 0; input_buf_X86[(j>>1)+(i>>1)].x2.b2[total_len_X86[j+i+1]] = 0; } #else for (i = 0; i < SIMD_COEF_32; i++) input_buf_X86[j+i].x1.b[total_len_X86[j+i]] = 0; #endif } #endif } void DynamicFunc__SSEtoX86_switch_input2(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx, max; if (dynamic_use_sse == 0) return; dynamic_use_sse = 2; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = input_buf2_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = input_buf2_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = input_buf2_X86[j+i].x1.w; #endif idx = j / SIMD_COEF_32; cpi = input_buf2[idx].w; max = total_len2_X86[j] = (total_len2[idx][0]); for (i = 1; i < SIMD_COEF_32; i++) if (max < (total_len2_X86[j+i] = total_len2[idx][i])) max = total_len2_X86[j+i]; max = (max+3)>>2; for (k = 0; k < max; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpo[i]++ = *cpi++; } // get rid of the 0x80 #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { input_buf2_X86[(j>>1)+(i>>1)].x1.b[total_len_X86[j+i]] = 0; input_buf2_X86[(j>>1)+(i>>1)].x2.b2[total_len_X86[j+i+1]] = 0; } #else for (i = 0; i < SIMD_COEF_32; i++) input_buf2_X86[j+i].x1.b[total_len2_X86[j+i]] = 0; #endif } #endif } void DynamicFunc__SSEtoX86_switch_output1(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx; if (dynamic_use_sse == 0) return; dynamic_use_sse = 2; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if MD5_X2 for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = crypt_key_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = crypt_key_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = crypt_key_X86[j+i].x1.w; #endif idx = j/SIMD_COEF_32; cpi = (void*)crypt_key[idx].c; for (k = 0; k < 4; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpo[i]++ = *cpi++; } } #endif } void DynamicFunc__SSEtoX86_switch_output2(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx; if (dynamic_use_sse == 0) return; dynamic_use_sse = 2; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = crypt_key2_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = crypt_key2_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = crypt_key2_X86[j+i].x1.w; #endif idx = j / SIMD_COEF_32; cpi = crypt_key2[idx].w; for (k = 0; k < 4; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpo[i]++ = *cpi++; } } #endif } void DynamicFunc__X86toSSE_switch_input1(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int j, idx, idx_mod; if (dynamic_use_sse == 0) return; dynamic_use_sse = 1; __nonMP_DynamicFunc__clean_input(); for (j = 0; j < m_count; ++j) { idx = j/SIMD_COEF_32; idx_mod = j&(SIMD_COEF_32-1); total_len[idx][idx_mod] += total_len_X86[j]; #if (MD5_X2) if (j & 1) __SSE_append_string_to_input(input_buf[idx].c,idx_mod,input_buf_X86[j>>1].x2.B2,total_len_X86[j],0,1); else #endif __SSE_append_string_to_input(input_buf[idx].c,idx_mod,input_buf_X86[j>>MD5_X2].x1.B,total_len_X86[j],0,1); } #endif } void DynamicFunc__X86toSSE_switch_input2(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int j, idx, idx_mod; if (dynamic_use_sse == 0) return; dynamic_use_sse = 1; __nonMP_DynamicFunc__clean_input2(); for (j = 0; j < m_count; ++j) { idx = j/SIMD_COEF_32; idx_mod = j&(SIMD_COEF_32-1); total_len2[idx][idx_mod] += total_len2_X86[j]; #if (MD5_X2) if (j & 1) __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,input_buf2_X86[j>>1].x2.B2,total_len2_X86[j],0,1); else #endif __SSE_append_string_to_input(input_buf2[idx].c,idx_mod,input_buf2_X86[j>>MD5_X2].x1.B,total_len2_X86[j],0,1); } #endif } void DynamicFunc__X86toSSE_switch_output1(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx; if (dynamic_use_sse == 0) return; dynamic_use_sse = 1; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = crypt_key_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = crypt_key_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = crypt_key_X86[j+i].x1.w; #endif idx = j / SIMD_COEF_32; cpi = (void*)crypt_key[idx].c; for (k = 0; k < 4; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpi++ = *cpo[i]++; } } #endif } void DynamicFunc__X86toSSE_switch_output2(DYNA_OMP_PARAMS) { #ifdef SIMD_COEF_32 unsigned int i, j, k, idx; if (dynamic_use_sse == 0) return; dynamic_use_sse = 1; for (j = 0; j < m_count; j += SIMD_COEF_32) { uint32_t *cpi; uint32_t *cpo[SIMD_COEF_32]; #if (MD5_X2) for (i = 0; i < SIMD_COEF_32; i += 2) { cpo[i ] = crypt_key2_X86[(j>>1)+(i>>1)].x1.w; cpo[i+1] = crypt_key2_X86[(j>>1)+(i>>1)].x2.w2; } #else for (i = 0; i < SIMD_COEF_32; i++) cpo[i] = crypt_key2_X86[j+i].x1.w; #endif idx = j / SIMD_COEF_32; cpi = crypt_key2[idx].w; for (k = 0; k < 4; ++k) { for (i = 0; i < SIMD_COEF_32; i++) *cpi++ = *cpo[i]++; } } #endif } // This function, simply 'switches' back to SSE It does NOT copy any data from X86 to SSE void DynamicFunc__ToSSE(DYNA_OMP_PARAMS) { if (dynamic_use_sse == 0) return; dynamic_use_sse = 1; } // This function, simply 'switches' to X86 It does NOT copy any data from SSE to X86 void DynamicFunc__ToX86(DYNA_OMP_PARAMS) { if (dynamic_use_sse == 0) return; dynamic_use_sse = 2; } void DynamicFunc__base16_convert_locase(DYNA_OMP_PARAMS) { dynamic_itoa16 = itoa16; itoa16_w2=itoa16_w2_l; } void DynamicFunc__base16_convert_upcase(DYNA_OMP_PARAMS) { dynamic_itoa16 = itoa16u; itoa16_w2=itoa16_w2_u; } /************************************************************** * DEPRICATED functions. These are the older pseudo functions * which we now have flags for. We keep them, so that we can * add the proper flags, even if the user is running an older * script. *************************************************************/ void DynamicFunc__InitialLoadKeysToInput(DYNA_OMP_PARAMS) {} void DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2(DYNA_OMP_PARAMS) {} void DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1(DYNA_OMP_PARAMS) {} void DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1_offset32(DYNA_OMP_PARAMS) {} /************************************************************** ************************************************************** ************************************************************** ************************************************************** * DYNAMIC primitive helper function * This is the END of the primitives. ************************************************************** ************************************************************** ************************************************************** *************************************************************/ static DYNAMIC_primitive_funcp *ConvertFuncs(DYNAMIC_primitive_funcp p, unsigned int *count) { static DYNAMIC_primitive_funcp fncs[20]; *count = 0; if (p==DynamicFunc__InitialLoadKeysToInput || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2 || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1 || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1_offset32) return fncs; // ignore these #ifndef SIMD_COEF_32 if (p==DynamicFunc__SSEtoX86_switch_input1 || p==DynamicFunc__SSEtoX86_switch_input2 || p==DynamicFunc__SSEtoX86_switch_output1 || p==DynamicFunc__SSEtoX86_switch_output2 || p==DynamicFunc__X86toSSE_switch_input1 || p==DynamicFunc__X86toSSE_switch_input2 || p==DynamicFunc__X86toSSE_switch_output1 || p==DynamicFunc__X86toSSE_switch_output2 || p==DynamicFunc__ToSSE || p==DynamicFunc__ToX86) return fncs; // we ignore these functions 100% in x86 mode. #endif // if (p==DynamicFunc__append_input2_from_CONST1) { // fncs[0] = DynamicFunc__set_input2; // fncs[1] = DynamicFunc__set_CONST1; // fncs[2] = DynamicFunc__append_CONST; // *count = 3; // } /* LOOK INTO THIS!!!!! This may not be valid, now that SHA1 is handled 100% outside of the SSE2 code. But I am not sure just WTF this is supposed to do anyway, since not LE should be using CTX only??? */ #if !ARCH_LITTLE_ENDIAN if (/*p==DynamicFunc__SHA1_crypt_input1_append_input2_base16 ||*/ p==DynamicFunc__SHA1_crypt_input1_append_input2 || /*p==DynamicFunc__SHA1_crypt_input2_append_input1_base16 ||*/ p==DynamicFunc__SHA1_crypt_input2_append_input1 || /*p==DynamicFunc__SHA1_crypt_input1_overwrite_input1_base16 ||*/ p==DynamicFunc__SHA1_crypt_input1_overwrite_input1 || /*p==DynamicFunc__SHA1_crypt_input2_overwrite_input2_base16 ||*/ p==DynamicFunc__SHA1_crypt_input2_overwrite_input2 || /*p==DynamicFunc__SHA1_crypt_input1_overwrite_input2_base16 ||*/ p==DynamicFunc__SHA1_crypt_input1_overwrite_input2 || /*p==DynamicFunc__SHA1_crypt_input2_overwrite_input1_base16 ||*/ p==DynamicFunc__SHA1_crypt_input2_overwrite_input1 || p==DynamicFunc__SHA1_crypt_input1_to_output1_FINAL || p==DynamicFunc__SHA1_crypt_input2_to_output1_FINAL) curdat.force_md5_ctx = 0; #endif *count = 1; fncs[0] = p; return fncs; } #ifdef _OPENMP static int isBadOMPFunc(DYNAMIC_primitive_funcp p) { // If ANY of these functions are seen, we can NOT use OMP for this single format. #if SIMD_COEF_32 if (p==DynamicFunc__SSEtoX86_switch_input1 || p==DynamicFunc__SSEtoX86_switch_input2 || p==DynamicFunc__SSEtoX86_switch_output1 || p==DynamicFunc__SSEtoX86_switch_output2 || p==DynamicFunc__X86toSSE_switch_input1 || p==DynamicFunc__X86toSSE_switch_input2 || p==DynamicFunc__X86toSSE_switch_output1 || p==DynamicFunc__X86toSSE_switch_output2 || p==DynamicFunc__ToSSE || p==DynamicFunc__ToX86) return 1; #endif if (p==DynamicFunc__base16_convert_locase || p==DynamicFunc__base16_convert_upcase) return 1; return 0; } #endif #define RETURN_TRUE_IF_BIG_FUNC(H) if (p==DynamicFunc__##H##_crypt_input1_append_input2 || \ p==DynamicFunc__##H##_crypt_input2_append_input1 || \ p==DynamicFunc__##H##_crypt_input1_overwrite_input1 || \ p==DynamicFunc__##H##_crypt_input2_overwrite_input2 || \ p==DynamicFunc__##H##_crypt_input1_overwrite_input2 || \ p==DynamicFunc__##H##_crypt_input2_overwrite_input1 || \ p==DynamicFunc__##H##_crypt_input1_to_output1_FINAL || \ p==DynamicFunc__##H##_crypt_input2_to_output1_FINAL) \ return 1 static int isMD4Func(DYNAMIC_primitive_funcp p) { // handle flats RETURN_TRUE_IF_BIG_FUNC(MD4); // handle older mmx_coef variants if (p==DynamicFunc__crypt_md4 || p==DynamicFunc__crypt_md4_in1_to_out2 || p==DynamicFunc__crypt2_md4 || p==DynamicFunc__crypt_md4_in2_to_out1) return 1; return 0; } #ifdef _OPENMP // Only used in OMP code, to compute LCM granularity. So we #ifdef it out to avoid compiler warnings. #ifdef SIMD_COEF_32 // otherwise unused static int isMD5Func(DYNAMIC_primitive_funcp p) { // handle flats RETURN_TRUE_IF_BIG_FUNC(MD5); // handle older mmx_coef variants if (p==DynamicFunc__crypt_md5 || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1 || p==DynamicFunc__crypt_md5_in1_to_out2 || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2 || p==DynamicFunc__crypt_md5_to_input_raw || p==DynamicFunc__crypt_md5_to_input_raw_Overwrite_NoLen || p==DynamicFunc__crypt_md5_in2_to_out1 || p==DynamicFunc__crypt_md5_to_input_raw_Overwrite_NoLen_but_setlen_in_SSE || p==DynamicFunc__crypt2_md5 || p==DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1_offset32) return 1; return 0; } #endif #endif static int isSHA1Func(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(SHA1); return 0; } static int isSHA2_256Func(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(SHA224); RETURN_TRUE_IF_BIG_FUNC(SHA256); return 0; } static int isSHA2_512Func(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(SHA384); RETURN_TRUE_IF_BIG_FUNC(SHA512); return 0; } static int isGOSTFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(GOST); return 0; } static int isTigerFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(Tiger); return 0; } static int isWHIRLFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(WHIRLPOOL); return 0; } static int isRIPEMDFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(RIPEMD128); RETURN_TRUE_IF_BIG_FUNC(RIPEMD160); RETURN_TRUE_IF_BIG_FUNC(RIPEMD256); RETURN_TRUE_IF_BIG_FUNC(RIPEMD320); return 0; } static int isHAVALFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(HAVAL128_3); RETURN_TRUE_IF_BIG_FUNC(HAVAL128_4); RETURN_TRUE_IF_BIG_FUNC(HAVAL128_5); RETURN_TRUE_IF_BIG_FUNC(HAVAL160_3); RETURN_TRUE_IF_BIG_FUNC(HAVAL160_4); RETURN_TRUE_IF_BIG_FUNC(HAVAL160_5); RETURN_TRUE_IF_BIG_FUNC(HAVAL192_3); RETURN_TRUE_IF_BIG_FUNC(HAVAL192_4); RETURN_TRUE_IF_BIG_FUNC(HAVAL192_5); RETURN_TRUE_IF_BIG_FUNC(HAVAL224_3); RETURN_TRUE_IF_BIG_FUNC(HAVAL224_4); RETURN_TRUE_IF_BIG_FUNC(HAVAL224_5); RETURN_TRUE_IF_BIG_FUNC(HAVAL256_3); RETURN_TRUE_IF_BIG_FUNC(HAVAL256_4); RETURN_TRUE_IF_BIG_FUNC(HAVAL256_5); return 0; } static int isMD2Func(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(MD2); return 0; } static int isPANAMAFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(PANAMA); return 0; } static int isSKEINFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(SKEIN224); RETURN_TRUE_IF_BIG_FUNC(SKEIN256); RETURN_TRUE_IF_BIG_FUNC(SKEIN384); RETURN_TRUE_IF_BIG_FUNC(SKEIN512); return 0; } static int isKECCAKFunc(DYNAMIC_primitive_funcp p) { RETURN_TRUE_IF_BIG_FUNC(SHA3_224); RETURN_TRUE_IF_BIG_FUNC(SHA3_256); RETURN_TRUE_IF_BIG_FUNC(SHA3_384); RETURN_TRUE_IF_BIG_FUNC(SHA3_512); RETURN_TRUE_IF_BIG_FUNC(KECCAK_256); RETURN_TRUE_IF_BIG_FUNC(KECCAK_512); return 0; } // LARGE_HASH_EDIT_POINT (Add a new IsXXXFunc() type function) static int isLargeHashFinalFunc(DYNAMIC_primitive_funcp p) { #undef IF #define IF(H) p==DynamicFunc__##H##_crypt_input1_to_output1_FINAL||p==DynamicFunc__##H##_crypt_input2_to_output1_FINAL if (IF(SHA1)||IF(SHA224)||IF(SHA256)||IF(SHA384)||IF(SHA512)||IF(GOST)||IF(WHIRLPOOL)||IF(Tiger)||IF(RIPEMD128)|| IF(RIPEMD160)||IF(RIPEMD256)||IF(RIPEMD320)|| IF(HAVAL128_3)||IF(HAVAL128_4)||IF(HAVAL128_5)||IF(HAVAL160_3)||IF(HAVAL160_4)||IF(HAVAL160_5)|| IF(HAVAL192_3)||IF(HAVAL192_4)||IF(HAVAL192_5)||IF(HAVAL224_3)||IF(HAVAL224_4)||IF(HAVAL224_5)|| IF(HAVAL256_3)||IF(HAVAL256_4)||IF(HAVAL256_5)||IF(MD2)||IF(PANAMA)||IF(SKEIN224)||IF(SKEIN256)|| IF(SKEIN384)||IF(SKEIN512)||IF(SHA3_224)||IF(SHA3_256)||IF(SHA3_384)||IF(SHA3_512)|| IF(KECCAK_256)||IF(KECCAK_512)) // LARGE_HASH_EDIT_POINT return 1; return 0; } #ifdef _OPENMP #ifdef SIMD_COEF_32 // Simple euclid algorithm for GCD static int GCD (int a, int b) { while (b) { int t = b; b = a % b; a = t; } return a; } // simple algorithm for LCM is (a*b)/GCD(a,b) static int LCM(int a, int b) { a/=GCD(a,b); return a*b; } #endif static void dyna_setupOMP(DYNAMIC_Setup *Setup, struct fmt_main *pFmt) { unsigned int i; #ifndef SIMD_COEF_32 curdat.omp_granularity=OMP_INC; #else if ((curdat.pSetup->flags& MGF_NOTSSE2Safe) == MGF_NOTSSE2Safe) curdat.omp_granularity=OMP_INC; else { curdat.omp_granularity = 1; for (i=0; Setup->pFuncs[i]; ++i) { if (isMD5Func(Setup->pFuncs[i])) curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_PARA_MD5*SIMD_COEF_32); else if (isMD4Func(Setup->pFuncs[i])) curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_PARA_MD4*SIMD_COEF_32); else if (isSHA1Func(Setup->pFuncs[i])) curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_PARA_SHA1*SIMD_COEF_32); else if (isSHA2_256Func(Setup->pFuncs[i])) #if SIMD_COEF_32 #if SIMD_PARA_SHA256 curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_PARA_SHA256*SIMD_COEF_32); #else curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_COEF_32); #endif #else curdat.omp_granularity=LCM(curdat.omp_granularity, OMP_INC); #endif else if (isSHA2_512Func(Setup->pFuncs[i])) #if SIMD_COEF_64 #if SIMD_PARA_SHA512 curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_PARA_SHA512*SIMD_COEF_64); #else curdat.omp_granularity = LCM(curdat.omp_granularity, SIMD_COEF_64); #endif #else curdat.omp_granularity=LCM(curdat.omp_granularity, OMP_INC); #endif } } #endif for (i=0; Setup->pFuncs[i]; ++i) { if (isBadOMPFunc(Setup->pFuncs[i])) pFmt->params.flags &= (~(FMT_OMP|FMT_OMP_BAD)); } if ((pFmt->params.flags&FMT_OMP)==FMT_OMP && (curdat.pSetup->startFlags&MGF_POOR_OMP)==MGF_POOR_OMP) pFmt->params.flags |= FMT_OMP_BAD; } #endif int dynamic_SETUP(DYNAMIC_Setup *Setup, struct fmt_main *pFmt) { unsigned int i, j, cnt, cnt2, x; DYNAMIC_primitive_funcp *pFuncs; if (Setup->flags & MGF_ColonNOTValid) { extern struct options_main options; if (options.loader.field_sep_char == ':') { return 0; } } // Deal with depricated 1st functions. Convert them to proper 'flags' if (Setup->pFuncs[0] == DynamicFunc__InitialLoadKeysToInput) Setup->startFlags |= MGF_KEYS_INPUT; if (Setup->pFuncs[0] == DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2) Setup->startFlags |= MGF_KEYS_CRYPT_IN2; if (Setup->pFuncs[0] == DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1) Setup->startFlags |= MGF_KEYS_BASE16_IN1; if (Setup->pFuncs[0] == DynamicFunc__InitialLoadKeys_md5crypt_ToOutput2_Base16_to_Input1_offset32) Setup->startFlags |= MGF_KEYS_BASE16_IN1_Offset32; curdat.dynamic_40_byte_input = ((Setup->startFlags&MGF_INPUT_20_BYTE)==MGF_INPUT_20_BYTE) ? 1 : 0; curdat.dynamic_48_byte_input = ((Setup->startFlags&MGF_INPUT_24_BYTE)==MGF_INPUT_24_BYTE) ? 1 : 0; curdat.dynamic_64_byte_input = ((Setup->startFlags&MGF_INPUT_32_BYTE)==MGF_INPUT_32_BYTE) ? 1 : 0; curdat.dynamic_56_byte_input = ((Setup->startFlags&MGF_INPUT_28_BYTE)==MGF_INPUT_28_BYTE) ? 1 : 0; curdat.dynamic_80_byte_input = ((Setup->startFlags&MGF_INPUT_40_BYTE)==MGF_INPUT_40_BYTE) ? 1 : 0; curdat.dynamic_96_byte_input = ((Setup->startFlags&MGF_INPUT_48_BYTE)==MGF_INPUT_48_BYTE) ? 1 : 0; curdat.dynamic_128_byte_input= ((Setup->startFlags&MGF_INPUT_64_BYTE)==MGF_INPUT_64_BYTE) ? 1 : 0; curdat.FldMask = 0; curdat.b2Salts = ((Setup->flags&MGF_SALTED2)==MGF_SALTED2) ? 1 : 0; curdat.dynamic_base16_upcase = ((Setup->flags&MGF_BASE_16_OUTPUT_UPCASE)==MGF_BASE_16_OUTPUT_UPCASE) ? 1 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD0)==MGF_FLD0) ? MGF_FLD0 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD1)==MGF_FLD1) ? MGF_FLD1 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD2)==MGF_FLD2) ? MGF_FLD2 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD3)==MGF_FLD3) ? MGF_FLD3 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD4)==MGF_FLD4) ? MGF_FLD4 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD5)==MGF_FLD5) ? MGF_FLD5 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD6)==MGF_FLD6) ? MGF_FLD6 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD7)==MGF_FLD7) ? MGF_FLD7 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD8)==MGF_FLD8) ? MGF_FLD8 : 0; curdat.FldMask |= ((Setup->flags&MGF_FLD9)==MGF_FLD9) ? MGF_FLD9 : 0; curdat.dynamic_base64_inout = 0; curdat.dynamic_salt_as_hex = 0; curdat.dynamic_salt_as_hex_format_type = 0; curdat.force_md5_ctx = 0; curdat.nUserName = 0; curdat.nPassCase = 1; curdat.md5_startup_in_x86 = curdat.dynamic_use_sse = 0; // if 0, then never use SSE2 curdat.init = 0; curdat.pSetup = Setup; pFmt->methods.binary = get_binary; pFmt->methods.cmp_all=cmp_all; pFmt->methods.cmp_one=cmp_one; pFmt->methods.source=fmt_default_source; pFmt->methods.salt = get_salt; pFmt->methods.done = done; pFmt->methods.set_salt = set_salt; pFmt->methods.salt_hash = salt_hash; //pFmt->params.format_name = str_alloc_copy(Setup->szFORMAT_NAME); pFmt->params.format_name = ""; pFmt->params.benchmark_length = 0; // NOTE 0 'assumes' salted. If unsalted, we set back to -1 pFmt->params.salt_size = 0; curdat.using_flat_buffers_sse2_ok = 0; // used to distingish MGF_NOTSSE2Safe from MGF_FLAT_BUFFERS if ((Setup->flags & MGF_FLAT_BUFFERS) == MGF_FLAT_BUFFERS) curdat.using_flat_buffers_sse2_ok = 1; #ifdef SIMD_COEF_32 curdat.dynamic_use_sse = 1; // if 1, then we are in SSE2 mode (but can switch out) if ((Setup->flags & MGF_NOTSSE2Safe) == MGF_NOTSSE2Safe) { curdat.dynamic_use_sse = 0; // Do not use SSE code at all. } else if ((Setup->flags & MGF_FLAT_BUFFERS) == MGF_FLAT_BUFFERS) { curdat.dynamic_use_sse = 0; // uses flat buffers but will use SSE code (large formats use the flat buffers, and the SSE2 code 'mixes' them). curdat.using_flat_buffers_sse2_ok = 1; } else if ((Setup->flags & MGF_StartInX86Mode) == MGF_StartInX86Mode) { curdat.dynamic_use_sse = 2; // if 2, then we are in SSE2 mode, but currently using X86 (and can switch back to SSE2). curdat.md5_startup_in_x86 = 1; } if (curdat.dynamic_use_sse || curdat.using_flat_buffers_sse2_ok) { pFmt->params.max_keys_per_crypt = MAX_KEYS_PER_CRYPT; pFmt->params.algorithm_name = ALGORITHM_NAME; } else { pFmt->params.max_keys_per_crypt = MAX_KEYS_PER_CRYPT_X86; pFmt->params.algorithm_name = ALGORITHM_NAME_X86; } #else pFmt->params.max_keys_per_crypt = MAX_KEYS_PER_CRYPT_X86; pFmt->params.algorithm_name = ALGORITHM_NAME_X86; #endif pFmt->params.min_keys_per_crypt = pFmt->params.max_keys_per_crypt; if (pFmt->params.min_keys_per_crypt > 64) pFmt->params.min_keys_per_crypt = 64; dynamic_use_sse = curdat.dynamic_use_sse; // Ok, set the new 'constants' data memset(curdat.Consts, 0, sizeof(curdat.Consts)); memset(curdat.ConstsLen, 0, sizeof(curdat.ConstsLen)); for (curdat.nConsts = 0; curdat.nConsts < 8; ++curdat.nConsts) { if (Setup->pConstants[curdat.nConsts].Const == NULL) break; //curdat.Consts[curdat.nConsts] = (unsigned char*)str_alloc_copy(Setup->pConstants[curdat.nConsts].Const); //curdat.ConstsLen[curdat.nConsts] = strlen(Setup->pConstants[curdat.nConsts].Const); // we really do not 'have' to null terminate, but do just to be on the 'safe' side. curdat.Consts[curdat.nConsts] = mem_alloc_tiny(Setup->pConstants[curdat.nConsts].len+1, MEM_ALIGN_NONE); memcpy(curdat.Consts[curdat.nConsts], Setup->pConstants[curdat.nConsts].Const, Setup->pConstants[curdat.nConsts].len); curdat.Consts[curdat.nConsts][Setup->pConstants[curdat.nConsts].len] = 0; curdat.ConstsLen[curdat.nConsts] = Setup->pConstants[curdat.nConsts].len; } if ( (Setup->flags & MGF_INPBASE64) == MGF_INPBASE64) { curdat.dynamic_base64_inout = 1; pFmt->methods.binary = binary_b64; } if ( (Setup->flags & MGF_INPBASE64m) == MGF_INPBASE64m) { curdat.dynamic_base64_inout = 3; pFmt->methods.binary = binary_b64m; } if ( (Setup->flags & MGF_INPBASE64b) == MGF_INPBASE64b) { curdat.dynamic_base64_inout = 5; pFmt->methods.binary = binary_b64b; } if ( (Setup->flags & MGF_INPBASE64_4x6) == MGF_INPBASE64_4x6) { curdat.dynamic_base64_inout = 2; pFmt->methods.binary = binary_b64_4x6; pFmt->methods.cmp_all = cmp_all_64_4x6; pFmt->methods.cmp_one = cmp_one_64_4x6; #if !ARCH_LITTLE_ENDIAN pFmt->methods.binary_hash[0] = binary_hash_0_64x4; pFmt->methods.binary_hash[1] = binary_hash_1_64x4; pFmt->methods.binary_hash[2] = binary_hash_2_64x4; pFmt->methods.binary_hash[3] = binary_hash_3_64x4; pFmt->methods.binary_hash[4] = binary_hash_4_64x4; pFmt->methods.binary_hash[5] = binary_hash_5_64x4; pFmt->methods.get_hash[0] = get_hash_0_64x4; pFmt->methods.get_hash[1] = get_hash_1_64x4; pFmt->methods.get_hash[2] = get_hash_2_64x4; pFmt->methods.get_hash[3] = get_hash_3_64x4; pFmt->methods.get_hash[4] = get_hash_4_64x4; pFmt->methods.get_hash[5] = get_hash_5_64x4; #endif // Not enough bits in a single WORD if (PASSWORD_HASH_SIZE_6 >= 0x1000000) { pFmt->methods.binary_hash[6] = NULL; pFmt->methods.get_hash[6] = NULL; } if (PASSWORD_HASH_SIZE_5 >= 0x1000000) { pFmt->methods.binary_hash[5] = NULL; pFmt->methods.get_hash[5] = NULL; } if (PASSWORD_HASH_SIZE_4 >= 0x1000000) { pFmt->methods.binary_hash[4] = NULL; pFmt->methods.get_hash[4] = NULL; } if (PASSWORD_HASH_SIZE_3 >= 0x1000000) { pFmt->methods.binary_hash[3] = NULL; pFmt->methods.get_hash[3] = NULL; } } // printf("%.13s",Setup->szFORMAT_NAME); if ( (Setup->flags & (MGF_INPBASE64|MGF_INPBASE64_4x6|MGF_INPBASE64a|MGF_INPBASE64m|MGF_INPBASE64b)) == 0) { pFmt->params.flags |= FMT_SPLIT_UNIFIES_CASE; // printf(" Setting FMT_SPLIT_UNIFIES_CASE"); if (pFmt->methods.split == split) { pFmt->methods.split = split_UC; // printf(" split set to split_UC()\n"); } } // else printf(" split set to split()\n"); if (Setup->flags & MGF_UTF8) pFmt->params.flags |= FMT_UTF8; if (Setup->flags & MGF_INPBASE64a) { curdat.dynamic_base64_inout = 1; pFmt->methods.binary = binary_b64a; } if ( (Setup->flags & MGF_USERNAME) == MGF_USERNAME) curdat.nUserName = 1; if ( (Setup->flags & MGF_USERNAME_UPCASE) == MGF_USERNAME_UPCASE) curdat.nUserName = 2; if ( (Setup->flags & MGF_USERNAME_LOCASE) == MGF_USERNAME_LOCASE) curdat.nUserName = 3; // Ok, what 'flag' in the format struct, do we clear??? if ( (Setup->flags & MGF_PASSWORD_UPCASE) == MGF_PASSWORD_UPCASE) { curdat.nPassCase = 2; pFmt->params.flags &= (~FMT_CASE); } if ( (Setup->flags & MGF_PASSWORD_LOCASE) == MGF_PASSWORD_LOCASE) { curdat.nPassCase = 3; pFmt->params.flags &= (~FMT_CASE); } if ( (Setup->flags & MGF_SALT_AS_HEX) == MGF_SALT_AS_HEX) { curdat.dynamic_salt_as_hex = 1; curdat.dynamic_salt_as_hex_format_type = Setup->flags >> 56; } if ( (Setup->flags & MGF_SALT_AS_HEX_TO_SALT2) == MGF_SALT_AS_HEX_TO_SALT2) { curdat.dynamic_salt_as_hex = 2; if (curdat.b2Salts) return !fprintf(stderr, "Error invalid format %s: MGF_SALT_AS_HEX_TO_SALT2 and MGF_SALTED2 are not valid to use in same format\n", Setup->szFORMAT_NAME); curdat.b2Salts = 2; } if ( (Setup->flags & MGF_SALT_UNICODE_B4_CRYPT) == MGF_SALT_UNICODE_B4_CRYPT && curdat.dynamic_salt_as_hex) curdat.dynamic_salt_as_hex |= 0x100; if ( (Setup->flags & MGF_SALTED) == 0) { curdat.dynamic_FIXED_SALT_SIZE = 0; pFmt->params.benchmark_length = -1; pFmt->params.salt_size = 0; } else { pFmt->params.salt_size = sizeof(void *); if (Setup->SaltLen > 0) curdat.dynamic_FIXED_SALT_SIZE = Setup->SaltLen; else { // says we have a salt, but NOT a fixed sized one that we 'know' about. // if the SaltLen is -1, then there is NO constraints. If the SaltLen // is -12 (or any other neg number other than -1), then there is no // fixed salt length, but the 'max' salt size is -SaltLen. So, -12 // means any salt from 1 to 12 is 'valid'. if (Setup->SaltLen > -2) curdat.dynamic_FIXED_SALT_SIZE = -1; else { curdat.dynamic_FIXED_SALT_SIZE = Setup->SaltLen; #if !defined (SIMD_COEF_32) // for non-sse, we limit ourselves to 110 bytes, not 55. So, we can add 55 to this value curdat.dynamic_FIXED_SALT_SIZE -= 55; #endif } } } if (Setup->MaxInputLen) pFmt->params.plaintext_length = Setup->MaxInputLen; else { if ( ((Setup->flags&MGF_FLAT_BUFFERS)==MGF_FLAT_BUFFERS) || ((Setup->flags&MGF_NOTSSE2Safe)==MGF_NOTSSE2Safe)) { pFmt->params.plaintext_length = 110 - abs(Setup->SaltLen); if (pFmt->params.plaintext_length < 32) pFmt->params.plaintext_length = 32; } else { pFmt->params.plaintext_length = 55 - abs(Setup->SaltLen); if (pFmt->params.plaintext_length < 1) { pFmt->params.plaintext_length = 1; fprintf(stderr, "\nError, for format %s, MMX build, is not valid due to TOO long of a SaltLength\n", Setup->szFORMAT_NAME); } } } #ifndef SIMD_COEF_32 if (Setup->MaxInputLenX86) { pFmt->params.plaintext_length = Setup->MaxInputLenX86; } else { if (Setup->SaltLenX86) pFmt->params.plaintext_length = 110 - abs(Setup->SaltLenX86); else pFmt->params.plaintext_length = 110 - abs(Setup->SaltLen); if (pFmt->params.plaintext_length < 32) pFmt->params.plaintext_length = 32; } #endif curdat.store_keys_in_input = !!(Setup->startFlags&MGF_KEYS_INPUT ); curdat.input2_set_len32 = !!(Setup->startFlags&MGF_SET_INP2LEN32); if (Setup->startFlags&MGF_SOURCE) { if (Setup->startFlags&MGF_INPUT_20_BYTE) pFmt->methods.source = source_20_hex; else if (Setup->startFlags&MGF_INPUT_28_BYTE) pFmt->methods.source = source_28_hex; else if (Setup->startFlags&MGF_INPUT_32_BYTE) pFmt->methods.source = source_32_hex; else if (Setup->startFlags&MGF_INPUT_40_BYTE) pFmt->methods.source = source_40_hex; else if (Setup->startFlags&MGF_INPUT_48_BYTE) pFmt->methods.source = source_48_hex; else if (Setup->startFlags&MGF_INPUT_64_BYTE) pFmt->methods.source = source_64_hex; else pFmt->methods.source = source; } if (!curdat.store_keys_in_input && Setup->startFlags&MGF_KEYS_INPUT_BE_SAFE) curdat.store_keys_in_input = 3; curdat.store_keys_in_input_unicode_convert = !!(Setup->startFlags&MGF_KEYS_UNICODE_B4_CRYPT); if (curdat.store_keys_in_input_unicode_convert && curdat.store_keys_in_input) return !fprintf(stderr, "Error invalid format %s: Using MGF_KEYS_INPUT and MGF_KEYS_UNICODE_B4_CRYPT in same format is NOT valid\n", Setup->szFORMAT_NAME); curdat.store_keys_normal_but_precompute_hash_to_output2 = !!(Setup->startFlags&MGF_KEYS_CRYPT_IN2); curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1 = !!(Setup->startFlags&MGF_KEYS_BASE16_IN1); if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1) curdat.store_keys_normal_but_precompute_hash_to_output2 = 1; #define IF_CDOFF32(F,L) if (!curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX) \ curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX = \ (!!((Setup->startFlags&MGF_KEYS_BASE16_IN1_Offset_TYPE)==MGF_KEYS_BASE16_IN1_Offset_ ## F))*L curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX = 0; IF_CDOFF32(MD5,32); IF_CDOFF32(MD4,32); IF_CDOFF32(SHA1,40); IF_CDOFF32(SHA224,56); IF_CDOFF32(SHA256,64); IF_CDOFF32(SHA384,96); IF_CDOFF32(SHA512,128); IF_CDOFF32(GOST,64); IF_CDOFF32(WHIRLPOOL,128); IF_CDOFF32(Tiger,48); IF_CDOFF32(RIPEMD128,32); IF_CDOFF32(RIPEMD160,40); IF_CDOFF32(RIPEMD256,64); IF_CDOFF32(RIPEMD320,80); IF_CDOFF32(MD2,32); IF_CDOFF32(PANAMA,64); IF_CDOFF32(HAVAL128_3,32); IF_CDOFF32(HAVAL160_3,40); IF_CDOFF32(HAVAL192_3,48); IF_CDOFF32(HAVAL224_3,56); IF_CDOFF32(HAVAL256_3,64); IF_CDOFF32(HAVAL128_4,32); IF_CDOFF32(HAVAL160_4,40); IF_CDOFF32(HAVAL192_4,48); IF_CDOFF32(HAVAL224_4,56); IF_CDOFF32(HAVAL256_4,64); IF_CDOFF32(HAVAL128_5,32); IF_CDOFF32(HAVAL160_5,40); IF_CDOFF32(HAVAL192_5,48); IF_CDOFF32(HAVAL224_5,56); IF_CDOFF32(HAVAL256_5,64); IF_CDOFF32(SKEIN224,56); IF_CDOFF32(SKEIN256,64); IF_CDOFF32(SKEIN384,96); IF_CDOFF32(SKEIN512,128); IF_CDOFF32(SHA3_224,56); IF_CDOFF32(SHA3_256,64); IF_CDOFF32(SHA3_384,96); IF_CDOFF32(SHA3_512,128); IF_CDOFF32(KECCAK_256,64); IF_CDOFF32(KECCAK_512,128); // LARGE_HASH_EDIT_POINT if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1_offsetX) { curdat.store_keys_normal_but_precompute_hash_to_output2 = 1; } curdat.store_keys_normal_but_precompute_hash_to_output2_base16_type = Setup->startFlags>>56; if ((Setup->startFlags) == 0) { // Ok, if we do not have some 'special' loader function, we MUST first clean some // input. If that is not done, there is NO WAY this is a valid format. This is // NOT an intelligent check, but more like the dummy lights on newer automobiles. // You know it will not work, but do not know 'why', nor should you care. if (Setup->pFuncs[0] != DynamicFunc__clean_input && Setup->pFuncs[0] != DynamicFunc__clean_input2 && Setup->pFuncs[0] != DynamicFunc__clean_input_kwik && Setup->pFuncs[0] != DynamicFunc__clean_input2_kwik && Setup->pFuncs[0] != DynamicFunc__clean_input_full) return !fprintf(stderr, "Error invalid format %s: The first command MUST be a clean of input 1 or input 2 OR a special key 2 input loader function\n", Setup->szFORMAT_NAME); } if ( (Setup->flags&MGF_SALTED2)==MGF_SALTED2 && (Setup->flags&MGF_SALT_AS_HEX) == MGF_SALT_AS_HEX) { // if the user wants salt_as_hex, then here can NOT be 2 salts. return !fprintf(stderr, "Error invalid format %s: If using MGF_SALT_AS_HEX flag, then you can NOT have a 2nd salt.\n", Setup->szFORMAT_NAME); } if (Setup->pFuncs && Setup->pFuncs[0]) { unsigned int z; for (z = 0; Setup->pFuncs[z]; ++z) ; z += 50; curdat.dynamic_FUNCTIONS = mem_alloc_tiny(z*sizeof(DYNAMIC_primitive_funcp), MEM_ALIGN_WORD); j = 0; #if !ARCH_LITTLE_ENDIAN // for bigendian, we do NOT store into keys, since we byte swap them. if (curdat.store_keys_in_input==1) { // this is only a minor speed hit, so simply fix by doing this. There is an // extra memcpy, that is it. curdat.store_keys_in_input = 0; curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__clean_input; curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__append_keys; } // NOTE NOTE NOTE, FIXME. These are 'hacks' which slow stuff way down. We should look at // building preloads that CAN do this. Store key input to input 1, but then do not use // input 1. Put a copy to input 2, then append, etc. In that way, we cut the number of // MD5's down by at least 1. // // But for now, just get it working. Get it working faster later. // NOTE, these are commented out now. I am not sure why they were there // I think the thought was for SIMD, BUT SIMD is not used on Sparc // I am leaving this code for now, BUT I think it should NOT be here. // I was getting failures on the 16 byte sph formats, for any // hash(hash($p).$s) such as md2(md2($p).$s) However, the modifications // where curdat.store_keys_in_input==1 is absolutely needed, or we have // get_key() failures all over the place. // note, with Setup->pFuncs[0]==DynamicFunc__set_input_len_32, we only will handle type 6 and 7 // for now we have this 'turned' off. It is fixed for type 6, 7 and 14. It is left on for the // john.ini stuff. Thus, if someone builds the intel version type 6, it will work (but slower). // if (curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1==1 && Setup->pFuncs[0]==DynamicFunc__set_input_len_32) { // curdat.store_keys_normal_but_precompute_hash_to_output2_base16_to_input1 = 0; // curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__clean_input; // curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__append_keys; // curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__crypt_md5; // curdat.dynamic_FUNCTIONS[j++] = DynamicFunc__clean_input; // Setup->pFuncs[0] = DynamicFunc__append_from_last_output_as_base16; // } #endif for (i=0; Setup->pFuncs[i]; ++i) { if (j > z-10) { unsigned int k; z += 100; curdat.dynamic_FUNCTIONS = mem_alloc_tiny(z*sizeof(DYNAMIC_primitive_funcp), MEM_ALIGN_WORD); for (k = 0; k <= j; ++k) curdat.dynamic_FUNCTIONS[k] = curdat.dynamic_FUNCTIONS[k]; } if (curdat.store_keys_in_input) { if (Setup->pFuncs[i] == DynamicFunc__append_keys) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_keys called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_keys2) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_keys2 called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__clean_input) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but clean_input called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_salt) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_salt called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_from_last_output2_to_input1_as_base16) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_from_last_output2_to_input1_as_base16 called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__overwrite_from_last_output2_to_input1_as_base16_no_size_fix) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but overwrite_from_last_output2_to_input1_as_base16_no_size_fix called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_from_last_output_as_base16) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_from_last_output_as_base16s called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__overwrite_from_last_output_as_base16_no_size_fix) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but overwrite_from_last_output_as_base16_no_size_fix called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_2nd_salt) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but append_2nd_salt called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__set_input_len_32) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but DynamicFunc__set_input_len_32 called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__set_input_len_64) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but DynamicFunc__set_input_len_32 called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__overwrite_salt_to_input1_no_size_fix) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but DynamicFunc__set_input_len_32 called and that is invalid\n", Setup->szFORMAT_NAME); if (Setup->pFuncs[i] == DynamicFunc__append_input_from_input2) return !fprintf(stderr, "Error invalid format %s: MGF_KEYS_INPUT used, but DynamicFunc__set_input_len_32 called and that is invalid\n", Setup->szFORMAT_NAME); } // Ok if copy constants are set, make SURE we have that many constants. if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST1 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST1) && curdat.nConsts == 0) return !fprintf(stderr, "Error invalid format %s: Append Constant function called, but NO constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST2 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST2) && curdat.nConsts < 2) return !fprintf(stderr, "Error invalid format %s: Append Constant #2 function called, but NO constants, or less than 2 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST3 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST3) && curdat.nConsts < 3) return !fprintf(stderr, "Error invalid format %s: Append Constant #3 function called, but NO constants, or less than 3 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST4 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST4) && curdat.nConsts < 4) return !fprintf(stderr, "Error invalid format %s: Append Constant #4 function called, but NO constants, or less than 4 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST5 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST5) && curdat.nConsts < 5) return !fprintf(stderr, "Error invalid format %s: Append Constant #5 function called, but NO constants, or less than 5 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST6 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST6) && curdat.nConsts < 6) return !fprintf(stderr, "Error invalid format %s: Append Constant #6 function called, but NO constants, or less than 6 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST7 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST7) && curdat.nConsts < 7) return !fprintf(stderr, "Error invalid format %s: Append Constant #7 function called, but NO constants, or less than 7 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_input1_from_CONST8 || Setup->pFuncs[i] == DynamicFunc__append_input2_from_CONST8) && curdat.nConsts < 8) return !fprintf(stderr, "Error invalid format %s: Append Constant #8 function called, but NO constants, or less than 8 constants in the format\n", Setup->szFORMAT_NAME); if ( (Setup->pFuncs[i] == DynamicFunc__append_2nd_salt || Setup->pFuncs[i] == DynamicFunc__append_2nd_salt2) && curdat.b2Salts == 0) return !fprintf(stderr, "Error invalid format %s: A call to one of the 'salt-2' functions, but this format does not have MFG_SALT2 flag set\n", Setup->szFORMAT_NAME); // Ok, if we have made it here, the function is 'currently' still valid. Load this pointer into our array of pointers. pFuncs = ConvertFuncs(Setup->pFuncs[i], &cnt2); #define IS_FUNC_NAME(H,N) if (is##H##Func(pFuncs[x])){ if (!strcmp(pFmt->params.algorithm_name, ALGORITHM_NAME)) pFmt->params.algorithm_name = ALGORITHM_NAME_##N; \ else if (!strcmp(pFmt->params.algorithm_name, ALGORITHM_NAME_X86)) pFmt->params.algorithm_name = ALGORITHM_NAME_X86_##N; } for (x = 0; x < cnt2; ++x) { curdat.dynamic_FUNCTIONS[j++] = pFuncs[x]; if (pFuncs[x] == DynamicFunc__setmode_unicode || pFuncs[x] == DynamicFunc__setmode_unicodeBE) pFmt->params.flags |= FMT_UNICODE; IS_FUNC_NAME(SHA1,S) if (isSHA2_256Func(pFuncs[x])) { #ifdef SIMD_COEF_32 if (curdat.using_flat_buffers_sse2_ok) pFmt->params.algorithm_name = ALGORITHM_NAME_S2_256; else #endif pFmt->params.algorithm_name = ALGORITHM_NAME_X86_S2_256; } if (isSHA2_512Func(pFuncs[x])) { #ifdef SIMD_COEF_64 if (curdat.using_flat_buffers_sse2_ok) pFmt->params.algorithm_name = ALGORITHM_NAME_S2_512; else #endif pFmt->params.algorithm_name = ALGORITHM_NAME_X86_S2_512; } IS_FUNC_NAME(MD4,4) IS_FUNC_NAME(WHIRL,WP2) IS_FUNC_NAME(GOST,GST2) IS_FUNC_NAME(Tiger,TGR) IS_FUNC_NAME(RIPEMD,RIPEMD) IS_FUNC_NAME(HAVAL,HAVAL) IS_FUNC_NAME(MD2,MD2) IS_FUNC_NAME(PANAMA,PANAMA) IS_FUNC_NAME(SKEIN,SKEIN) // Note, until we add SIMD keccak, one algoithm is all we 'need' IS_FUNC_NAME(KECCAK,KECCAK) // IS_FUNC_NAME(KECCAK,SHA3_256) // IS_FUNC_NAME(KECCAK,SHA3_384) // IS_FUNC_NAME(KECCAK,SHA3_512) // IS_FUNC_NAME(KECCAK,KECCAK_256) // IS_FUNC_NAME(KECCAK,KECCAK_512) // LARGE_HASH_EDIT_POINT (MUST match the just added a new IsXXXFunc() type function) } if (isLargeHashFinalFunc(curdat.dynamic_FUNCTIONS[j-1])) { if (Setup->pFuncs[i+1]) return !fprintf(stderr, "Error invalid format %s: DynamicFunc__LARGE_HASH_crypt_inputX_to_output1_FINAL, can ONLY be used as the last function in a script\n", Setup->szFORMAT_NAME); } } curdat.dynamic_FUNCTIONS[j] = NULL; } if (!Setup->pPreloads || Setup->pPreloads[0].ciphertext == NULL) { return !fprintf(stderr, "Error invalid format %s: Error, no validation hash(s) for this format\n", Setup->szFORMAT_NAME); } cnt = 0; #ifdef _OPENMP dyna_setupOMP(Setup, pFmt); #endif { struct fmt_tests *pfx = mem_alloc_tiny(ARRAY_COUNT(dynamic_tests) * sizeof (struct fmt_tests), MEM_ALIGN_WORD); memset(pfx, 0, ARRAY_COUNT(dynamic_tests) * sizeof (struct fmt_tests)); for (i = 0; cnt < ARRAY_COUNT(dynamic_tests) -1; ++i) { if (Setup->pPreloads[i].ciphertext == NULL) { i = 0; } if (Setup->pPreloads[i].ciphertext[0] == 'A' && Setup->pPreloads[i].ciphertext[1] == '=') { if (options.target_enc != ASCII && options.target_enc != ISO_8859_1) continue; pfx[cnt].ciphertext = str_alloc_copy(&Setup->pPreloads[i].ciphertext[2]); } else if (Setup->pPreloads[i].ciphertext[0] == 'U' && Setup->pPreloads[i].ciphertext[1] == '=') { if (options.target_enc != UTF_8) continue; pfx[cnt].ciphertext = str_alloc_copy(&Setup->pPreloads[i].ciphertext[2]); } else pfx[cnt].ciphertext = str_alloc_copy(Setup->pPreloads[i].ciphertext); pfx[cnt].plaintext = str_alloc_copy(Setup->pPreloads[i].plaintext); pfx[cnt].fields[0] = Setup->pPreloads[i].fields[0] ? str_alloc_copy(Setup->pPreloads[i].fields[0]) : ""; pfx[cnt].fields[1] = pfx[cnt].ciphertext; for (j = 2; j < 10; ++j) pfx[cnt].fields[j] = Setup->pPreloads[i].fields[j] ? str_alloc_copy(Setup->pPreloads[i].fields[j]) : ""; ++cnt; } pfx[cnt].ciphertext = NULL; pfx[cnt].plaintext = NULL; pFmt->params.tests = pfx; } if (curdat.dynamic_base16_upcase) dynamic_itoa16 = itoa16u; else dynamic_itoa16 = itoa16; { char s[512], *cp; cp = Setup->szFORMAT_NAME; cp = strchr(Setup->szFORMAT_NAME, ' '); ++cp; sprintf(s, "%s %s", cp, pFmt->params.algorithm_name); pFmt->params.algorithm_name = str_alloc_copy(s); } if ((Setup->flags & MGF_SALTED) && !Setup->SaltLen) return !fprintf(stderr, "Error invalid format %s\n\tIt is required to add SaltLen= to the script, for this format\n", Setup->szFORMAT_NAME); return 1; } static int LoadOneFormat(int idx, struct fmt_main *pFmt) { extern struct options_main options; char label[16] = { 0 }, label_id[16] = { 0 }, *cp = NULL; memcpy(pFmt, &fmt_Dynamic, sizeof(struct fmt_main)); // TODO: // NOTE, this was commented out, because the late binding @dynamic=expr@ // hashes were killing out possibly pre-setup input buffers. NOTE, that // things worked fine after this, all self tests do pass, and I am 99% // sure that all of this 'required' cleaning happens in init(). but I am // putting this comment in here, so that if at a later time, there are // problems and are tracked down to this, we will know why. // dynamic_RESET(pFmt); // Ok we need to list this as a dynamic format (even for the 'thin' formats) pFmt->params.flags |= FMT_DYNAMIC; if (idx < 1000) { if (dynamic_RESERVED_PRELOAD_SETUP(idx, pFmt) != 1) return 0; } else { if (dynamic_LOAD_PARSER_FUNCTIONS(idx, pFmt) != 1) return 0; } /* we 'have' to take the sig from the test array. If we do not have */ /* our preload array 'solid', then the idx will not be the proper */ /* number. So we simply grab the label from the test cyphertext string */ strncpy(label, pFmt->params.tests[0].ciphertext, 15); cp = strchr(&label[1], '$'); if (NULL != cp) cp[1] = 0; strcpy(label_id, &label[1]); cp = strchr(label_id, '$'); if (NULL != cp) *cp = 0; // if (!options.format || strncmp(options.format, "dynamic_", 8)) // pFmt->params.label = str_alloc_copy("dynamic"); // else pFmt->params.label = str_alloc_copy(label_id); strcpy(curdat.dynamic_WHICH_TYPE_SIG, label); curdat.dynamic_HASH_OFFSET = strlen(label); if (curdat.dynamic_base64_inout == 1 || curdat.dynamic_base64_inout == 3) { // we have to compute 'proper' offset const char *cp = pFmt->params.tests[0].ciphertext; size_t len = base64_valid_length(&cp[curdat.dynamic_HASH_OFFSET], curdat.dynamic_base64_inout == 1 ? e_b64_crypt : e_b64_mime, flg_Base64_MIME_TRAIL_EQ_CNT, 0); curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + len + 1; } else if (curdat.dynamic_base64_inout == 2) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 16 + 1; else if (curdat.dynamic_40_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 40 + 1; else if (curdat.dynamic_48_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 48 + 1; else if (curdat.dynamic_64_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 64 + 1; else if (curdat.dynamic_56_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 56 + 1; else if (curdat.dynamic_80_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 80 + 1; else if (curdat.dynamic_96_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 96 + 1; else if (curdat.dynamic_128_byte_input) curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 128 + 1; else curdat.dynamic_SALT_OFFSET = curdat.dynamic_HASH_OFFSET + 32 + 1; pFmt->private.data = mem_alloc_tiny(sizeof(private_subformat_data), MEM_ALIGN_WORD); memcpy(pFmt->private.data, &curdat, sizeof(private_subformat_data)); if (strncmp(curdat.dynamic_WHICH_TYPE_SIG, pFmt->params.tests[0].ciphertext, strlen(curdat.dynamic_WHICH_TYPE_SIG))) { fprintf(stderr, "ERROR, when loading dynamic formats, the wrong curdat item was linked to this type:\nTYPE_SIG=%s\nTest_Dat=%s\n", curdat.dynamic_WHICH_TYPE_SIG, pFmt->params.tests[0].ciphertext); return 0; } return 1; } struct fmt_main *dynamic_Register_local_format(int *type) { int num=nLocalFmts++; private_subformat_data keep; if (!pLocalFmts) pLocalFmts = mem_calloc_tiny(1000*sizeof(struct fmt_main), 16); /* since these are loaded LATE in the process, init() has been called * and we HAVE to preserve the already loaded setup. This will happen * if we run a crack, but do not specify a specific dyna format */ memcpy(&keep, &curdat, sizeof(private_subformat_data)); LoadOneFormat(num+6000, &(pLocalFmts[num])); memcpy(&curdat, &keep, sizeof(private_subformat_data)); dynamic_use_sse = curdat.dynamic_use_sse; force_md5_ctx = curdat.force_md5_ctx; *type = num+6000; return &(pLocalFmts[num]); } int dynamic_Register_formats(struct fmt_main **ptr) { int count, i, idx, single=-1, wildcard = 0, pop[5000]; extern struct options_main options; if (options.format && strstr(options.format, "*")) wildcard = 1; Dynamic_Load_itoa16_w2(); if (!wildcard && options.format && !strncmp(options.format, "dynamic_", 8)) sscanf(options.format, "dynamic_%d", &single); if (options.format && options.subformat && !strcmp(options.format, "dynamic") && !strncmp(options.subformat, "dynamic_", 8)) sscanf(options.subformat, "dynamic_%d", &single); if (options.dynamic_bare_hashes_always_valid == 'Y') dynamic_allow_rawhash_fixup = 1; else if (options.dynamic_bare_hashes_always_valid != 'N' && cfg_get_bool(SECTION_OPTIONS, NULL, "DynamicAlwaysUseBareHashes", 1)) dynamic_allow_rawhash_fixup = 1; if (single != -1) { // user wanted only a 'specific' format. Simply load that one. dynamic_allow_rawhash_fixup = 1; if (dynamic_IS_VALID(single, 1) == 0) return 0; pFmts = mem_alloc_tiny(sizeof(pFmts[0]), MEM_ALIGN_WORD); if (!LoadOneFormat(single, pFmts)) return 0; *ptr = pFmts; return (nFmts = 1); } for (count = i = 0; i < 5000; ++i) { if ((pop[i] = (dynamic_IS_VALID(i, 0) == 1))) ++count; } // Ok, now we know how many formats we have. Load them pFmts = mem_alloc_tiny(sizeof(pFmts[0])*count, MEM_ALIGN_WORD); for (idx = i = 0; i < 5000; ++i) { if (pop[i]) { if (LoadOneFormat(i, &pFmts[idx]) == 0) --count; else ++idx; } } *ptr = pFmts; return (nFmts = count); } /* * finds the 'proper' sub format from the allocated formats, IFF that format 'exists' */ static struct fmt_main *dynamic_Get_fmt_main(int which) { char label[40]; int i; sprintf(label, "$dynamic_%d$", which); for (i = 0; i < nFmts; ++i) { private_subformat_data *pPriv = pFmts[i].private.data; if (!strcmp(pPriv->dynamic_WHICH_TYPE_SIG, label)) return &pFmts[i]; } for (i = 0; i < nLocalFmts; ++i) { private_subformat_data *pPriv = pLocalFmts[i].private.data; if (!strcmp(pPriv->dynamic_WHICH_TYPE_SIG, label)) return &pLocalFmts[i]; } return NULL; } /* * This function will 'forget' which md5-gen subtype we are working with. It will allow * a different type to be used. Very useful for things like -test (benchmarking). */ static void dynamic_RESET(struct fmt_main *fmt) { memset(&curdat, 0, sizeof(curdat)); m_count = 0; keys_dirty = 0; cursalt=cursalt2=username=0; saltlen=saltlen2=usernamelen=0; // make 'sure' we startout with blank inputs. m_count = 0; #ifdef SIMD_COEF_32 if (input_buf) { #else if (input_buf_X86) { #endif __nonMP_DynamicFunc__clean_input_full(); __nonMP_DynamicFunc__clean_input2_full(); } } /* * This will LINK our functions into some other fmt_main struction. That way * that struction can use our code. The other *_fmt.c file will need to * 'override' the valid, the binary and the salt functions, and make changes * to the hash, BEFORE calling into the dynamic valid/binary/salt functions. * Other than those functions (and calling into this linkage function at init time) * that is about all that needs to be in that 'other' *_fmt.c file, as long as the * format is part of the md5-generic 'class' of functions. */ struct fmt_main *dynamic_THIN_FORMAT_LINK(struct fmt_main *pFmt, char *ciphertext, char *orig_sig, int bInitAlso) { int i, valid, nFmtNum; struct fmt_main *pFmtLocal; static char subformat[17], *cp; dynamic_allow_rawhash_fixup = 0; strncpy(subformat, ciphertext, 16); subformat[16] = 0; cp = strchr(&subformat[9], '$'); if (cp) cp[1] = 0; nFmtNum = -1; sscanf(subformat, "$dynamic_%d", &nFmtNum); if (nFmtNum == -1) error_msg("Error, Invalid signature line trying to link to dynamic format.\nOriginal format=%s\nSignature line=%s\n", orig_sig, ciphertext); pFmtLocal = dynamic_Get_fmt_main(nFmtNum); if (pFmtLocal == NULL) error_msg("Error, Invalid signature line trying to link to dynamic format.\nOriginal format=%s\nSignature line=%s\n", orig_sig, ciphertext); valid = pFmtLocal->methods.valid(ciphertext, pFmtLocal); if (!valid) error_msg("Error, trying to link to %s using ciphertext=%s FAILED\n", subformat, ciphertext); pFmt->params.algorithm_name = pFmtLocal->params.algorithm_name; if (pFmt->params.plaintext_length == 0 || pFmt->params.plaintext_length > pFmtLocal->params.plaintext_length) { pFmt->params.plaintext_length = pFmtLocal->params.plaintext_length; pFmt->params.plaintext_min_length = pFmtLocal->params.plaintext_min_length; } pFmt->params.max_keys_per_crypt = pFmtLocal->params.max_keys_per_crypt; pFmt->params.min_keys_per_crypt = pFmtLocal->params.max_keys_per_crypt; if (pFmt->params.min_keys_per_crypt > 64) pFmt->params.min_keys_per_crypt = 64; pFmt->params.flags = pFmtLocal->params.flags; if (pFmtLocal->params.salt_size) pFmt->params.salt_size = sizeof(void*); else pFmt->params.salt_size = 0; pFmt->methods.cmp_all = pFmtLocal->methods.cmp_all; pFmt->methods.cmp_one = pFmtLocal->methods.cmp_one; pFmt->methods.cmp_exact = pFmtLocal->methods.cmp_exact; for (i = 0; i < FMT_TUNABLE_COSTS; ++i) { pFmt->methods.tunable_cost_value[i] = pFmtLocal->methods.tunable_cost_value[i]; pFmt->params.tunable_cost_name[i] = pFmtLocal->params.tunable_cost_name[i]; } pFmt->methods.source = pFmtLocal->methods.source; pFmt->methods.set_salt = pFmtLocal->methods.set_salt; pFmt->methods.salt = pFmtLocal->methods.salt; pFmt->methods.done = pFmtLocal->methods.done; pFmt->methods.salt_hash = pFmtLocal->methods.salt_hash; pFmt->methods.split = pFmtLocal->methods.split; pFmt->methods.set_key = pFmtLocal->methods.set_key; pFmt->methods.get_key = pFmtLocal->methods.get_key; pFmt->methods.clear_keys = pFmtLocal->methods.clear_keys; pFmt->methods.crypt_all = pFmtLocal->methods.crypt_all; pFmt->methods.prepare = pFmtLocal->methods.prepare; pFmt->methods.salt_compare = pFmtLocal->methods.salt_compare; for (i = 0; i < PASSWORD_HASH_SIZES; ++i) { pFmt->methods.binary_hash[i] = pFmtLocal->methods.binary_hash[i]; pFmt->methods.get_hash[i] = pFmtLocal->methods.get_hash[i]; } if (bInitAlso) { //fprintf(stderr, "dynamic_THIN_FORMAT_LINK() calling init(%s)\n", subformat); init(pFmtLocal); } pFmt->private.data = mem_alloc_tiny(sizeof(private_subformat_data), MEM_ALIGN_WORD); memcpy(pFmt->private.data, pFmtLocal->private.data, sizeof(private_subformat_data)); return pFmtLocal; } // We ONLY deal with hex hashes at this time. Is we later have to deal with // base-64, this will become harder. Before this function we had bugs where // many things were loaded as 'being' valid, even if not. static int looks_like_raw_hash(char *ciphertext, private_subformat_data *pPriv) { int i, cipherTextLen = CIPHERTEXT_LENGTH; if (pPriv->dynamic_40_byte_input) { cipherTextLen = 40; } else if (pPriv->dynamic_48_byte_input) { cipherTextLen = 48; } else if (pPriv->dynamic_64_byte_input) { cipherTextLen = 64; } else if (pPriv->dynamic_56_byte_input) { cipherTextLen = 56; } else if (pPriv->dynamic_80_byte_input) { cipherTextLen = 80; } else if (pPriv->dynamic_96_byte_input) { cipherTextLen = 96; } else if (pPriv->dynamic_128_byte_input) { cipherTextLen = 128; } for (i = 0; i < cipherTextLen; i++) { if (atoi16[ARCH_INDEX(ciphertext[i])] == 0x7f) return 0; } if ((pPriv->pSetup->flags&MGF_SALTED) == 0) { if (!ciphertext[cipherTextLen]) return 1; return 0; } return ciphertext[cipherTextLen] == '$'; } static char *FixupIfNeeded(char *ciphertext, private_subformat_data *pPriv) { if (!ciphertext || *ciphertext == 0 || *ciphertext == '*') return ciphertext; if (dynamic_allow_rawhash_fixup && strncmp(ciphertext, "$dynamic_", 9) && looks_like_raw_hash(ciphertext, pPriv)) { static char __ciphertext[512+24]; if (pPriv->pSetup->flags & MGF_SALTED) { if (!strchr(ciphertext, '$')) return ciphertext; } if ( (pPriv->pSetup->flags & MGF_SALTED2) == MGF_SALTED2) { if (!strstr(ciphertext, "$$2")) return ciphertext; } if ( (pPriv->pSetup->flags & MGF_USERNAME) == MGF_USERNAME) { if (!strstr(ciphertext, "$$U")) return ciphertext; } if (pPriv->FldMask) { int i; for (i = 0; i < 10; ++i) { if ((pPriv->FldMask & (MGF_FLDx_BIT<<i)) == (MGF_FLDx_BIT<<i)) { char Fld[8]; sprintf(Fld, "$$F%d", i); if (!strstr(&ciphertext[pPriv->dynamic_SALT_OFFSET-1], Fld)) return ciphertext; } } } strcpy(__ciphertext, pPriv->dynamic_WHICH_TYPE_SIG); strnzcpy(&__ciphertext[strlen(__ciphertext)], ciphertext, 512); return __ciphertext; } return ciphertext; } int text_in_dynamic_format_already(struct fmt_main *pFmt, char *ciphertext) { private_subformat_data *pPriv; if (!pFmt) return 0; /* NOTE, it 'is' possible to get called here, without the private stuff being setup properly (in valid, etc). So, we simply grab the static private stuff each time */ pPriv = pFmt->private.data; if (!ciphertext || !pPriv) return 0; return !strncmp(ciphertext, pPriv->dynamic_WHICH_TYPE_SIG, strlen(pPriv->dynamic_WHICH_TYPE_SIG)); } // if caseType == 1, return cp // if caseType == 2, return upcase(cp) // if caseType == 3, return locase(cp) // if caseType == 4, return upcaseFirstChar(locase(cp)) static char *HandleCase(char *cp, int caseType) { static UTF8 dest[256]; switch(caseType) { case 1: return cp; case 2: enc_uc(dest, sizeof(dest), (unsigned char*)cp, strlen(cp)); if (!strcmp((char*)dest, cp)) return cp; break; case 3: case 4: enc_lc(dest, sizeof(dest), (unsigned char*)cp, strlen(cp)); if (caseType == 4) dest[0] = low2up_ansi(dest[0]); if (!strcmp((char*)dest, cp)) return cp; break; default: return cp; } return (char*)dest; } int dynamic_real_salt_length(struct fmt_main *pFmt) { if (pFmt->params.flags & FMT_DYNAMIC) { private_subformat_data *pPriv = pFmt->private.data; if (pPriv == NULL || pPriv->pSetup == NULL) return -1; // not a dynamic format, or called before we have loaded them!! return abs(pPriv->pSetup->SaltLen); } // NOT a dynamic format return -1; } #else #warning Notice: Dynamic format disabled from build. #endif /* DYNAMIC_DISABLED */
GB_binop__atan2_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__atan2_fp32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__atan2_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__atan2_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__atan2_fp32) // C=scalar+B GB (_bind1st__atan2_fp32) // C=scalar+B' GB (_bind1st_tran__atan2_fp32) // C=A+scalar GB (_bind2nd__atan2_fp32) // C=A'+scalar GB (_bind2nd_tran__atan2_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = atan2f (aij, bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = atan2f (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ATAN2 || GxB_NO_FP32 || GxB_NO_ATAN2_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__atan2_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__atan2_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__atan2_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__atan2_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__atan2_fp32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__atan2_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__atan2_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__atan2_fp32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__atan2_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = atan2f (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__atan2_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = atan2f (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = atan2f (x, aij) ; \ } GrB_Info GB (_bind1st_tran__atan2_fp32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = atan2f (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__atan2_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GeneralMatrixMatrix.h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_GENERAL_MATRIX_MATRIX_H #define EIGEN_GENERAL_MATRIX_MATRIX_H namespace Eigen { namespace internal { template<typename _LhsScalar, typename _RhsScalar> class level3_blocking; /* Specialization for a row-major destination matrix => simple transposition of the product */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int ResInnerStride> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,RowMajor,ResInnerStride> { typedef gebp_traits<RhsScalar,LhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static EIGEN_STRONG_INLINE void run( Index rows, Index cols, Index depth, const LhsScalar* lhs, Index lhsStride, const RhsScalar* rhs, Index rhsStride, ResScalar* res, Index resIncr, Index resStride, ResScalar alpha, level3_blocking<RhsScalar,LhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { // transpose the product such that the result is column major general_matrix_matrix_product<Index, RhsScalar, RhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateRhs, LhsScalar, LhsStorageOrder==RowMajor ? ColMajor : RowMajor, ConjugateLhs, ColMajor,ResInnerStride> ::run(cols,rows,depth,rhs,rhsStride,lhs,lhsStride,res,resIncr,resStride,alpha,blocking,info); } }; /* Specialization for a col-major destination matrix * => Blocking algorithm following Goto's paper */ template< typename Index, typename LhsScalar, int LhsStorageOrder, bool ConjugateLhs, typename RhsScalar, int RhsStorageOrder, bool ConjugateRhs, int ResInnerStride> struct general_matrix_matrix_product<Index,LhsScalar,LhsStorageOrder,ConjugateLhs,RhsScalar,RhsStorageOrder,ConjugateRhs,ColMajor,ResInnerStride> { typedef gebp_traits<LhsScalar,RhsScalar> Traits; typedef typename ScalarBinaryOpTraits<LhsScalar, RhsScalar>::ReturnType ResScalar; static void run(Index rows, Index cols, Index depth, const LhsScalar* _lhs, Index lhsStride, const RhsScalar* _rhs, Index rhsStride, ResScalar* _res, Index resIncr, Index resStride, ResScalar alpha, level3_blocking<LhsScalar,RhsScalar>& blocking, GemmParallelInfo<Index>* info = 0) { typedef const_blas_data_mapper<LhsScalar, Index, LhsStorageOrder> LhsMapper; typedef const_blas_data_mapper<RhsScalar, Index, RhsStorageOrder> RhsMapper; typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor,Unaligned,ResInnerStride> ResMapper; LhsMapper lhs(_lhs, lhsStride); RhsMapper rhs(_rhs, rhsStride); ResMapper res(_res, resStride, resIncr); Index kc = blocking.kc(); // cache block size along the K direction Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction Index nc = (std::min)(cols,blocking.nc()); // cache block size along the N direction gemm_pack_lhs<LhsScalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, typename Traits::LhsPacket4Packing, LhsStorageOrder> pack_lhs; gemm_pack_rhs<RhsScalar, Index, RhsMapper, Traits::nr, RhsStorageOrder> pack_rhs; gebp_kernel<LhsScalar, RhsScalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp; #ifdef EIGEN_HAS_OPENMP if(info) { // this is the parallel version! int tid = omp_get_thread_num(); int threads = omp_get_num_threads(); LhsScalar* blockA = blocking.blockA(); eigen_internal_assert(blockA!=0); std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, 0); // For each horizontal panel of the rhs, and corresponding vertical panel of the lhs... for(Index k=0; k<depth; k+=kc) { const Index actual_kc = (std::min)(k+kc,depth)-k; // => rows of B', and cols of the A' // In order to reduce the chance that a thread has to wait for the other, // let's start by packing B'. pack_rhs(blockB, rhs.getSubMapper(k,0), actual_kc, nc); // Pack A_k to A' in a parallel fashion: // each thread packs the sub block A_k,i to A'_i where i is the thread id. // However, before copying to A'_i, we have to make sure that no other thread is still using it, // i.e., we test that info[tid].users equals 0. // Then, we set info[tid].users to the number of threads to mark that all other threads are going to use it. while(info[tid].users!=0) {} info[tid].users = threads; pack_lhs(blockA+info[tid].lhs_start*actual_kc, lhs.getSubMapper(info[tid].lhs_start,k), actual_kc, info[tid].lhs_length); // Notify the other threads that the part A'_i is ready to go. info[tid].sync = k; // Computes C_i += A' * B' per A'_i for(int shift=0; shift<threads; ++shift) { int i = (tid+shift)%threads; // At this point we have to make sure that A'_i has been updated by the thread i, // we use testAndSetOrdered to mimic a volatile access. // However, no need to wait for the B' part which has been updated by the current thread! if (shift>0) { while(info[i].sync!=k) { } } gebp(res.getSubMapper(info[i].lhs_start, 0), blockA+info[i].lhs_start*actual_kc, blockB, info[i].lhs_length, actual_kc, nc, alpha); } // Then keep going as usual with the remaining B' for(Index j=nc; j<cols; j+=nc) { const Index actual_nc = (std::min)(j+nc,cols)-j; // pack B_k,j to B' pack_rhs(blockB, rhs.getSubMapper(k,j), actual_kc, actual_nc); // C_j += A' * B' gebp(res.getSubMapper(0, j), blockA, blockB, rows, actual_kc, actual_nc, alpha); } // Release all the sub blocks A'_i of A' for the current thread, // i.e., we simply decrement the number of users by 1 for(Index i=0; i<threads; ++i) #if !EIGEN_HAS_CXX11_ATOMIC #pragma omp atomic #endif info[i].users -= 1; } } else #endif // EIGEN_HAS_OPENMP { EIGEN_UNUSED_VARIABLE(info); // this is the sequential version! std::size_t sizeA = kc*mc; std::size_t sizeB = kc*nc; ei_declare_aligned_stack_constructed_variable(LhsScalar, blockA, sizeA, blocking.blockA()); ei_declare_aligned_stack_constructed_variable(RhsScalar, blockB, sizeB, blocking.blockB()); const bool pack_rhs_once = mc!=rows && kc==depth && nc==cols; // For each horizontal panel of the rhs, and corresponding panel of the lhs... for(Index i2=0; i2<rows; i2+=mc) { const Index actual_mc = (std::min)(i2+mc,rows)-i2; for(Index k2=0; k2<depth; k2+=kc) { const Index actual_kc = (std::min)(k2+kc,depth)-k2; // OK, here we have selected one horizontal panel of rhs and one vertical panel of lhs. // => Pack lhs's panel into a sequential chunk of memory (L2/L3 caching) // Note that this panel will be read as many times as the number of blocks in the rhs's // horizontal panel which is, in practice, a very low number. pack_lhs(blockA, lhs.getSubMapper(i2,k2), actual_kc, actual_mc); // For each kc x nc block of the rhs's horizontal panel... for(Index j2=0; j2<cols; j2+=nc) { const Index actual_nc = (std::min)(j2+nc,cols)-j2; // We pack the rhs's block into a sequential chunk of memory (L2 caching) // Note that this block will be read a very high number of times, which is equal to the number of // micro horizontal panel of the large rhs's panel (e.g., rows/12 times). if((!pack_rhs_once) || i2==0) pack_rhs(blockB, rhs.getSubMapper(k2,j2), actual_kc, actual_nc); // Everything is packed, we can now call the panel * block kernel: gebp(res.getSubMapper(i2, j2), blockA, blockB, actual_mc, actual_kc, actual_nc, alpha); } } } } } }; /********************************************************************************* * Specialization of generic_product_impl for "large" GEMM, i.e., * implementation of the high level wrapper to general_matrix_matrix_product **********************************************************************************/ template<typename Scalar, typename Index, typename Gemm, typename Lhs, typename Rhs, typename Dest, typename BlockingType> struct gemm_functor { gemm_functor(const Lhs& lhs, const Rhs& rhs, Dest& dest, const Scalar& actualAlpha, BlockingType& blocking) : m_lhs(lhs), m_rhs(rhs), m_dest(dest), m_actualAlpha(actualAlpha), m_blocking(blocking) {} void initParallelSession(Index num_threads) const { m_blocking.initParallel(m_lhs.rows(), m_rhs.cols(), m_lhs.cols(), num_threads); m_blocking.allocateA(); } void operator() (Index row, Index rows, Index col=0, Index cols=-1, GemmParallelInfo<Index>* info=0) const { if(cols==-1) cols = m_rhs.cols(); Gemm::run(rows, cols, m_lhs.cols(), &m_lhs.coeffRef(row,0), m_lhs.outerStride(), &m_rhs.coeffRef(0,col), m_rhs.outerStride(), (Scalar*)&(m_dest.coeffRef(row,col)), m_dest.innerStride(), m_dest.outerStride(), m_actualAlpha, m_blocking, info); } typedef typename Gemm::Traits Traits; protected: const Lhs& m_lhs; const Rhs& m_rhs; Dest& m_dest; Scalar m_actualAlpha; BlockingType& m_blocking; }; template<int StorageOrder, typename LhsScalar, typename RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor=1, bool FiniteAtCompileTime = MaxRows!=Dynamic && MaxCols!=Dynamic && MaxDepth != Dynamic> class gemm_blocking_space; template<typename _LhsScalar, typename _RhsScalar> class level3_blocking { typedef _LhsScalar LhsScalar; typedef _RhsScalar RhsScalar; protected: LhsScalar* m_blockA; RhsScalar* m_blockB; Index m_mc; Index m_nc; Index m_kc; public: level3_blocking() : m_blockA(0), m_blockB(0), m_mc(0), m_nc(0), m_kc(0) {} inline Index mc() const { return m_mc; } inline Index nc() const { return m_nc; } inline Index kc() const { return m_kc; } inline LhsScalar* blockA() { return m_blockA; } inline RhsScalar* blockB() { return m_blockB; } }; template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, true /* == FiniteAtCompileTime */> : public level3_blocking< typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type, typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type> { enum { Transpose = StorageOrder==RowMajor, ActualRows = Transpose ? MaxCols : MaxRows, ActualCols = Transpose ? MaxRows : MaxCols }; typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar; typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; enum { SizeA = ActualRows * MaxDepth, SizeB = ActualCols * MaxDepth }; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES EIGEN_ALIGN_MAX LhsScalar m_staticA[SizeA]; EIGEN_ALIGN_MAX RhsScalar m_staticB[SizeB]; #else EIGEN_ALIGN_MAX char m_staticA[SizeA * sizeof(LhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; EIGEN_ALIGN_MAX char m_staticB[SizeB * sizeof(RhsScalar) + EIGEN_DEFAULT_ALIGN_BYTES-1]; #endif public: gemm_blocking_space(Index /*rows*/, Index /*cols*/, Index /*depth*/, Index /*num_threads*/, bool /*full_rows = false*/) { this->m_mc = ActualRows; this->m_nc = ActualCols; this->m_kc = MaxDepth; #if EIGEN_MAX_STATIC_ALIGN_BYTES >= EIGEN_DEFAULT_ALIGN_BYTES this->m_blockA = m_staticA; this->m_blockB = m_staticB; #else this->m_blockA = reinterpret_cast<LhsScalar*>((internal::UIntPtr(m_staticA) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); this->m_blockB = reinterpret_cast<RhsScalar*>((internal::UIntPtr(m_staticB) + (EIGEN_DEFAULT_ALIGN_BYTES-1)) & ~std::size_t(EIGEN_DEFAULT_ALIGN_BYTES-1)); #endif } void initParallel(Index, Index, Index, Index) {} inline void allocateA() {} inline void allocateB() {} inline void allocateAll() {} }; template<int StorageOrder, typename _LhsScalar, typename _RhsScalar, int MaxRows, int MaxCols, int MaxDepth, int KcFactor> class gemm_blocking_space<StorageOrder,_LhsScalar,_RhsScalar,MaxRows, MaxCols, MaxDepth, KcFactor, false> : public level3_blocking< typename conditional<StorageOrder==RowMajor,_RhsScalar,_LhsScalar>::type, typename conditional<StorageOrder==RowMajor,_LhsScalar,_RhsScalar>::type> { enum { Transpose = StorageOrder==RowMajor }; typedef typename conditional<Transpose,_RhsScalar,_LhsScalar>::type LhsScalar; typedef typename conditional<Transpose,_LhsScalar,_RhsScalar>::type RhsScalar; typedef gebp_traits<LhsScalar,RhsScalar> Traits; Index m_sizeA; Index m_sizeB; public: gemm_blocking_space(Index rows, Index cols, Index depth, Index num_threads, bool l3_blocking) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; if(l3_blocking) { computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, this->m_nc, num_threads); } else // no l3 blocking { Index n = this->m_nc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, this->m_mc, n, num_threads); } m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void initParallel(Index rows, Index cols, Index depth, Index num_threads) { this->m_mc = Transpose ? cols : rows; this->m_nc = Transpose ? rows : cols; this->m_kc = depth; eigen_internal_assert(this->m_blockA==0 && this->m_blockB==0); Index m = this->m_mc; computeProductBlockingSizes<LhsScalar,RhsScalar,KcFactor>(this->m_kc, m, this->m_nc, num_threads); m_sizeA = this->m_mc * this->m_kc; m_sizeB = this->m_kc * this->m_nc; } void allocateA() { if(this->m_blockA==0) this->m_blockA = aligned_new<LhsScalar>(m_sizeA); } void allocateB() { if(this->m_blockB==0) this->m_blockB = aligned_new<RhsScalar>(m_sizeB); } void allocateAll() { allocateA(); allocateB(); } ~gemm_blocking_space() { aligned_delete(this->m_blockA, m_sizeA); aligned_delete(this->m_blockB, m_sizeB); } }; } // end namespace internal namespace internal { template<typename Lhs, typename Rhs> struct generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> : generic_product_impl_base<Lhs,Rhs,generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,GemmProduct> > { typedef typename Product<Lhs,Rhs>::Scalar Scalar; typedef typename Lhs::Scalar LhsScalar; typedef typename Rhs::Scalar RhsScalar; typedef internal::blas_traits<Lhs> LhsBlasTraits; typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; typedef typename internal::remove_all<ActualLhsType>::type ActualLhsTypeCleaned; typedef internal::blas_traits<Rhs> RhsBlasTraits; typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; typedef typename internal::remove_all<ActualRhsType>::type ActualRhsTypeCleaned; enum { MaxDepthAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(Lhs::MaxColsAtCompileTime,Rhs::MaxRowsAtCompileTime) }; typedef generic_product_impl<Lhs,Rhs,DenseShape,DenseShape,CoeffBasedProductMode> lazyproduct; template<typename Dst> static void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { // See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=404 for a discussion and helper boundProgram // to determine the following heuristic. // EIGEN_GEMM_TO_COEFFBASED_THRESHOLD is typically defined to 20 in GeneralProduct.h, // unless it has been specialized by the user or for a given architecture. // Note that the condition rhs.rows()>0 was required because lazy product is (was?) not happy with empty inputs. // I'm not sure it is still required. if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::assign_op<typename Dst::Scalar,Scalar>()); else { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } } template<typename Dst> static void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::add_assign_op<typename Dst::Scalar,Scalar>()); else scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } template<typename Dst> static void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) { if((rhs.rows()+dst.rows()+dst.cols())<EIGEN_GEMM_TO_COEFFBASED_THRESHOLD && rhs.rows()>0) lazyproduct::eval_dynamic(dst, lhs, rhs, internal::sub_assign_op<typename Dst::Scalar,Scalar>()); else scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } template<typename Dest> static void scaleAndAddTo(Dest& dst, const Lhs& a_lhs, const Rhs& a_rhs, const Scalar& alpha) { eigen_assert(dst.rows()==a_lhs.rows() && dst.cols()==a_rhs.cols()); if(a_lhs.cols()==0 || a_lhs.rows()==0 || a_rhs.cols()==0) return; // Fallback to GEMV if either the lhs or rhs is a runtime vector if (dst.cols() == 1) { typename Dest::ColXpr dst_vec(dst.col(0)); return internal::generic_product_impl<Lhs,typename Rhs::ConstColXpr,DenseShape,DenseShape,GemvProduct> ::scaleAndAddTo(dst_vec, a_lhs, a_rhs.col(0), alpha); } else if (dst.rows() == 1) { typename Dest::RowXpr dst_vec(dst.row(0)); return internal::generic_product_impl<typename Lhs::ConstRowXpr,Rhs,DenseShape,DenseShape,GemvProduct> ::scaleAndAddTo(dst_vec, a_lhs.row(0), a_rhs, alpha); } typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(a_lhs); typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(a_rhs); Scalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(a_lhs) * RhsBlasTraits::extractScalarFactor(a_rhs); typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,LhsScalar,RhsScalar, Dest::MaxRowsAtCompileTime,Dest::MaxColsAtCompileTime,MaxDepthAtCompileTime> BlockingType; typedef internal::gemm_functor< Scalar, Index, internal::general_matrix_matrix_product< Index, LhsScalar, (ActualLhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(LhsBlasTraits::NeedToConjugate), RhsScalar, (ActualRhsTypeCleaned::Flags&RowMajorBit) ? RowMajor : ColMajor, bool(RhsBlasTraits::NeedToConjugate), (Dest::Flags&RowMajorBit) ? RowMajor : ColMajor, Dest::InnerStrideAtCompileTime>, ActualLhsTypeCleaned, ActualRhsTypeCleaned, Dest, BlockingType> GemmFunctor; BlockingType blocking(dst.rows(), dst.cols(), lhs.cols(), 1, true); internal::parallelize_gemm<(Dest::MaxRowsAtCompileTime>32 || Dest::MaxRowsAtCompileTime==Dynamic)> (GemmFunctor(lhs, rhs, dst, actualAlpha, blocking), a_lhs.rows(), a_rhs.cols(), a_lhs.cols(), Dest::Flags&RowMajorBit); } }; } // end namespace internal } // end namespace Eigen #endif // EIGEN_GENERAL_MATRIX_MATRIX_H
EmbeddingBag.h
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/libxsmm/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Dhiraj Kalamkar, Evangelos Georganas (Intel Corp.) ******************************************************************************/ #if defined(USE_LIBXSMM_JIT) #include <libxsmm.h> #endif #include "utils.h" #include "rtm.h" template <typename T> class EmbeddingBagImpl { public: EmbeddingBagImpl(long M, long E) : M(M), E(E) { #ifdef USE_LIBXSMM_JIT libxsmm_meltw_unary_shape unary_shape_f32 = libxsmm_create_meltw_unary_shape( E, 0, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 ); libxsmm_meltw_unary_shape unary_shape_f16 = libxsmm_create_meltw_unary_shape( E, 0, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 ); libxsmm_meltw_binary_shape binary_shape_f32 = libxsmm_create_meltw_binary_shape( E, 1, _ld, _ld, _ld, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32 ); weight_ = (T*)my_malloc((size_t)M * E * sizeof(T), alignment); _ld = E; if (sizeof(T) == 4) { kernel = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REDUCE_COLS_IDX_OP_ADD, unary_shape_f32, (sizeof(long) == 8) ? LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_8BYTES : LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_4BYTES ); } else { kernel = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REDUCE_COLS_IDX_OP_ADD, unary_shape_f16, (sizeof(long) == 8) ? LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_8BYTES : LIBXSMM_MELTW_FLAG_UNARY_IDX_SIZE_4BYTES ); } kernel1 = libxsmm_dispatch_meltw_unary_v2( LIBXSMM_MELTW_TYPE_UNARY_REPLICATE_COL_VAR, unary_shape_f32, LIBXSMM_MELTW_FLAG_UNARY_NONE ); kernel2 = libxsmm_dispatch_meltw_binary_v2( LIBXSMM_MELTW_TYPE_BINARY_MULADD, binary_shape_f32, LIBXSMM_MELTW_FLAG_BINARY_BCAST_SCALAR_IN_0 ); #endif } ~EmbeddingBagImpl() { my_free(weight_); weight_ = 0; } void init(T low = -0.1, T high = 0.1) { init_random(M * E, weight_, low, high); } #ifdef USE_LIBXSMM_JIT void forward(long N, long NS, const long *offsets, const long *indices, T *output_) { T(*__restrict weight)[E] = (T(*)[*])weight_; T(*__restrict output)[E] = (T(*)[*])output_; #pragma omp parallel for for (int n = 0; n < N; n++) { libxsmm_meltw_unary_param params; auto start = offsets[n]; auto end = (n < N - 1 ? offsets[n + 1] : NS); unsigned long long __n = end-start; params.in.primary = weight; params.in.secondary = (void*)&indices[start]; params.in.tertiary = &__n; params.out.primary = &output[n][0]; kernel( &params ); } } #else void forward(long N, long NS, const long *offsets, const long *indices, T *output_) { T(*__restrict weight)[E] = (T(*)[*])weight_; T(*__restrict output)[E] = (T(*)[*])output_; #pragma omp parallel for for (long n = 0; n < N; n++) { auto start = offsets[n]; auto end = (n < N - 1 ? offsets[n + 1] : NS); #pragma omp simd for (long v = 0; v < E; v++) output[n][v] = 0; for (long s = start; s < end; s++) { auto ind = indices[s]; #pragma omp simd for (long v = 0; v < E; v++) { output[n][v] += weight[ind][v]; } } } } #endif #ifdef USE_LIBXSMM_JIT void backward(long N, long NS, const T *gradout_, const long *offsets, const long *indices, T *values_) { T(*__restrict gradout)[E] = (T(*)[*])gradout_; T(*__restrict values)[E] = (T(*)[*])values_; int _ld = E; #pragma omp parallel for for (long n = 0; n < N; n++) { libxsmm_meltw_unary_param unary_param; auto start = offsets[n]; auto end = (n < N - 1 ? offsets[n + 1] : NS); unsigned long long _N = end-start; unary_param.in.primary = (void*)&gradout[n][0]; unary_param.out.primary = (void*)&values[start][0]; unary_param.op.primary = (void*)&_N; kernel1(&unary_param); } } #else void backward(long N, long NS, const T *gradout_, const long *offsets, const long *indices, T *values_) { T(*__restrict gradout)[E] = (T(*)[*])gradout_; T(*__restrict values)[E] = (T(*)[*])values_; #pragma omp parallel for for (long n = 0; n < N; n++) { auto start = offsets[n]; auto end = (n < N - 1 ? offsets[n + 1] : NS); for (long s = start; s < end; s++) { #pragma omp simd #ifdef STREAMING_WRITES #pragma vector nontemporal(values) #endif for (long v = 0; v < E; v++) values[s][v] = gradout[n][v]; } } } #endif #ifdef USE_LIBXSMM_JIT void update(long NS, const T *grads_, const long *indices, float lr, long M, int use_rtm) { int use_lock_free = use_rtm == 0 ? 1: 0; T(*__restrict weight)[E] = (T(*)[*])weight_; T(*__restrict grads)[E] = (T(*)[*])grads_; int _ld = E; if(use_lock_free) { /*printf("Using lock free update\n");*/ int max_thr = omp_get_max_threads(); if(M < max_thr) max_thr = M; #pragma omp parallel num_threads(max_thr) { int tid = omp_get_thread_num(); for(long i = 0; i < NS; i++) { auto ind = indices[i]; if(ind % max_thr == tid) { libxsmm_meltw_binary_param binary_param; binary_param.in0.primary = (void*)&lr; binary_param.in1.primary = (void*)&grads[i][0]; binary_param.out.primary = (void*)&weight[ind][0]; { kernel2(&binary_param); } } } } } else { SimpleSpinLock fallBackLock; #pragma omp parallel for for (long i = 0; i < NS; i++) { libxsmm_meltw_binary_param binary_param; long ind = indices[i]; binary_param.in0.primary = (void*)&lr; binary_param.in1.primary = (void*)&grads[i][0]; binary_param.out.primary = (void*)&weight[ind][0]; { TransactionScope guard(fallBackLock, 100, 0); kernel2(&binary_param); } } } } #else void update(long NS, const T *grads_, const long *indices, float lr, long M, int use_rtm) { T(*__restrict weight)[E] = (T(*)[*])weight_; T(*__restrict grads)[E] = (T(*)[*])grads_; int use_lock_free = use_rtm == 0 ? 1: 0; if(use_lock_free) { int max_thr = omp_get_max_threads(); if(M < max_thr) max_thr = M; #pragma omp parallel num_threads(max_thr) { int tid = omp_get_thread_num(); for(long i = 0; i < NS; i++) { auto ind = indices[i]; if(ind % max_thr == tid) { #pragma omp simd for (long v = 0; v < E; v++) weight[ind][v] += lr * grads[i][v]; } } } } else { SimpleSpinLock fallBackLock; #pragma omp parallel for for (long i = 0; i < NS; i++) { long ind = indices[i]; { TransactionScope guard(fallBackLock, 100, 0); #pragma omp simd for (long v = 0; v < E; v++) weight[ind][v] += lr * grads[i][v]; } } } } #endif T *weight_; long M; long E; #ifdef USE_LIBXSMM_JIT int _ld; libxsmm_meltwfunction_unary kernel; libxsmm_meltwfunction_unary kernel1; libxsmm_meltwfunction_binary kernel2; #endif };
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 16; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_unaryop__minv_fp64_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_fp64_fp32 // op(A') function: GB_tran__minv_fp64_fp32 // C type: double // A type: float // cast: double cij = (double) aij // unaryop: cij = 1./aij #define GB_ATYPE \ float #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./x ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp64_fp32 ( double *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
knncpp.h
/* knncpp.h * * Author: Fabian Meyer * Created On: 22 Aug 2021 * License: MIT */ #ifndef KNNCPP_H_ #define KNNCPP_H_ #include <Eigen/Geometry> #include <vector> #include <map> #include <set> #ifdef KNNCPP_FLANN #include <flann/flann.hpp> #endif namespace knncpp { /******************************************************** * Matrix Definitions *******************************************************/ typedef typename Eigen::MatrixXd::Index Index; typedef Eigen::Matrix<Index, Eigen::Dynamic, 1> Vectori; typedef Eigen::Matrix<Index, 2, 1> Vector2i; typedef Eigen::Matrix<Index, 3, 1> Vector3i; typedef Eigen::Matrix<Index, 4, 1> Vector4i; typedef Eigen::Matrix<Index, 5, 1> Vector5i; typedef Eigen::Matrix<Index, Eigen::Dynamic, Eigen::Dynamic> Matrixi; typedef Eigen::Matrix<Index, 2, 2> Matrix2i; typedef Eigen::Matrix<Index, 3, 3> Matrix3i; typedef Eigen::Matrix<Index, 4, 4> Matrix4i; typedef Eigen::Matrix<Index, 5, 5> Matrix5i; typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> Matrixf; typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> Matrixd; /******************************************************** * Distance Functors *******************************************************/ /** Manhatten distance functor. * This the same as the L1 minkowski distance but more efficient. * @see EuclideanDistance, ChebyshevDistance, MinkowskiDistance */ template <typename Scalar> struct ManhattenDistance { /** Compute the unrooted distance between two vectors. * @param lhs vector on left hand side * @param rhs vector on right hand side */ template<typename DerivedA, typename DerivedB> Scalar operator()(const Eigen::MatrixBase<DerivedA> &lhs, const Eigen::MatrixBase<DerivedB> &rhs) const { static_assert( std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,Scalar>::value, "distance scalar and input matrix A must have same type"); static_assert( std::is_same<typename Eigen::MatrixBase<DerivedB>::Scalar, Scalar>::value, "distance scalar and input matrix B must have same type"); return (lhs - rhs).cwiseAbs().sum(); } /** Compute the unrooted distance between two scalars. * @param lhs scalar on left hand side * @param rhs scalar on right hand side */ Scalar operator()(const Scalar lhs, const Scalar rhs) const { return std::abs(lhs - rhs); } /** Compute the root of a unrooted distance value. * @param value unrooted distance value */ Scalar operator()(const Scalar val) const { return val; } }; /** Euclidean distance functor. * This the same as the L2 minkowski distance but more efficient. * @see ManhattenDistance, ChebyshevDistance, MinkowskiDistance */ template <typename Scalar> struct EuclideanDistance { /** Compute the unrooted distance between two vectors. * @param lhs vector on left hand side * @param rhs vector on right hand side */ template<typename DerivedA, typename DerivedB> Scalar operator()(const Eigen::MatrixBase<DerivedA> &lhs, const Eigen::MatrixBase<DerivedB> &rhs) const { static_assert( std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,Scalar>::value, "distance scalar and input matrix A must have same type"); static_assert( std::is_same<typename Eigen::MatrixBase<DerivedB>::Scalar, Scalar>::value, "distance scalar and input matrix B must have same type"); return (lhs - rhs).cwiseAbs2().sum(); } /** Compute the unrooted distance between two scalars. * @param lhs scalar on left hand side * @param rhs scalar on right hand side */ Scalar operator()(const Scalar lhs, const Scalar rhs) const { Scalar diff = lhs - rhs; return diff * diff; } /** Compute the root of a unrooted distance value. * @param value unrooted distance value */ Scalar operator()(const Scalar val) const { return std::sqrt(val); } }; /** General minkowski distance functor. * The infinite version is only available through the chebyshev distance. * @see ManhattenDistance, EuclideanDistance, ChebyshevDistance */ template <typename Scalar, int P> struct MinkowskiDistance { struct Pow { Scalar operator()(const Scalar val) const { Scalar result = 1; for(int i = 0; i < P; ++i) result *= val; return result; } }; /** Compute the unrooted distance between two vectors. * @param lhs vector on left hand side * @param rhs vector on right hand side */ template<typename DerivedA, typename DerivedB> Scalar operator()(const Eigen::MatrixBase<DerivedA> &lhs, const Eigen::MatrixBase<DerivedB> &rhs) const { static_assert( std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,Scalar>::value, "distance scalar and input matrix A must have same type"); static_assert( std::is_same<typename Eigen::MatrixBase<DerivedB>::Scalar, Scalar>::value, "distance scalar and input matrix B must have same type"); return (lhs - rhs).cwiseAbs().unaryExpr(MinkowskiDistance::Pow()).sum(); } /** Compute the unrooted distance between two scalars. * @param lhs scalar on left hand side * @param rhs scalar on right hand side */ Scalar operator()(const Scalar lhs, const Scalar rhs) const { return std::pow(std::abs(lhs - rhs), P);; } /** Compute the root of a unrooted distance value. * @param value unrooted distance value */ Scalar operator()(const Scalar val) const { return std::pow(val, 1 / static_cast<Scalar>(P)); } }; /** Chebyshev distance functor. * This distance is the same as infinity minkowski distance. * @see ManhattenDistance, EuclideanDistance, MinkowskiDistance */ template<typename Scalar> struct ChebyshevDistance { /** Compute the unrooted distance between two vectors. * @param lhs vector on left hand side * @param rhs vector on right hand side */ template<typename DerivedA, typename DerivedB> Scalar operator()(const Eigen::MatrixBase<DerivedA> &lhs, const Eigen::MatrixBase<DerivedB> &rhs) const { static_assert( std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,Scalar>::value, "distance scalar and input matrix A must have same type"); static_assert( std::is_same<typename Eigen::MatrixBase<DerivedB>::Scalar, Scalar>::value, "distance scalar and input matrix B must have same type"); return (lhs - rhs).cwiseAbs().maxCoeff(); } /** Compute the unrooted distance between two scalars. * @param lhs scalar on left hand side * @param rhs scalar on right hand side */ Scalar operator()(const Scalar lhs, const Scalar rhs) const { return std::abs(lhs - rhs); } /** Compute the root of a unrooted distance value. * @param value unrooted distance value */ Scalar operator()(const Scalar val) const { return val; } }; /** Hamming distance functor. * The distance vectors have to be of integral type and should hold the * information vectors as bitmasks. * Performs a XOR operation on the vectors and counts the number of set * ones. */ template<typename Scalar> struct HammingDistance { static_assert(std::is_integral<Scalar>::value, "HammingDistance requires integral Scalar type"); struct XOR { Scalar operator()(const Scalar lhs, const Scalar rhs) const { return lhs ^ rhs; } }; struct BitCount { Scalar operator()(const Scalar lhs) const { Scalar copy = lhs; Scalar result = 0; while(copy != static_cast<Scalar>(0)) { ++result; copy &= (copy - 1); } return result; } }; /** Compute the unrooted distance between two vectors. * @param lhs vector on left hand side * @param rhs vector on right hand side */ template<typename DerivedA, typename DerivedB> Scalar operator()(const Eigen::MatrixBase<DerivedA> &lhs, const Eigen::MatrixBase<DerivedB> &rhs) const { static_assert( std::is_same<typename Eigen::MatrixBase<DerivedA>::Scalar,Scalar>::value, "distance scalar and input matrix A must have same type"); static_assert( std::is_same<typename Eigen::MatrixBase<DerivedB>::Scalar, Scalar>::value, "distance scalar and input matrix B must have same type"); return lhs. binaryExpr(rhs, XOR()). unaryExpr(BitCount()). sum(); } /** Compute the unrooted distance between two scalars. * @param lhs scalar on left hand side * @param rhs scalar on right hand side */ Scalar operator()(const Scalar lhs, const Scalar rhs) const { BitCount cnt; XOR xOr; return cnt(xOr(lhs, rhs)); } /** Compute the root of a unrooted distance value. * @param value unrooted distance value */ Scalar operator()(const Scalar value) const { return value; } }; /** Efficient heap structure to query nearest neighbours. */ template<typename Scalar> class QueryHeap { private: Index *indices_ = nullptr; Scalar *distances_ = nullptr; size_t maxSize_ = 0; size_t size_ = 0; public: /** Creates a query heap with the given index and distance memory regions. */ QueryHeap(Index *indices, Scalar *distances, const size_t maxSize) : indices_(indices), distances_(distances), maxSize_(maxSize) { } /** Pushes a new query data set into the heap with the given * index and distance. * The index identifies the point for which the given distance * was computed. * @param idx index / ID of the query point * @param dist distance that was computed for the query point*/ void push(const Index idx, const Scalar dist) { assert(!full()); // add new value at the end indices_[size_] = idx; distances_[size_] = dist; ++size_; // upheap size_t k = size_ - 1; size_t tmp = (k - 1) / 2; while(k > 0 && distances_[tmp] < dist) { distances_[k] = distances_[tmp]; indices_[k] = indices_[tmp]; k = tmp; tmp = (k - 1) / 2; } distances_[k] = dist; indices_[k] = idx; } /** Removes the element at the front of the heap and restores * the heap order. */ void pop() { assert(!empty()); // replace first element with last --size_; distances_[0] = distances_[size_]; indices_[0] = indices_[size_]; // downheap size_t k = 0; size_t j; Scalar dist = distances_[0]; Index idx = indices_[0]; while(2 * k + 1 < size_) { j = 2 * k + 1; if(j + 1 < size_ && distances_[j+1] > distances_[j]) ++j; // j references now greatest child if(dist >= distances_[j]) break; distances_[k] = distances_[j]; indices_[k] = indices_[j]; k = j; } distances_[k] = dist; indices_[k] = idx; } /** Returns the distance of the element in front of the heap. */ Scalar front() const { assert(!empty()); return distances_[0]; } /** Determines if this query heap is full. * The heap is considered full if its number of elements * has reached its max size. * @return true if the heap is full, else false */ bool full() const { return size_ >= maxSize_; } /** Determines if this query heap is empty. * @return true if the heap contains no elements, else false */ bool empty() const { return size_ == 0; } /** Returns the number of elements within the query heap. * @return number of elements in the heap */ size_t size() const { return size_; } /** Clears the query heap. */ void clear() { size_ = 0; } /** Sorts the elements within the heap according to * their distance. */ void sort() { size_t cnt = size_; for(size_t i = 0; i < cnt; ++i) { Index idx = indices_[0]; Scalar dist = distances_[0]; pop(); indices_[cnt - i - 1] = idx; distances_[cnt - i - 1] = dist; } } }; /** Class for performing brute force knn search. */ template<typename Scalar, typename Distance=EuclideanDistance<Scalar>> class BruteForce { public: typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector; typedef knncpp::Matrixi Matrixi; private: Distance distance_ = Distance(); Matrix dataCopy_ = Matrix(); const Matrix *data_ = nullptr; bool sorted_ = true; bool takeRoot_ = true; Index threads_ = 1; Scalar maxDist_ = 0; public: BruteForce() = default; /** Constructs a brute force instance with the given data. * @param data NxM matrix, M points of dimension N * @param copy if true copies the data, otherwise assumes static data */ BruteForce(const Matrix &data, const bool copy = false) : BruteForce() { setData(data, copy); } /** Set if the points returned by the queries should be sorted * according to their distance to the query points. * @param sorted sort query results */ void setSorted(const bool sorted) { sorted_ = sorted; } /** Set if the distances after the query should be rooted or not. * Taking the root of the distances increases query time, but the * function will return true distances instead of their powered * versions. * @param takeRoot set true if root should be taken else false */ void setTakeRoot(const bool takeRoot) { takeRoot_ = takeRoot; } /** Set the amount of threads that should be used for querying. * OpenMP has to be enabled for this to work. * @param threads amount of threads, 0 for optimal choice */ void setThreads(const unsigned int threads) { threads_ = threads; } /** Set the maximum distance for querying the tree. * The search will be pruned if the maximum distance is set to any * positive number. * @param maxDist maximum distance, <= 0 for no limit */ void setMaxDistance(const Scalar maxDist) { maxDist_ = maxDist; } /** Set the data points used for this tree. * This does not build the tree. * @param data NxM matrix, M points of dimension N * @param copy if true data is copied, assumes static data otherwise */ void setData(const Matrix &data, const bool copy = false) { if(copy) { dataCopy_ = data; data_ = &dataCopy_; } else { data_ = &data; } } void setDistance(const Distance &distance) { distance_ = distance; } void build() { } template<typename Derived> void query(const Eigen::MatrixBase<Derived> &queryPoints, const size_t knn, Matrixi &indices, Matrix &distances) const { if(data_ == nullptr) throw std::runtime_error("cannot query BruteForce: data not set"); if(data_->size() == 0) throw std::runtime_error("cannot query BruteForce: data is empty"); if(queryPoints.rows() != dimension()) throw std::runtime_error("cannot query BruteForce: data and query descriptors do not have same dimension"); const Matrix &dataPoints = *data_; indices.setConstant(knn, queryPoints.cols(), -1); distances.setConstant(knn, queryPoints.cols(), -1); #pragma omp parallel for num_threads(threads_) for(Index i = 0; i < queryPoints.cols(); ++i) { Index *idxPoint = &indices.data()[i * knn]; Scalar *distPoint = &distances.data()[i * knn]; QueryHeap<Scalar> heap(idxPoint, distPoint, knn); for(Index j = 0; j < dataPoints.cols(); ++j) { Scalar dist = distance_(queryPoints.col(i), dataPoints.col(j)); // check if point is in range if max distance was set bool isInRange = maxDist_ <= 0 || dist <= maxDist_; // check if this node was an improvement if heap is already full bool isImprovement = !heap.full() || dist < heap.front(); if(isInRange && isImprovement) { if(heap.full()) heap.pop(); heap.push(j, dist); } } if(sorted_) heap.sort(); if(takeRoot_) { for(size_t j = 0; j < knn; ++j) { if(idxPoint[j] < 0) break; distPoint[j] = distance_(distPoint[j]); } } } } /** Returns the amount of data points stored in the search index. * @return number of data points */ Index size() const { return data_ == nullptr ? 0 : data_->cols(); } /** Returns the dimension of the data points in the search index. * @return dimension of data points */ Index dimension() const { return data_ == nullptr ? 0 : data_->rows(); } }; // template<typename Scalar> // struct MeanMidpointRule // { // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; // typedef knncpp::Matrixi Matrixi; // void operator(const Matrix &data, const Matrixi &indices, Index split) // }; /** Class for performing k nearest neighbour searches with minkowski distances. * This kdtree only works reliably with the minkowski distance and its * special cases like manhatten or euclidean distance. * @see ManhattenDistance, EuclideanDistance, ChebyshevDistance, MinkowskiDistance*/ template<typename _Scalar, int _Dimension, typename _Distance> class KDTreeMinkowski { public: typedef _Scalar Scalar; typedef _Distance Distance; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; typedef Eigen::Matrix<Scalar, _Dimension, Eigen::Dynamic> DataMatrix; typedef Eigen::Matrix<Scalar, _Dimension, 1> DataVector; typedef knncpp::Matrixi Matrixi; private: typedef Eigen::Matrix<Scalar, 2, 1> Bounds; typedef Eigen::Matrix<Scalar, 2, _Dimension> BoundingBox; /** Struct representing a node in the KDTree. * It can be either a inner node or a leaf node. */ struct Node { /** Indices of data points in this leaf node. */ Index startIdx = 0; Index length = 0; /** Left child of this inner node. */ Index left = -1; /** Right child of this inner node. */ Index right = -1; /** Axis of the axis aligned splitting hyper plane. */ Index splitaxis = -1; /** Translation of the axis aligned splitting hyper plane. */ Scalar splitpoint = 0; /** Lower end of the splitpoint range */ Scalar splitlower = 0; /** Upper end of the splitpoint range */ Scalar splitupper = 0; Node() = default; /** Constructor for leaf nodes */ Node(const Index startIdx, const Index length) : startIdx(startIdx), length(length) { } /** Constructor for inner nodes */ Node(const Index splitaxis, const Scalar splitpoint, const Index left, const Index right) : left(left), right(right), splitaxis(splitaxis), splitpoint(splitpoint) { } bool isLeaf() const { return !hasLeft() && !hasRight(); } bool isInner() const { return hasLeft() && hasRight(); } bool hasLeft() const { return left >= 0; } bool hasRight() const { return right >= 0; } }; DataMatrix dataCopy_ = DataMatrix(); const DataMatrix *data_ = nullptr; std::vector<Index> indices_ = std::vector<Index>(); std::vector<Node> nodes_ = std::vector<Node>(); Index bucketSize_ = 16; bool sorted_ = true; bool compact_ = false; bool balanced_ = false; bool takeRoot_ = true; Index threads_ = 0; Scalar maxDist_ = 0; Distance distance_ = Distance(); BoundingBox bbox_ = BoundingBox(); Index buildLeafNode(const Index startIdx, const Index length, BoundingBox &bbox) { nodes_.push_back(Node(startIdx, length)); calculateBoundingBox(startIdx, length, bbox); return static_cast<Index>(nodes_.size() - 1); } /** Finds the minimum and maximum values of each dimension (row) in the * data matrix. Only respects the columns specified by the index * vector. * @param startIdx starting index within indices data structure to search for bounding box * @param length length of the block of indices*/ void calculateBoundingBox(const Index startIdx, const Index length, BoundingBox &bbox) const { assert(length > 0); assert(startIdx >= 0); assert(static_cast<size_t>(startIdx + length) <= indices_.size()); assert(data_->rows() == bbox.cols()); const DataMatrix &data = *data_; // initialize bounds of the bounding box Index first = indices_[startIdx]; for(Index i = 0; i < bbox.cols(); ++i) { bbox(0, i) = data(i, first); bbox(1, i) = data(i, first); } // search for min / max values in data for(Index i = 1; i < length; ++i) { // retrieve data index Index col = indices_[startIdx + i]; assert(col >= 0 && col < data.cols()); // check min and max for each dimension individually for(Index j = 0; j < data.rows(); ++j) { bbox(0, j) = std::min(bbox(0, j), data(j, col)); bbox(1, j) = std::max(bbox(1, j), data(j, col)); } } } /** Calculates the bounds (min / max values) for the given dimension and block of data. */ void calculateBounds(const Index startIdx, const Index length, const Index dim, Bounds &bounds) const { assert(length > 0); assert(startIdx >= 0); assert(static_cast<size_t>(startIdx + length) <= indices_.size()); const DataMatrix &data = *data_; bounds(0) = data(dim, indices_[startIdx]); bounds(1) = data(dim, indices_[startIdx]); for(Index i = 1; i < length; ++i) { Index col = indices_[startIdx + i]; assert(col >= 0 && col < data.cols()); bounds(0) = std::min(bounds(0), data(dim, col)); bounds(1) = std::max(bounds(1), data(dim, col)); } } void calculateSplittingMidpoint(const Index startIdx, const Index length, const BoundingBox &bbox, Index &splitaxis, Scalar &splitpoint, Index &splitoffset) { const DataMatrix &data = *data_; // search for axis with longest distance splitaxis = 0; Scalar splitsize = static_cast<Scalar>(0); for(Index i = 0; i < data.rows(); ++i) { Scalar diff = bbox(1, i) - bbox(0, i); if(diff > splitsize) { splitaxis = i; splitsize = diff; } } // calculate the bounds in this axis and update our data // accordingly Bounds bounds; calculateBounds(startIdx, length, splitaxis, bounds); splitsize = bounds(1) - bounds(0); const Index origSplitaxis = splitaxis; for(Index i = 0; i < data.rows(); ++i) { // skip the dimension of the previously found splitaxis if(i == origSplitaxis) continue; Scalar diff = bbox(1, i) - bbox(0, i); // check if the split for this dimension would be potentially larger if(diff > splitsize) { Bounds newBounds; // update the bounds to their actual current value calculateBounds(startIdx, length, splitaxis, newBounds); diff = newBounds(1) - newBounds(0); if(diff > splitsize) { splitaxis = i; splitsize = diff; bounds = newBounds; } } } // use the sliding midpoint rule splitpoint = (bounds(0) + bounds(1)) / static_cast<Scalar>(2); Index leftIdx = startIdx; Index rightIdx = startIdx + length - 1; // first loop checks left < splitpoint and right >= splitpoint while(leftIdx <= rightIdx) { // increment left as long as left has not reached right and // the value of the left element is less than the splitpoint while(leftIdx <= rightIdx && data(splitaxis, indices_[leftIdx]) < splitpoint) ++leftIdx; // decrement right as long as left has not reached right and // the value of the right element is greater than the splitpoint while(leftIdx <= rightIdx && data(splitaxis, indices_[rightIdx]) >= splitpoint) --rightIdx; if(leftIdx <= rightIdx) { std::swap(indices_[leftIdx], indices_[rightIdx]); ++leftIdx; --rightIdx; } } // remember this offset from starting index const Index offset1 = leftIdx - startIdx; rightIdx = startIdx + length - 1; // second loop checks left <= splitpoint and right > splitpoint while(leftIdx <= rightIdx) { // increment left as long as left has not reached right and // the value of the left element is less than the splitpoint while(leftIdx <= rightIdx && data(splitaxis, indices_[leftIdx]) <= splitpoint) ++leftIdx; // decrement right as long as left has not reached right and // the value of the right element is greater than the splitpoint while(leftIdx <= rightIdx && data(splitaxis, indices_[rightIdx]) > splitpoint) --rightIdx; if(leftIdx <= rightIdx) { std::swap(indices_[leftIdx], indices_[rightIdx]); ++leftIdx; --rightIdx; } } // remember this offset from starting index const Index offset2 = leftIdx - startIdx; const Index halfLength = length / static_cast<Index>(2); // find a separation of points such that is best balanced // offset1 denotes separation where equal points are all on the right // offset2 denots separation where equal points are all on the left if (offset1 > halfLength) splitoffset = offset1; else if (offset2 < halfLength) splitoffset = offset2; // when we get here offset1 < halflength and offset2 > halflength // so simply split the equal elements in the middle else splitoffset = halfLength; } Index buildInnerNode(const Index startIdx, const Index length, BoundingBox &bbox) { assert(length > 0); assert(startIdx >= 0); assert(static_cast<size_t>(startIdx + length) <= indices_.size()); assert(data_->rows() == bbox.cols()); // create node const Index nodeIdx = nodes_.size(); nodes_.push_back(Node()); Index splitaxis; Index splitoffset; Scalar splitpoint; calculateSplittingMidpoint(startIdx, length, bbox, splitaxis, splitpoint, splitoffset); nodes_[nodeIdx].splitaxis = splitaxis; nodes_[nodeIdx].splitpoint = splitpoint; const Index leftStart = startIdx; const Index leftLength = splitoffset; const Index rightStart = startIdx + splitoffset; const Index rightLength = length - splitoffset; BoundingBox bboxLeft = bbox; BoundingBox bboxRight = bbox; // do left build bboxLeft(1, splitaxis) = splitpoint; Index left = buildR(leftStart, leftLength, bboxLeft); nodes_[nodeIdx].left = left; // do right build bboxRight(0, splitaxis) = splitpoint; Index right = buildR(rightStart, rightLength, bboxRight); nodes_[nodeIdx].right = right; // extract the range of the splitpoint nodes_[nodeIdx].splitlower = bboxLeft(1, splitaxis); nodes_[nodeIdx].splitupper = bboxRight(0, splitaxis); // update the bounding box to the values of the new bounding boxes for(Index i = 0; i < bbox.cols(); ++i) { bbox(0, i) = std::min(bboxLeft(0, i), bboxRight(0, i)); bbox(1, i) = std::max(bboxLeft(1, i), bboxRight(1, i)); } return nodeIdx; } Index buildR(const Index startIdx, const Index length, BoundingBox &bbox) { // check for base case if(length <= bucketSize_) return buildLeafNode(startIdx, length, bbox); else return buildInnerNode(startIdx, length, bbox); } bool isDistanceInRange(const Scalar dist) const { return maxDist_ <= 0 || dist <= maxDist_; } bool isDistanceImprovement(const Scalar dist, const QueryHeap<Scalar> &dataHeap) const { return !dataHeap.full() || dist < dataHeap.front(); } template<typename Derived> void queryLeafNode(const Node &node, const Eigen::MatrixBase<Derived> &queryPoint, QueryHeap<Scalar> &dataHeap) const { assert(node.isLeaf()); const DataMatrix &data = *data_; // go through all points in this leaf node and do brute force search for(Index i = 0; i < node.length; ++i) { const Index idx = node.startIdx + i; assert(idx >= 0 && idx < static_cast<Index>(indices_.size())); // retrieve index of the current data point const Index dataIdx = indices_[idx]; const Scalar dist = distance_(queryPoint, data.col(dataIdx)); // check if point is within max distance and if the value would be // an improvement if(isDistanceInRange(dist) && isDistanceImprovement(dist, dataHeap)) { if(dataHeap.full()) dataHeap.pop(); dataHeap.push(dataIdx, dist); } } } template<typename Derived> void queryInnerNode(const Node &node, const Eigen::MatrixBase<Derived> &queryPoint, QueryHeap<Scalar> &dataHeap, DataVector &splitdists, const Scalar mindist) const { assert(node.isInner()); const Index splitaxis = node.splitaxis; const Scalar splitval = queryPoint(splitaxis, 0); Scalar splitdist; Index firstNode; Index secondNode; // check if right or left child should be visited const bool visitLeft = (splitval - node.splitlower + splitval - node.splitupper) < 0; if(visitLeft) { firstNode = node.left; secondNode = node.right; splitdist = distance_(splitval, node.splitupper); } else { firstNode = node.right; secondNode = node.left; splitdist = distance_(splitval, node.splitlower); } queryR(nodes_[firstNode], queryPoint, dataHeap, splitdists, mindist); const Scalar mindistNew = mindist + splitdist - splitdists(splitaxis); // check if node is in range if max distance was set // check if this node was an improvement if heap is already full if(isDistanceInRange(mindistNew) && isDistanceImprovement(mindistNew, dataHeap)) { const Scalar splitdistOld = splitdists(splitaxis); splitdists(splitaxis) = splitdist; queryR(nodes_[secondNode], queryPoint, dataHeap, splitdists, mindistNew); splitdists(splitaxis) = splitdistOld; } } template<typename Derived> void queryR(const Node &node, const Eigen::MatrixBase<Derived> &queryPoint, QueryHeap<Scalar> &dataHeap, DataVector &splitdists, const Scalar mindist) const { if(node.isLeaf()) queryLeafNode(node, queryPoint, dataHeap); else queryInnerNode(node, queryPoint, dataHeap, splitdists, mindist); } /** Recursively computes the depth for the given node. */ Index depthR(const Node &node) const { if(node.isLeaf()) return 1; else { Index left = depthR(nodes_[node.left]); Index right = depthR(nodes_[node.right]); return std::max(left, right) + 1; } } public: /** Constructs an empty KDTree. */ KDTreeMinkowski() { } /** Constructs KDTree with the given data. This does not build the * the index of the tree. * @param data NxM matrix, M points of dimension N * @param copy if true copies the data, otherwise assumes static data */ KDTreeMinkowski(const DataMatrix &data, const bool copy=false) { setData(data, copy); } /** Set the maximum amount of data points per leaf in the tree (aka * bucket size). * @param bucketSize amount of points per leaf. */ void setBucketSize(const Index bucketSize) { bucketSize_ = bucketSize; } /** Set if the points returned by the queries should be sorted * according to their distance to the query points. * @param sorted sort query results */ void setSorted(const bool sorted) { sorted_ = sorted; } /** Set if the tree should be built as balanced as possible. * This increases build time, but decreases search time. * @param balanced set true to build a balanced tree */ void setBalanced(const bool balanced) { balanced_ = balanced; } /** Set if the distances after the query should be rooted or not. * Taking the root of the distances increases query time, but the * function will return true distances instead of their powered * versions. * @param takeRoot set true if root should be taken else false */ void setTakeRoot(const bool takeRoot) { takeRoot_ = takeRoot; } /** Set if the tree should be built with compact leaf nodes. * This increases build time, but makes leaf nodes denser (more) * points. Thus less visits are necessary. * @param compact set true ti build a tree with compact leafs */ void setCompact(const bool compact) { compact_ = compact; } /** Set the amount of threads that should be used for building and * querying the tree. * OpenMP has to be enabled for this to work. * @param threads amount of threads, 0 for optimal choice */ void setThreads(const unsigned int threads) { threads_ = threads; } /** Set the maximum distance for querying the tree. * The search will be pruned if the maximum distance is set to any * positive number. * @param maxDist maximum distance, <= 0 for no limit */ void setMaxDistance(const Scalar maxDist) { maxDist_ = maxDist; } /** Set the data points used for this tree. * This does not build the tree. * @param data NxM matrix, M points of dimension N * @param copy if true data is copied, assumes static data otherwise */ void setData(const DataMatrix &data, const bool copy = false) { clear(); if(copy) { dataCopy_ = data; data_ = &dataCopy_; } else { data_ = &data; } } void setDistance(const Distance &distance) { distance_ = distance; } /** Builds the search index of the tree. * Data has to be set and must be non-empty. */ void build() { if(data_ == nullptr) throw std::runtime_error("cannot build KDTree; data not set"); if(data_->size() == 0) throw std::runtime_error("cannot build KDTree; data is empty"); clear(); nodes_.reserve((data_->cols() / bucketSize_) + 1); // initialize indices in simple sequence indices_.resize(data_->cols()); for(size_t i = 0; i < indices_.size(); ++i) indices_[i] = i; bbox_.resize(2, data_->rows()); Index startIdx = 0; Index length = data_->cols(); calculateBoundingBox(startIdx, length, bbox_); buildR(startIdx, length, bbox_); } /** Queries the tree for the nearest neighbours of the given query * points. * * The tree has to be built before it can be queried. * * The query points have to have the same dimension as the data points * of the tree. * * The result matrices will be resized appropriatley. * Indices and distances will be set to -1 if less than knn neighbours * were found. * * @param queryPoints NxM matrix, M points of dimension N * @param knn amount of neighbours to be found * @param indices KNNxM matrix, indices of neighbours in the data set * @param distances KNNxM matrix, distance between query points and * neighbours */ template<typename Derived> void query(const Eigen::MatrixBase<Derived> &queryPoints, const size_t knn, Matrixi &indices, Matrix &distances) const { if(nodes_.size() == 0) throw std::runtime_error("cannot query KDTree; not built yet"); if(queryPoints.rows() != dimension()) throw std::runtime_error("cannot query KDTree; data and query points do not have same dimension"); distances.setConstant(knn, queryPoints.cols(), -1); indices.setConstant(knn, queryPoints.cols(), -1); Index *indicesRaw = indices.data(); Scalar *distsRaw = distances.data(); #pragma omp parallel for num_threads(threads_) for(Index i = 0; i < queryPoints.cols(); ++i) { Scalar *distPoint = &distsRaw[i * knn]; Index *idxPoint = &indicesRaw[i * knn]; // create heap to find nearest neighbours QueryHeap<Scalar> dataHeap(idxPoint, distPoint, knn); Scalar mindist = static_cast<Scalar>(0); DataVector splitdists(queryPoints.rows()); for(Index j = 0; j < splitdists.rows(); ++j) { const Scalar value = queryPoints(j, i); const Scalar lower = bbox_(0, j); const Scalar upper = bbox_(1, j); if(value < lower) { splitdists(j) = distance_(value, lower); } else if(value > upper) { splitdists(j) = distance_(value, upper); } else { splitdists(j) = static_cast<Scalar>(0); } mindist += splitdists(j); } queryR(nodes_[0], queryPoints.col(i), dataHeap, splitdists, mindist); if(sorted_) dataHeap.sort(); if(takeRoot_) { for(size_t j = 0; j < knn; ++j) { if(distPoint[j] < 0) break; distPoint[j] = distance_(distPoint[j]); } } } } /** Clears the tree. */ void clear() { nodes_.clear(); } /** Returns the amount of data points stored in the search index. * @return number of data points */ Index size() const { return data_ == nullptr ? 0 : data_->cols(); } /** Returns the dimension of the data points in the search index. * @return dimension of data points */ Index dimension() const { return data_ == nullptr ? 0 : data_->rows(); } /** Returns the maxximum depth of the tree. * @return maximum depth of the tree */ Index depth() const { return nodes_.size() == 0 ? 0 : depthR(nodes_.front()); } }; template<typename _Scalar, typename _Distance = EuclideanDistance<_Scalar>> using KDTreeMinkowski2 = KDTreeMinkowski<_Scalar, 2, _Distance>; template<typename _Scalar, typename _Distance = EuclideanDistance<_Scalar>> using KDTreeMinkowski3 = KDTreeMinkowski<_Scalar, 3, _Distance>; template<typename _Scalar, typename _Distance = EuclideanDistance<_Scalar>> using KDTreeMinkowski4 = KDTreeMinkowski<_Scalar, 4, _Distance>; template<typename _Scalar, typename _Distance = EuclideanDistance<_Scalar>> using KDTreeMinkowski5 = KDTreeMinkowski<_Scalar, 5, _Distance>; template<typename _Scalar, typename _Distance = EuclideanDistance<_Scalar>> using KDTreeMinkowskiX = KDTreeMinkowski<_Scalar, Eigen::Dynamic, _Distance>; /** Class for performing KNN search in hamming space by multi-index hashing. */ template<typename Scalar> class MultiIndexHashing { public: static_assert(std::is_integral<Scalar>::value, "MultiIndexHashing Scalar has to be integral"); typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector; typedef knncpp::Matrixi Matrixi; private: HammingDistance<Scalar> distance_; Matrix dataCopy_; const Matrix *data_; bool sorted_; Scalar maxDist_; Index substrLen_; Index threads_; std::vector<std::map<Scalar, std::vector<Index>>> buckets_; template<typename Derived> Scalar extractCode(const Eigen::MatrixBase<Derived> &data, const Index idx, const Index offset) const { Index leftShift = std::max<Index>(0, static_cast<Index>(sizeof(Scalar)) - offset - substrLen_); Index rightShift = leftShift + offset; Scalar code = (data(idx, 0) << (leftShift * 8)) >> (rightShift * 8); if(static_cast<Index>(sizeof(Scalar)) - offset < substrLen_ && idx + 1 < data.rows()) { Index shift = 2 * static_cast<Index>(sizeof(Scalar)) - substrLen_ - offset; code |= data(idx+1, 0) << (shift * 8); } return code; } public: MultiIndexHashing() : distance_(), dataCopy_(), data_(nullptr), sorted_(true), maxDist_(0), substrLen_(1), threads_(1) { } /** Constructs an index with the given data. * This does not build the the index. * @param data NxM matrix, M points of dimension N * @param copy if true copies the data, otherwise assumes static data */ MultiIndexHashing(const Matrix &data, const bool copy=false) : MultiIndexHashing() { setData(data, copy); } /** Set the maximum distance for querying the index. * Note that if no maximum distance is used, this algorithm performs * basically a brute force search. * @param maxDist maximum distance, <= 0 for no limit */ void setMaxDistance(const Scalar maxDist) { maxDist_ = maxDist; } /** Set if the points returned by the queries should be sorted * according to their distance to the query points. * @param sorted sort query results */ void setSorted(const bool sorted) { sorted_ = sorted; } /** Set the amount of threads that should be used for building and * querying the tree. * OpenMP has to be enabled for this to work. * @param threads amount of threads, 0 for optimal choice */ void setThreads(const unsigned int threads) { threads_ = threads; } /** Set the length of substrings (in bytes) used for multi index hashing. * @param len lentth of bucket substrings in bytes*/ void setSubstringLength(const Index len) { substrLen_ = len; } /** Set the data points used for the KNN search. * @param data NxM matrix, M points of dimension N * @param copy if true data is copied, assumes static data otherwise */ void setData(const Matrix &data, const bool copy = false) { clear(); if(copy) { dataCopy_ = data; data_ = &dataCopy_; } else { data_ = &data; } } void build() { if(data_ == nullptr) throw std::runtime_error("cannot build MultiIndexHashing; data not set"); if(data_->size() == 0) throw std::runtime_error("cannot build MultiIndexHashing; data is empty"); const Matrix &data = *data_; const Index bytesPerVec = data.rows() * static_cast<Index>(sizeof(Scalar)); if(bytesPerVec % substrLen_ != 0) throw std::runtime_error("cannot build MultiIndexHashing; cannot divide byte count per vector by substring length without remainings"); buckets_.clear(); buckets_.resize(bytesPerVec / substrLen_); for(size_t i = 0; i < buckets_.size(); ++i) { Index start = static_cast<Index>(i) * substrLen_; Index idx = start / static_cast<Index>(sizeof(Scalar)); Index offset = start % static_cast<Index>(sizeof(Scalar)); std::map<Scalar, std::vector<Index>> &map = buckets_[i]; for(Index c = 0; c < data.cols(); ++c) { Scalar code = extractCode(data.col(c), idx, offset); if(map.find(code) == map.end()) map[code] = std::vector<Index>(); map[code].push_back(c); } } } template<typename Derived> void query(const Eigen::MatrixBase<Derived> &queryPoints, const size_t knn, Matrixi &indices, Matrix &distances) const { if(buckets_.size() == 0) throw std::runtime_error("cannot query MultiIndexHashing; not built yet"); if(queryPoints.rows() != dimension()) throw std::runtime_error("cannot query MultiIndexHashing; data and query points do not have same dimension"); const Matrix &data = *data_; indices.setConstant(knn, queryPoints.cols(), -1); distances.setConstant(knn, queryPoints.cols(), -1); Index *indicesRaw = indices.data(); Scalar *distsRaw = distances.data(); Scalar maxDistPart = maxDist_ / buckets_.size(); #pragma omp parallel for num_threads(threads_) for(Index c = 0; c < queryPoints.cols(); ++c) { std::set<Index> candidates; for(size_t i = 0; i < buckets_.size(); ++i) { Index start = static_cast<Index>(i) * substrLen_; Index idx = start / static_cast<Index>(sizeof(Scalar)); Index offset = start % static_cast<Index>(sizeof(Scalar)); const std::map<Scalar, std::vector<Index>> &map = buckets_[i]; Scalar code = extractCode(queryPoints.col(c), idx, offset); for(const auto &x: map) { Scalar dist = distance_(x.first, code); if(maxDistPart <= 0 || dist <= maxDistPart) { for(size_t j = 0; j < x.second.size(); ++j) candidates.insert(x.second[j]); } } } Scalar *distPoint = &distsRaw[c * knn]; Index *idxPoint = &indicesRaw[c * knn]; // create heap to find nearest neighbours QueryHeap<Scalar> dataHeap(idxPoint, distPoint, knn); for(Index idx: candidates) { Scalar dist = distance_(data.col(idx), queryPoints.col(c)); bool isInRange = maxDist_ <= 0 || dist <= maxDist_; bool isImprovement = !dataHeap.full() || dist < dataHeap.front(); if(isInRange && isImprovement) { if(dataHeap.full()) dataHeap.pop(); dataHeap.push(idx, dist); } } if(sorted_) dataHeap.sort(); } } /** Returns the amount of data points stored in the search index. * @return number of data points */ Index size() const { return data_ == nullptr ? 0 : data_->cols(); } /** Returns the dimension of the data points in the search index. * @return dimension of data points */ Index dimension() const { return data_ == nullptr ? 0 : data_->rows(); } void clear() { data_ = nullptr; dataCopy_.resize(0, 0); buckets_.clear(); } }; #ifdef KNNCPP_FLANN /** Wrapper class of FLANN kdtrees for the use with Eigen3. */ template<typename Scalar, typename Distance=flann::L2_Simple<Scalar>> class KDTreeFlann { public: typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic> Matrix; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector; typedef Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic> Matrixi; private: typedef flann::Index<Distance> FlannIndex; Matrix dataCopy_; Matrix *dataPoints_; FlannIndex *index_; flann::SearchParams searchParams_; flann::IndexParams indexParams_; Scalar maxDist_; public: KDTreeFlann() : dataCopy_(), dataPoints_(nullptr), index_(nullptr), searchParams_(32, 0, false), indexParams_(flann::KDTreeSingleIndexParams(15)), maxDist_(0) { } KDTreeFlann(Matrix &data, const bool copy = false) : KDTreeFlann() { setData(data, copy); } ~KDTreeFlann() { clear(); } void setIndexParams(const flann::IndexParams &params) { indexParams_ = params; } void setChecks(const int checks) { searchParams_.checks = checks; } void setSorted(const bool sorted) { searchParams_.sorted = sorted; } void setThreads(const int threads) { searchParams_.cores = threads; } void setEpsilon(const float eps) { searchParams_.eps = eps; } void setMaxDistance(const Scalar dist) { maxDist_ = dist; } void setData(Matrix &data, const bool copy = false) { if(copy) { dataCopy_ = data; dataPoints_ = &dataCopy_; } else { dataPoints_ = &data; } clear(); } void build() { if(dataPoints_ == nullptr) throw std::runtime_error("cannot build KDTree; data not set"); if(dataPoints_->size() == 0) throw std::runtime_error("cannot build KDTree; data is empty"); if(index_ != nullptr) delete index_; flann::Matrix<Scalar> dataPts( dataPoints_->data(), dataPoints_->cols(), dataPoints_->rows()); index_ = new FlannIndex(dataPts, indexParams_); index_->buildIndex(); } void query(Matrix &queryPoints, const size_t knn, Matrixi &indices, Matrix &distances) const { if(index_ == nullptr) throw std::runtime_error("cannot query KDTree; not built yet"); if(dataPoints_->rows() != queryPoints.rows()) throw std::runtime_error("cannot query KDTree; KDTree has different dimension than query data"); // resize result matrices distances.resize(knn, queryPoints.cols()); indices.resize(knn, queryPoints.cols()); // wrap matrices into flann matrices flann::Matrix<Scalar> queryPts( queryPoints.data(), queryPoints.cols(), queryPoints.rows()); flann::Matrix<int> indicesF( indices.data(), indices.cols(), indices.rows()); flann::Matrix<Scalar> distancesF( distances.data(), distances.cols(), distances.rows()); // if maximum distance was set then use radius search if(maxDist_ > 0) index_->radiusSearch(queryPts, indicesF, distancesF, maxDist_, searchParams_); else index_->knnSearch(queryPts, indicesF, distancesF, knn, searchParams_); // make result matrices compatible to API #pragma omp parallel for num_threads(searchParams_.cores) for(Index i = 0; i < indices.cols(); ++i) { bool found = false; for(Index j = 0; j < indices.rows(); ++j) { if(indices(j, i) == -1) found = true; if(found) { indices(j, i) = -1; distances(j, i) = -1; } } } } Index size() const { return dataPoints_ == nullptr ? 0 : dataPoints_->cols(); } Index dimension() const { return dataPoints_ == nullptr ? 0 : dataPoints_->rows(); } void clear() { if(index_ != nullptr) { delete index_; index_ = nullptr; } } FlannIndex &flannIndex() { return index_; } }; typedef KDTreeFlann<double> KDTreeFlannd; typedef KDTreeFlann<float> KDTreeFlannf; #endif } #endif
bc_adj.h
/* * bc_adj.h * LLAMA Graph Analytics * * Copyright 2014 * The President and Fellows of Harvard College. * * Copyright 2014 * Oracle Labs. * * 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 University 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 UNIVERSITY 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 UNIVERSITY OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifndef LL_GENERATED_CPP_BC_ADJ_H #define LL_GENERATED_CPP_BC_ADJ_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <float.h> #include <limits.h> #include <cmath> #include <algorithm> #include <omp.h> #include "llama/ll_bfs_template.h" #include "llama/ll_writable_graph.h" #include "benchmarks/benchmark.h" // BFS/DFS definitions for the procedure template <class Graph> class comp_BC_adj_bfs : public ll_bfs_template <Graph, short, true, false, false, true> { public: comp_BC_adj_bfs(Graph& _G, float*& _G_BC, node_t& _s, float*& _G_sigma, float*& _G_delta) : ll_bfs_template<Graph, short, true, false, false, true>(_G), G(_G), G_BC(_G_BC), s(_s), G_sigma(_G_sigma), G_delta(_G_delta){} private: // list of varaibles Graph& G; float*& G_BC; node_t& s; float*& G_sigma; float*& G_delta; protected: virtual void visit_fw(node_t v) { { ll_edge_iterator iter; G.out_iter_begin(iter, v); for (edge_t w_idx = G.out_iter_next(iter); w_idx != LL_NIL_EDGE; w_idx = G.out_iter_next(iter)) { if (!this->is_down_edge(w_idx)) continue; node_t w = LL_ITER_OUT_NEXT_NODE(G, iter, w_idx); float sigma_w_prv = 0.0 ; sigma_w_prv = ((float)(0.000000)) ; sigma_w_prv = sigma_w_prv + G_sigma[v] ; ATOMIC_ADD(&G_sigma[w], sigma_w_prv); } } } virtual void visit_rv(node_t v) { if (v != s) { float __S3 = 0.0 ; __S3 = ((float)(0.000000)) ; ll_edge_iterator iter; G.out_iter_begin(iter, v); for (edge_t w_idx = G.out_iter_next(iter); w_idx != LL_NIL_EDGE; w_idx = G.out_iter_next(iter)) { if (!this->is_down_edge(w_idx)) continue; node_t w = LL_ITER_OUT_NEXT_NODE(G, iter, w_idx); __S3 = __S3 + G_sigma[v] / G_sigma[w] * (1 + G_delta[w]) ; } G.set_node_prop(G_delta, v, __S3); G.set_node_prop(G_BC, v, G_BC[v] + G_delta[v]); } } virtual bool check_navigator(node_t v, edge_t v_idx) {return true;} }; /** * Betweenness Centrality - Exact */ template <class Graph> class ll_b_bc_adj : public ll_benchmark<Graph> { float* G_BC; public: /** * Create the benchmark */ ll_b_bc_adj() : ll_benchmark<Graph>("Betweenness Centrality - Exact") { this->create_auto_array_for_nodes(G_BC); } /** * Destroy the benchmark */ virtual ~ll_b_bc_adj(void) { } /** * Run the benchmark * * @return the numerical result, if applicable */ virtual double run(void) { Graph& G = *this->_graph; ll_memory_helper m; float* G_sigma = m.allocate<float>(G.max_nodes()); float* G_delta = m.allocate<float>(G.max_nodes()); #pragma omp parallel for for (node_t t0 = 0; t0 < G.max_nodes(); t0 ++) G.set_node_prop(G_BC, t0, (float)0); for (node_t s = 0; s < G.max_nodes(); s ++) { #pragma omp parallel for for (node_t t1 = 0; t1 < G.max_nodes(); t1 ++) G.set_node_prop(G_sigma, t1, (float)0); G.set_node_prop(G_sigma, s, (float)1); comp_BC_adj_bfs<Graph> _BFS(G, G_BC, s, G_sigma, G_delta); _BFS.prepare(s); _BFS.do_bfs_forward(); _BFS.do_bfs_reverse(); } return 0; } /** * Finalize the benchmark * * @return the updated numerical result, if applicable */ virtual double finalize(void) { float max = 0; for (node_t n = 0; n < this->_graph->max_nodes(); n++) { if (G_BC[n] > max) max = G_BC[n]; } return max; } /** * Print the results * * @param f the output file */ virtual void print_results(FILE* f) { print_results_part(f, this->_graph, G_BC); } }; #endif
StmtOpenMP.h
//===- StmtOpenMP.h - Classes for OpenMP directives ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file defines OpenMP AST classes for executable directives and /// clauses. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_STMTOPENMP_H #define LLVM_CLANG_AST_STMTOPENMP_H #include "clang/AST/Expr.h" #include "clang/AST/OpenMPClause.h" #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" namespace clang { //===----------------------------------------------------------------------===// // AST classes for directives. //===----------------------------------------------------------------------===// /// \brief This is a basic class for representing single OpenMP executable /// directive. /// class OMPExecutableDirective : public Stmt { friend class ASTStmtReader; /// \brief Kind of the directive. OpenMPDirectiveKind Kind; /// \brief Starting location of the directive (directive keyword). SourceLocation StartLoc; /// \brief Ending location of the directive. SourceLocation EndLoc; /// \brief Numbers of clauses. const unsigned NumClauses; /// \brief Number of child expressions/stmts. const unsigned NumChildren; /// \brief Offset from this to the start of clauses. /// There are NumClauses pointers to clauses, they are followed by /// NumChildren pointers to child stmts/exprs (if the directive type /// requires an associated stmt, then it has to be the first of them). const unsigned ClausesOffset; /// \brief Get the clauses storage. MutableArrayRef<OMPClause *> getClauses() { OMPClause **ClauseStorage = reinterpret_cast<OMPClause **>( reinterpret_cast<char *>(this) + ClausesOffset); return MutableArrayRef<OMPClause *>(ClauseStorage, NumClauses); } protected: /// \brief Build instance of directive of class \a K. /// /// \param SC Statement class. /// \param K Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// template <typename T> OMPExecutableDirective(const T *, StmtClass SC, OpenMPDirectiveKind K, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses, unsigned NumChildren) : Stmt(SC), Kind(K), StartLoc(std::move(StartLoc)), EndLoc(std::move(EndLoc)), NumClauses(NumClauses), NumChildren(NumChildren), ClausesOffset(llvm::alignTo(sizeof(T), alignof(OMPClause *))) {} /// \brief Sets the list of variables for this clause. /// /// \param Clauses The list of clauses for the directive. /// void setClauses(ArrayRef<OMPClause *> Clauses); /// \brief Set the associated statement for the directive. /// /// /param S Associated statement. /// void setAssociatedStmt(Stmt *S) { assert(hasAssociatedStmt() && "no associated statement."); *child_begin() = S; } public: /// \brief Iterates over a filtered subrange of clauses applied to a /// directive. /// /// This iterator visits only clauses of type SpecificClause. template <typename SpecificClause> class specific_clause_iterator : public llvm::iterator_adaptor_base< specific_clause_iterator<SpecificClause>, ArrayRef<OMPClause *>::const_iterator, std::forward_iterator_tag, const SpecificClause *, ptrdiff_t, const SpecificClause *, const SpecificClause *> { ArrayRef<OMPClause *>::const_iterator End; void SkipToNextClause() { while (this->I != End && !isa<SpecificClause>(*this->I)) ++this->I; } public: explicit specific_clause_iterator(ArrayRef<OMPClause *> Clauses) : specific_clause_iterator::iterator_adaptor_base(Clauses.begin()), End(Clauses.end()) { SkipToNextClause(); } const SpecificClause *operator*() const { return cast<SpecificClause>(*this->I); } const SpecificClause *operator->() const { return **this; } specific_clause_iterator &operator++() { ++this->I; SkipToNextClause(); return *this; } }; template <typename SpecificClause> static llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind(ArrayRef<OMPClause *> Clauses) { return {specific_clause_iterator<SpecificClause>(Clauses), specific_clause_iterator<SpecificClause>( llvm::makeArrayRef(Clauses.end(), 0))}; } template <typename SpecificClause> llvm::iterator_range<specific_clause_iterator<SpecificClause>> getClausesOfKind() const { return getClausesOfKind<SpecificClause>(clauses()); } /// Gets a single clause of the specified kind associated with the /// current directive iff there is only one clause of this kind (and assertion /// is fired if there is more than one clause is associated with the /// directive). Returns nullptr if no clause of this kind is associated with /// the directive. template <typename SpecificClause> const SpecificClause *getSingleClause() const { auto Clauses = getClausesOfKind<SpecificClause>(); if (Clauses.begin() != Clauses.end()) { assert(std::next(Clauses.begin()) == Clauses.end() && "There are at least 2 clauses of the specified kind"); return *Clauses.begin(); } return nullptr; } /// Returns true if the current directive has one or more clauses of a /// specific kind. template <typename SpecificClause> bool hasClausesOfKind() const { auto Clauses = getClausesOfKind<SpecificClause>(); return Clauses.begin() != Clauses.end(); } /// \brief Returns starting location of directive kind. SourceLocation getLocStart() const { return StartLoc; } /// \brief Returns ending location of directive. SourceLocation getLocEnd() const { return EndLoc; } /// \brief Set starting location of directive kind. /// /// \param Loc New starting location of directive. /// void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// \brief Set ending location of directive. /// /// \param Loc New ending location of directive. /// void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// \brief Get number of clauses. unsigned getNumClauses() const { return NumClauses; } /// \brief Returns specified clause. /// /// \param i Number of clause. /// OMPClause *getClause(unsigned i) const { return clauses()[i]; } /// \brief Returns true if directive has associated statement. bool hasAssociatedStmt() const { return NumChildren > 0; } /// \brief Returns statement associated with the directive. Stmt *getAssociatedStmt() const { assert(hasAssociatedStmt() && "no associated statement."); return const_cast<Stmt *>(*child_begin()); } OpenMPDirectiveKind getDirectiveKind() const { return Kind; } static bool classof(const Stmt *S) { return S->getStmtClass() >= firstOMPExecutableDirectiveConstant && S->getStmtClass() <= lastOMPExecutableDirectiveConstant; } child_range children() { if (!hasAssociatedStmt()) return child_range(child_iterator(), child_iterator()); Stmt **ChildStorage = reinterpret_cast<Stmt **>(getClauses().end()); return child_range(ChildStorage, ChildStorage + NumChildren); } ArrayRef<OMPClause *> clauses() { return getClauses(); } ArrayRef<OMPClause *> clauses() const { return const_cast<OMPExecutableDirective *>(this)->getClauses(); } }; /// \brief This represents '#pragma omp parallel' directive. /// /// \code /// #pragma omp parallel private(a,b) reduction(+: c,d) /// \endcode /// In this example directive '#pragma omp parallel' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief true if the construct has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending Location of the directive. /// OMPParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelDirectiveClass, OMPD_parallel, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement associated with the directive. /// \param HasCancel true if this directive has inner cancel directive. /// static OMPParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// \brief Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelDirectiveClass; } }; /// \brief This is a common base class for loop directives ('omp simd', 'omp /// for', 'omp for simd' etc.). It is responsible for the loop code generation. /// class OMPLoopDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Number of collapsed loops as specified by 'collapse' clause. unsigned CollapsedNum; /// \brief Offsets to the stored exprs. /// This enumeration contains offsets to all the pointers to children /// expressions stored in OMPLoopDirective. /// The first 9 children are nesessary for all the loop directives, and /// the next 10 are specific to the worksharing ones. /// After the fixed children, three arrays of length CollapsedNum are /// allocated: loop counters, their updates and final values. /// PrevLowerBound and PrevUpperBound are used to communicate blocking /// information in composite constructs which require loop blocking /// enum { AssociatedStmtOffset = 0, IterationVariableOffset = 1, LastIterationOffset = 2, CalcLastIterationOffset = 3, PreConditionOffset = 4, CondOffset = 5, InitOffset = 6, IncOffset = 7, PreInitsOffset = 8, // The '...End' enumerators do not correspond to child expressions - they // specify the offset to the end (and start of the following counters/ // updates/finals arrays). DefaultEnd = 9, // The following 7 exprs are used by worksharing loops only. IsLastIterVariableOffset = 9, LowerBoundVariableOffset = 10, UpperBoundVariableOffset = 11, StrideVariableOffset = 12, EnsureUpperBoundOffset = 13, NextLowerBoundOffset = 14, NextUpperBoundOffset = 15, NumIterationsOffset = 16, PrevLowerBoundVariableOffset = 17, PrevUpperBoundVariableOffset = 18, // Offset to the end (and start of the following counters/updates/finals // arrays) for worksharing loop directives. WorksharingEnd = 19, }; /// \brief Get the counters storage. MutableArrayRef<Expr *> getCounters() { Expr **Storage = reinterpret_cast<Expr **>( &(*(std::next(child_begin(), getArraysOffset(getDirectiveKind()))))); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// \brief Get the private counters storage. MutableArrayRef<Expr *> getPrivateCounters() { Expr **Storage = reinterpret_cast<Expr **>(&*std::next( child_begin(), getArraysOffset(getDirectiveKind()) + CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// \brief Get the updates storage. MutableArrayRef<Expr *> getInits() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 2 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// \brief Get the updates storage. MutableArrayRef<Expr *> getUpdates() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 3 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } /// \brief Get the final counter updates storage. MutableArrayRef<Expr *> getFinals() { Expr **Storage = reinterpret_cast<Expr **>( &*std::next(child_begin(), getArraysOffset(getDirectiveKind()) + 4 * CollapsedNum)); return MutableArrayRef<Expr *>(Storage, CollapsedNum); } protected: /// \brief Build instance of loop directive of class \a Kind. /// /// \param SC Statement class. /// \param Kind Kind of OpenMP directive. /// \param StartLoc Starting location of the directive (directive keyword). /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed loops from 'collapse' clause. /// \param NumClauses Number of clauses. /// \param NumSpecialChildren Number of additional directive-specific stmts. /// template <typename T> OMPLoopDirective(const T *That, StmtClass SC, OpenMPDirectiveKind Kind, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses, unsigned NumSpecialChildren = 0) : OMPExecutableDirective(That, SC, Kind, StartLoc, EndLoc, NumClauses, numLoopChildren(CollapsedNum, Kind) + NumSpecialChildren), CollapsedNum(CollapsedNum) {} /// \brief Offset to the start of children expression arrays. static unsigned getArraysOffset(OpenMPDirectiveKind Kind) { return (isOpenMPWorksharingDirective(Kind) || isOpenMPTaskLoopDirective(Kind) || isOpenMPDistributeDirective(Kind)) ? WorksharingEnd : DefaultEnd; } /// \brief Children number. static unsigned numLoopChildren(unsigned CollapsedNum, OpenMPDirectiveKind Kind) { return getArraysOffset(Kind) + 5 * CollapsedNum; // Counters, // PrivateCounters, Inits, // Updates and Finals } void setIterationVariable(Expr *IV) { *std::next(child_begin(), IterationVariableOffset) = IV; } void setLastIteration(Expr *LI) { *std::next(child_begin(), LastIterationOffset) = LI; } void setCalcLastIteration(Expr *CLI) { *std::next(child_begin(), CalcLastIterationOffset) = CLI; } void setPreCond(Expr *PC) { *std::next(child_begin(), PreConditionOffset) = PC; } void setCond(Expr *Cond) { *std::next(child_begin(), CondOffset) = Cond; } void setInit(Expr *Init) { *std::next(child_begin(), InitOffset) = Init; } void setInc(Expr *Inc) { *std::next(child_begin(), IncOffset) = Inc; } void setPreInits(Stmt *PreInits) { *std::next(child_begin(), PreInitsOffset) = PreInits; } void setIsLastIterVariable(Expr *IL) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), IsLastIterVariableOffset) = IL; } void setLowerBoundVariable(Expr *LB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), LowerBoundVariableOffset) = LB; } void setUpperBoundVariable(Expr *UB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), UpperBoundVariableOffset) = UB; } void setStrideVariable(Expr *ST) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), StrideVariableOffset) = ST; } void setEnsureUpperBound(Expr *EUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), EnsureUpperBoundOffset) = EUB; } void setNextLowerBound(Expr *NLB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextLowerBoundOffset) = NLB; } void setNextUpperBound(Expr *NUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NextUpperBoundOffset) = NUB; } void setNumIterations(Expr *NI) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), NumIterationsOffset) = NI; } void setPrevLowerBoundVariable(Expr *PrevLB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), PrevLowerBoundVariableOffset) = PrevLB; } void setPrevUpperBoundVariable(Expr *PrevUB) { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); *std::next(child_begin(), PrevUpperBoundVariableOffset) = PrevUB; } void setCounters(ArrayRef<Expr *> A); void setPrivateCounters(ArrayRef<Expr *> A); void setInits(ArrayRef<Expr *> A); void setUpdates(ArrayRef<Expr *> A); void setFinals(ArrayRef<Expr *> A); public: /// \brief The expressions built for the OpenMP loop CodeGen for the /// whole collapsed loop nest. struct HelperExprs { /// \brief Loop iteration variable. Expr *IterationVarRef; /// \brief Loop last iteration number. Expr *LastIteration; /// \brief Loop number of iterations. Expr *NumIterations; /// \brief Calculation of last iteration. Expr *CalcLastIteration; /// \brief Loop pre-condition. Expr *PreCond; /// \brief Loop condition. Expr *Cond; /// \brief Loop iteration variable init. Expr *Init; /// \brief Loop increment. Expr *Inc; /// \brief IsLastIteration - local flag variable passed to runtime. Expr *IL; /// \brief LowerBound - local variable passed to runtime. Expr *LB; /// \brief UpperBound - local variable passed to runtime. Expr *UB; /// \brief Stride - local variable passed to runtime. Expr *ST; /// \brief EnsureUpperBound -- expression LB = min(LB, NumIterations). Expr *EUB; /// \brief Update of LowerBound for statically sheduled 'omp for' loops. Expr *NLB; /// \brief Update of UpperBound for statically sheduled 'omp for' loops. Expr *NUB; /// \brief PreviousLowerBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevLB; /// \brief PreviousUpperBound - local variable passed to runtime in the /// enclosing schedule or null if that does not apply. Expr *PrevUB; /// \brief Counters Loop counters. SmallVector<Expr *, 4> Counters; /// \brief PrivateCounters Loop counters. SmallVector<Expr *, 4> PrivateCounters; /// \brief Expressions for loop counters inits for CodeGen. SmallVector<Expr *, 4> Inits; /// \brief Expressions for loop counters update for CodeGen. SmallVector<Expr *, 4> Updates; /// \brief Final loop counter values for GodeGen. SmallVector<Expr *, 4> Finals; /// Init statement for all captured expressions. Stmt *PreInits; /// \brief Check if all the expressions are built (does not check the /// worksharing ones). bool builtAll() { return IterationVarRef != nullptr && LastIteration != nullptr && NumIterations != nullptr && PreCond != nullptr && Cond != nullptr && Init != nullptr && Inc != nullptr; } /// \brief Initialize all the fields to null. /// \param Size Number of elements in the counters/finals/updates arrays. void clear(unsigned Size) { IterationVarRef = nullptr; LastIteration = nullptr; CalcLastIteration = nullptr; PreCond = nullptr; Cond = nullptr; Init = nullptr; Inc = nullptr; IL = nullptr; LB = nullptr; UB = nullptr; ST = nullptr; EUB = nullptr; NLB = nullptr; NUB = nullptr; NumIterations = nullptr; PrevLB = nullptr; PrevUB = nullptr; Counters.resize(Size); PrivateCounters.resize(Size); Inits.resize(Size); Updates.resize(Size); Finals.resize(Size); for (unsigned i = 0; i < Size; ++i) { Counters[i] = nullptr; PrivateCounters[i] = nullptr; Inits[i] = nullptr; Updates[i] = nullptr; Finals[i] = nullptr; } PreInits = nullptr; } }; /// \brief Get number of collapsed loops. unsigned getCollapsedNumber() const { return CollapsedNum; } Expr *getIterationVariable() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IterationVariableOffset))); } Expr *getLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LastIterationOffset))); } Expr *getCalcLastIteration() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), CalcLastIterationOffset))); } Expr *getPreCond() const { return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PreConditionOffset))); } Expr *getCond() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), CondOffset))); } Expr *getInit() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), InitOffset))); } Expr *getInc() const { return const_cast<Expr *>( reinterpret_cast<const Expr *>(*std::next(child_begin(), IncOffset))); } const Stmt *getPreInits() const { return *std::next(child_begin(), PreInitsOffset); } Stmt *getPreInits() { return *std::next(child_begin(), PreInitsOffset); } Expr *getIsLastIterVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), IsLastIterVariableOffset))); } Expr *getLowerBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), LowerBoundVariableOffset))); } Expr *getUpperBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), UpperBoundVariableOffset))); } Expr *getStrideVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), StrideVariableOffset))); } Expr *getEnsureUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), EnsureUpperBoundOffset))); } Expr *getNextLowerBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextLowerBoundOffset))); } Expr *getNextUpperBound() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NextUpperBoundOffset))); } Expr *getNumIterations() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), NumIterationsOffset))); } Expr *getPrevLowerBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevLowerBoundVariableOffset))); } Expr *getPrevUpperBoundVariable() const { assert((isOpenMPWorksharingDirective(getDirectiveKind()) || isOpenMPTaskLoopDirective(getDirectiveKind()) || isOpenMPDistributeDirective(getDirectiveKind())) && "expected worksharing loop directive"); return const_cast<Expr *>(reinterpret_cast<const Expr *>( *std::next(child_begin(), PrevUpperBoundVariableOffset))); } const Stmt *getBody() const { // This relies on the loop form is already checked by Sema. Stmt *Body = getAssociatedStmt()->IgnoreContainers(true); Body = cast<ForStmt>(Body)->getBody(); for (unsigned Cnt = 1; Cnt < CollapsedNum; ++Cnt) { Body = Body->IgnoreContainers(); Body = cast<ForStmt>(Body)->getBody(); } return Body; } ArrayRef<Expr *> counters() { return getCounters(); } ArrayRef<Expr *> counters() const { return const_cast<OMPLoopDirective *>(this)->getCounters(); } ArrayRef<Expr *> private_counters() { return getPrivateCounters(); } ArrayRef<Expr *> private_counters() const { return const_cast<OMPLoopDirective *>(this)->getPrivateCounters(); } ArrayRef<Expr *> inits() { return getInits(); } ArrayRef<Expr *> inits() const { return const_cast<OMPLoopDirective *>(this)->getInits(); } ArrayRef<Expr *> updates() { return getUpdates(); } ArrayRef<Expr *> updates() const { return const_cast<OMPLoopDirective *>(this)->getUpdates(); } ArrayRef<Expr *> finals() { return getFinals(); } ArrayRef<Expr *> finals() const { return const_cast<OMPLoopDirective *>(this)->getFinals(); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass || T->getStmtClass() == OMPForDirectiveClass || T->getStmtClass() == OMPForSimdDirectiveClass || T->getStmtClass() == OMPParallelForDirectiveClass || T->getStmtClass() == OMPParallelForSimdDirectiveClass || T->getStmtClass() == OMPTaskLoopDirectiveClass || T->getStmtClass() == OMPTaskLoopSimdDirectiveClass || T->getStmtClass() == OMPDistributeDirectiveClass || T->getStmtClass() == OMPTargetParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForDirectiveClass || T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPDistributeSimdDirectiveClass || T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass || T->getStmtClass() == OMPTargetSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeDirectiveClass || T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass || T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass; } }; /// \brief This represents '#pragma omp simd' directive. /// /// \code /// #pragma omp simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPSimdDirectiveClass, OMPD_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPSimdDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSimdDirectiveClass; } }; /// \brief This represents '#pragma omp for' directive. /// /// \code /// #pragma omp for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for' has clauses 'private' with the /// variables 'a' and 'b' and 'reduction' with operator '+' and variables 'c' /// and 'd'. /// class OMPForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief true if current directive has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForDirectiveClass, OMPD_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPForDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForDirectiveClass; } }; /// \brief This represents '#pragma omp for simd' directive. /// /// \code /// #pragma omp for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp for simd' has clauses 'private' /// with the variables 'a' and 'b', 'linear' with variables 'i', 'j' and /// linear step 's', 'reduction' with operator '+' and variables 'c' and 'd'. /// class OMPForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPForSimdDirectiveClass, OMPD_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPForSimdDirectiveClass; } }; /// \brief This represents '#pragma omp sections' directive. /// /// \code /// #pragma omp sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp sections' has clauses 'private' with /// the variables 'a' and 'b' and 'reduction' with operator '+' and variables /// 'c' and 'd'. /// class OMPSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief true if current directive has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSectionsDirectiveClass, OMPD_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSectionsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionsDirectiveClass; } }; /// \brief This represents '#pragma omp section' directive. /// /// \code /// #pragma omp section /// \endcode /// class OMPSectionDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief true if current directive has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPSectionDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, StartLoc, EndLoc, 0, 1), HasCancel(false) {} /// \brief Build an empty directive. /// explicit OMPSectionDirective() : OMPExecutableDirective(this, OMPSectionDirectiveClass, OMPD_section, SourceLocation(), SourceLocation(), 0, 1), HasCancel(false) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner directive. /// static OMPSectionDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt, bool HasCancel); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPSectionDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSectionDirectiveClass; } }; /// \brief This represents '#pragma omp single' directive. /// /// \code /// #pragma omp single private(a,b) copyprivate(c,d) /// \endcode /// In this example directive '#pragma omp single' has clauses 'private' with /// the variables 'a' and 'b' and 'copyprivate' with variables 'c' and 'd'. /// class OMPSingleDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPSingleDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, StartLoc, EndLoc, NumClauses, 1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPSingleDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPSingleDirectiveClass, OMPD_single, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPSingleDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPSingleDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPSingleDirectiveClass; } }; /// \brief This represents '#pragma omp master' directive. /// /// \code /// #pragma omp master /// \endcode /// class OMPMasterDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPMasterDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, StartLoc, EndLoc, 0, 1) {} /// \brief Build an empty directive. /// explicit OMPMasterDirective() : OMPExecutableDirective(this, OMPMasterDirectiveClass, OMPD_master, SourceLocation(), SourceLocation(), 0, 1) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPMasterDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPMasterDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPMasterDirectiveClass; } }; /// \brief This represents '#pragma omp critical' directive. /// /// \code /// #pragma omp critical /// \endcode /// class OMPCriticalDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Name of the directive. DeclarationNameInfo DirName; /// \brief Build directive with the given start and end location. /// /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCriticalDirective(const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, StartLoc, EndLoc, NumClauses, 1), DirName(Name) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPCriticalDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCriticalDirectiveClass, OMPD_critical, SourceLocation(), SourceLocation(), NumClauses, 1), DirName() {} /// \brief Set name of the directive. /// /// \param Name Name of the directive. /// void setDirectiveName(const DeclarationNameInfo &Name) { DirName = Name; } public: /// \brief Creates directive. /// /// \param C AST context. /// \param Name Name of the directive. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPCriticalDirective * Create(const ASTContext &C, const DeclarationNameInfo &Name, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCriticalDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Return name of the directive. /// DeclarationNameInfo getDirectiveName() const { return DirName; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCriticalDirectiveClass; } }; /// \brief This represents '#pragma omp parallel for' directive. /// /// \code /// #pragma omp parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for' has clauses 'private' /// with the variables 'a' and 'b' and 'reduction' with operator '+' and /// variables 'c' and 'd'. /// class OMPParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief true if current region has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForDirectiveClass, OMPD_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForDirectiveClass; } }; /// \brief This represents '#pragma omp parallel for simd' directive. /// /// \code /// #pragma omp parallel for simd private(a,b) linear(i,j:s) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel for simd' has clauses /// 'private' with the variables 'a' and 'b', 'linear' with variables 'i', 'j' /// and linear step 's', 'reduction' with operator '+' and variables 'c' and /// 'd'. /// class OMPParallelForSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPParallelForSimdDirectiveClass, OMPD_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelForSimdDirectiveClass; } }; /// \brief This represents '#pragma omp parallel sections' directive. /// /// \code /// #pragma omp parallel sections private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp parallel sections' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPParallelSectionsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief true if current directive has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPParallelSectionsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPParallelSectionsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPParallelSectionsDirectiveClass, OMPD_parallel_sections, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPParallelSectionsDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPParallelSectionsDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPParallelSectionsDirectiveClass; } }; /// \brief This represents '#pragma omp task' directive. /// /// \code /// #pragma omp task private(a,b) final(d) /// \endcode /// In this example directive '#pragma omp task' has clauses 'private' with the /// variables 'a' and 'b' and 'final' with condition 'd'. /// class OMPTaskDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief true if this directive has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTaskDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, StartLoc, EndLoc, NumClauses, 1), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTaskDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTaskDirectiveClass, OMPD_task, SourceLocation(), SourceLocation(), NumClauses, 1), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param HasCancel true, if current directive has inner cancel directive. /// static OMPTaskDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, bool HasCancel); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTaskDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskDirectiveClass; } }; /// \brief This represents '#pragma omp taskyield' directive. /// /// \code /// #pragma omp taskyield /// \endcode /// class OMPTaskyieldDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, StartLoc, EndLoc, 0, 0) {} /// \brief Build an empty directive. /// explicit OMPTaskyieldDirective() : OMPExecutableDirective(this, OMPTaskyieldDirectiveClass, OMPD_taskyield, SourceLocation(), SourceLocation(), 0, 0) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskyieldDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPTaskyieldDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskyieldDirectiveClass; } }; /// \brief This represents '#pragma omp barrier' directive. /// /// \code /// #pragma omp barrier /// \endcode /// class OMPBarrierDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, StartLoc, EndLoc, 0, 0) {} /// \brief Build an empty directive. /// explicit OMPBarrierDirective() : OMPExecutableDirective(this, OMPBarrierDirectiveClass, OMPD_barrier, SourceLocation(), SourceLocation(), 0, 0) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPBarrierDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPBarrierDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPBarrierDirectiveClass; } }; /// \brief This represents '#pragma omp taskwait' directive. /// /// \code /// #pragma omp taskwait /// \endcode /// class OMPTaskwaitDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, StartLoc, EndLoc, 0, 0) {} /// \brief Build an empty directive. /// explicit OMPTaskwaitDirective() : OMPExecutableDirective(this, OMPTaskwaitDirectiveClass, OMPD_taskwait, SourceLocation(), SourceLocation(), 0, 0) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPTaskwaitDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPTaskwaitDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskwaitDirectiveClass; } }; /// \brief This represents '#pragma omp taskgroup' directive. /// /// \code /// #pragma omp taskgroup /// \endcode /// class OMPTaskgroupDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPTaskgroupDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, StartLoc, EndLoc, 0, 1) {} /// \brief Build an empty directive. /// explicit OMPTaskgroupDirective() : OMPExecutableDirective(this, OMPTaskgroupDirectiveClass, OMPD_taskgroup, SourceLocation(), SourceLocation(), 0, 1) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTaskgroupDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AssociatedStmt); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPTaskgroupDirective *CreateEmpty(const ASTContext &C, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskgroupDirectiveClass; } }; /// \brief This represents '#pragma omp flush' directive. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has 2 arguments- variables 'a' /// and 'b'. /// 'omp flush' directive does not have clauses but have an optional list of /// variables to flush. This list of variables is stored within some fake clause /// FlushClause. class OMPFlushDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPFlushDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, StartLoc, EndLoc, NumClauses, 0) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPFlushDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPFlushDirectiveClass, OMPD_flush, SourceLocation(), SourceLocation(), NumClauses, 0) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses (only single OMPFlushClause clause is /// allowed). /// static OMPFlushDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPFlushDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPFlushDirectiveClass; } }; /// \brief This represents '#pragma omp ordered' directive. /// /// \code /// #pragma omp ordered /// \endcode /// class OMPOrderedDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPOrderedDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, StartLoc, EndLoc, NumClauses, 1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPOrderedDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPOrderedDirectiveClass, OMPD_ordered, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPOrderedDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPOrderedDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPOrderedDirectiveClass; } }; /// \brief This represents '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has clause 'capture'. /// class OMPAtomicDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// x = x binop expr; /// x = expr binop x; /// \endcode /// This field is true for the first form of the expression and false for the /// second. Required for correct codegen of non-associative operations (like /// << or >>). bool IsXLHSInRHSPart; /// \brief Used for 'atomic update' or 'atomic capture' constructs. They may /// have atomic expressions of forms /// \code /// v = x; <update x>; /// <update x>; v = x; /// \endcode /// This field is true for the first(postfix) form of the expression and false /// otherwise. bool IsPostfixUpdate; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPAtomicDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, StartLoc, EndLoc, NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPAtomicDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPAtomicDirectiveClass, OMPD_atomic, SourceLocation(), SourceLocation(), NumClauses, 5), IsXLHSInRHSPart(false), IsPostfixUpdate(false) {} /// \brief Set 'x' part of the associated expression/statement. void setX(Expr *X) { *std::next(child_begin()) = X; } /// \brief Set helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. void setUpdateExpr(Expr *UE) { *std::next(child_begin(), 2) = UE; } /// \brief Set 'v' part of the associated expression/statement. void setV(Expr *V) { *std::next(child_begin(), 3) = V; } /// \brief Set 'expr' part of the associated expression/statement. void setExpr(Expr *E) { *std::next(child_begin(), 4) = E; } public: /// \brief Creates directive with a list of \a Clauses and 'x', 'v' and 'expr' /// parts of the atomic construct (see Section 2.12.6, atomic Construct, for /// detailed description of 'x', 'v' and 'expr'). /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param X 'x' part of the associated expression/statement. /// \param V 'v' part of the associated expression/statement. /// \param E 'expr' part of the associated expression/statement. /// \param UE Helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. /// \param IsXLHSInRHSPart true if \a UE has the first form and false if the /// second. /// \param IsPostfixUpdate true if original value of 'x' must be stored in /// 'v', not an updated one. static OMPAtomicDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, Expr *X, Expr *V, Expr *E, Expr *UE, bool IsXLHSInRHSPart, bool IsPostfixUpdate); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPAtomicDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Get 'x' part of the associated expression/statement. Expr *getX() { return cast_or_null<Expr>(*std::next(child_begin())); } const Expr *getX() const { return cast_or_null<Expr>(*std::next(child_begin())); } /// \brief Get helper expression of the form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. Expr *getUpdateExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } const Expr *getUpdateExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 2)); } /// \brief Return true if helper update expression has form /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' and false if it has form /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } /// \brief Return true if 'v' expression must be updated to original value of /// 'x', false if 'v' must be updated to the new value of 'x'. bool isPostfixUpdate() const { return IsPostfixUpdate; } /// \brief Get 'v' part of the associated expression/statement. Expr *getV() { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } const Expr *getV() const { return cast_or_null<Expr>(*std::next(child_begin(), 3)); } /// \brief Get 'expr' part of the associated expression/statement. Expr *getExpr() { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } const Expr *getExpr() const { return cast_or_null<Expr>(*std::next(child_begin(), 4)); } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPAtomicDirectiveClass; } }; /// \brief This represents '#pragma omp target' directive. /// /// \code /// #pragma omp target if(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'if' with /// condition 'a'. /// class OMPTargetDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, StartLoc, EndLoc, NumClauses, 1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDirectiveClass, OMPD_target, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDirectiveClass; } }; /// \brief This represents '#pragma omp target data' directive. /// /// \code /// #pragma omp target data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target data' has clauses 'device' /// with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, StartLoc, EndLoc, NumClauses, 1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetDataDirectiveClass, OMPD_target_data, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetDataDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetDataDirectiveClass; } }; /// \brief This represents '#pragma omp target enter data' directive. /// /// \code /// #pragma omp target enter data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target enter data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetEnterDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetEnterDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/0) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetEnterDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetEnterDataDirectiveClass, OMPD_target_enter_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/0) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPTargetEnterDataDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// \brief Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetEnterDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetEnterDataDirectiveClass; } }; /// \brief This represents '#pragma omp target exit data' directive. /// /// \code /// #pragma omp target exit data device(0) if(a) map(b[:]) /// \endcode /// In this example directive '#pragma omp target exit data' has clauses /// 'device' with the value '0', 'if' with condition 'a' and 'map' with array /// section 'b[:]'. /// class OMPTargetExitDataDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetExitDataDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, StartLoc, EndLoc, NumClauses, /*NumChildren=*/0) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetExitDataDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetExitDataDirectiveClass, OMPD_target_exit_data, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/0) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPTargetExitDataDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// \brief Creates an empty directive with the place for \a N clauses. /// /// \param C AST context. /// \param N The number of clauses. /// static OMPTargetExitDataDirective *CreateEmpty(const ASTContext &C, unsigned N, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetExitDataDirectiveClass; } }; /// \brief This represents '#pragma omp target parallel' directive. /// /// \code /// #pragma omp target parallel if(a) /// \endcode /// In this example directive '#pragma omp target parallel' has clause 'if' with /// condition 'a'. /// class OMPTargetParallelDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetParallelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, StartLoc, EndLoc, NumClauses, /*NumChildren=*/1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetParallelDirectiveClass, OMPD_target_parallel, SourceLocation(), SourceLocation(), NumClauses, /*NumChildren=*/1) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetParallelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetParallelDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelDirectiveClass; } }; /// \brief This represents '#pragma omp target parallel for' directive. /// /// \code /// #pragma omp target parallel for private(a,b) reduction(+:c,d) /// \endcode /// In this example directive '#pragma omp target parallel for' has clauses /// 'private' with the variables 'a' and 'b' and 'reduction' with operator '+' /// and variables 'c' and 'd'. /// class OMPTargetParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief true if current region has inner cancel directive. bool HasCancel; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForDirectiveClass, OMPD_target_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses), HasCancel(false) {} /// \brief Set cancel state. void setHasCancel(bool Has) { HasCancel = Has; } public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// \param HasCancel true if current directive has inner cancel directive. /// static OMPTargetParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs, bool HasCancel); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); /// \brief Return true if current directive has inner cancel directive. bool hasCancel() const { return HasCancel; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForDirectiveClass; } }; /// \brief This represents '#pragma omp teams' directive. /// /// \code /// #pragma omp teams if(a) /// \endcode /// In this example directive '#pragma omp teams' has clause 'if' with /// condition 'a'. /// class OMPTeamsDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, StartLoc, EndLoc, NumClauses, 1) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTeamsDirectiveClass, OMPD_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDirectiveClass; } }; /// \brief This represents '#pragma omp cancellation point' directive. /// /// \code /// #pragma omp cancellation point for /// \endcode /// /// In this example a cancellation point is created for innermost 'for' region. class OMPCancellationPointDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// OMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc) : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, StartLoc, EndLoc, 0, 0), CancelRegion(OMPD_unknown) {} /// \brief Build an empty directive. /// explicit OMPCancellationPointDirective() : OMPExecutableDirective(this, OMPCancellationPointDirectiveClass, OMPD_cancellation_point, SourceLocation(), SourceLocation(), 0, 0), CancelRegion(OMPD_unknown) {} /// \brief Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// static OMPCancellationPointDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// \brief Creates an empty directive. /// /// \param C AST context. /// static OMPCancellationPointDirective *CreateEmpty(const ASTContext &C, EmptyShell); /// \brief Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancellationPointDirectiveClass; } }; /// \brief This represents '#pragma omp cancel' directive. /// /// \code /// #pragma omp cancel for /// \endcode /// /// In this example a cancel is created for innermost 'for' region. class OMPCancelDirective : public OMPExecutableDirective { friend class ASTStmtReader; OpenMPDirectiveKind CancelRegion; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPCancelDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, StartLoc, EndLoc, NumClauses, 0), CancelRegion(OMPD_unknown) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. explicit OMPCancelDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPCancelDirectiveClass, OMPD_cancel, SourceLocation(), SourceLocation(), NumClauses, 0), CancelRegion(OMPD_unknown) {} /// \brief Set cancel region for current cancellation point. /// \param CR Cancellation region. void setCancelRegion(OpenMPDirectiveKind CR) { CancelRegion = CR; } public: /// \brief Creates directive. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPCancelDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, OpenMPDirectiveKind CancelRegion); /// \brief Creates an empty directive. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPCancelDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); /// \brief Get cancellation region for the current cancellation point. OpenMPDirectiveKind getCancelRegion() const { return CancelRegion; } static bool classof(const Stmt *T) { return T->getStmtClass() == OMPCancelDirectiveClass; } }; /// \brief This represents '#pragma omp taskloop' directive. /// /// \code /// #pragma omp taskloop private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopDirectiveClass, OMPD_taskloop, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopDirectiveClass; } }; /// \brief This represents '#pragma omp taskloop simd' directive. /// /// \code /// #pragma omp taskloop simd private(a,b) grainsize(val) num_tasks(num) /// \endcode /// In this example directive '#pragma omp taskloop simd' has clauses 'private' /// with the variables 'a' and 'b', 'grainsize' with expression 'val' and /// 'num_tasks' with expression 'num'. /// class OMPTaskLoopSimdDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTaskLoopSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTaskLoopSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTaskLoopSimdDirectiveClass, OMPD_taskloop_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTaskLoopSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTaskLoopSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTaskLoopSimdDirectiveClass; } }; /// \brief This represents '#pragma omp distribute' directive. /// /// \code /// #pragma omp distribute private(a,b) /// \endcode /// In this example directive '#pragma omp distribute' has clauses 'private' /// with the variables 'a' and 'b' /// class OMPDistributeDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeDirectiveClass, OMPD_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeDirectiveClass; } }; /// \brief This represents '#pragma omp target update' directive. /// /// \code /// #pragma omp target update to(a) from(b) device(1) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' with /// argument 'a', clause 'from' with argument 'b' and clause 'device' with /// argument '1'. /// class OMPTargetUpdateDirective : public OMPExecutableDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param NumClauses The number of clauses. /// OMPTargetUpdateDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, StartLoc, EndLoc, NumClauses, 0) {} /// \brief Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetUpdateDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetUpdateDirectiveClass, OMPD_target_update, SourceLocation(), SourceLocation(), NumClauses, 0) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// static OMPTargetUpdateDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses); /// \brief Creates an empty directive with the place for \a NumClauses /// clauses. /// /// \param C AST context. /// \param NumClauses The number of clauses. /// static OMPTargetUpdateDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetUpdateDirectiveClass; } }; /// \brief This represents '#pragma omp distribute parallel for' composite /// directive. /// /// \code /// #pragma omp distribute parallel for private(a,b) /// \endcode /// In this example directive '#pragma omp distribute parallel for' has clause /// 'private' with the variables 'a' and 'b' /// class OMPDistributeParallelForDirective : public OMPLoopDirective { friend class ASTStmtReader; /// \brief Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// \brief Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForDirectiveClass, OMPD_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// \brief Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// \brief Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp distribute parallel for simd' has /// clause 'private' with the variables 'x' /// class OMPDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeParallelForSimdDirectiveClass, OMPD_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeParallelForSimdDirective *Create( const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeParallelForSimdDirective *CreateEmpty( const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp distribute simd' composite directive. /// /// \code /// #pragma omp distribute simd private(x) /// \endcode /// In this example directive '#pragma omp distribute simd' has clause /// 'private' with the variables 'x' /// class OMPDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPDistributeSimdDirectiveClass, OMPD_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp target parallel for simd' directive. /// /// \code /// #pragma omp target parallel for simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target parallel for simd' has clauses /// 'private' with the variable 'a', 'map' with the variable 'b' and 'safelen' /// with the variable 'c'. /// class OMPTargetParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetParallelForSimdDirectiveClass, OMPD_target_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetParallelForSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp target simd' directive. /// /// \code /// #pragma omp target simd private(a) map(b) safelen(c) /// \endcode /// In this example directive '#pragma omp target simd' has clauses 'private' /// with the variable 'a', 'map' with the variable 'b' and 'safelen' with /// the variable 'c'. /// class OMPTargetSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetSimdDirectiveClass, OMPD_target_simd, SourceLocation(),SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute' directive. /// /// \code /// #pragma omp teams distribute private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute' has clauses /// 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeDirectiveClass, OMPD_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp teams distribute simd' /// combined directive. /// /// \code /// #pragma omp teams distribute simd private(a,b) /// \endcode /// In this example directive '#pragma omp teams distribute simd' /// has clause 'private' with the variables 'a' and 'b' /// class OMPTeamsDistributeSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeSimdDirectiveClass, OMPD_teams_distribute_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place /// for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeSimdDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for simd' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for simd' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForSimdDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForSimdDirectiveClass, OMPD_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForSimdDirectiveClass; } }; /// This represents '#pragma omp teams distribute parallel for' composite /// directive. /// /// \code /// #pragma omp teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp teams distribute parallel for' /// has clause 'private' with the variables 'x' /// class OMPTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTeamsDistributeParallelForDirectiveClass, OMPD_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams' directive. /// /// \code /// #pragma omp target teams if(a>0) /// \endcode /// In this example directive '#pragma omp target teams' has clause 'if' with /// condition 'a>0'. /// class OMPTargetTeamsDirective final : public OMPExecutableDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, StartLoc, EndLoc, NumClauses, 1) {} /// Build an empty directive. /// /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDirective(unsigned NumClauses) : OMPExecutableDirective(this, OMPTargetTeamsDirectiveClass, OMPD_target_teams, SourceLocation(), SourceLocation(), NumClauses, 1) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// static OMPTargetTeamsDirective *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDirective *CreateEmpty(const ASTContext &C, unsigned NumClauses, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDirectiveClass; } }; /// This represents '#pragma omp target teams distribute' combined directive. /// /// \code /// #pragma omp target teams distribute private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute' has clause /// 'private' with the variables 'x' /// class OMPTargetTeamsDistributeDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeDirectiveClass, OMPD_target_teams_distribute, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for' combined /// directive. /// /// \code /// #pragma omp target teams distribute parallel for private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForDirective(unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForDirectiveClass, OMPD_target_teams_distribute_parallel_for, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeParallelForDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForDirectiveClass; } }; /// This represents '#pragma omp target teams distribute parallel for simd' /// combined directive. /// /// \code /// #pragma omp target teams distribute parallel for simd private(x) /// \endcode /// In this example directive '#pragma omp target teams distribute parallel /// for simd' has clause 'private' with the variables 'x' /// class OMPTargetTeamsDistributeParallelForSimdDirective final : public OMPLoopDirective { friend class ASTStmtReader; /// Build directive with the given start and end location. /// /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending location of the directive. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// OMPTargetTeamsDistributeParallelForSimdDirective(SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective(this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, StartLoc, EndLoc, CollapsedNum, NumClauses) {} /// Build an empty directive. /// /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// explicit OMPTargetTeamsDistributeParallelForSimdDirective( unsigned CollapsedNum, unsigned NumClauses) : OMPLoopDirective( this, OMPTargetTeamsDistributeParallelForSimdDirectiveClass, OMPD_target_teams_distribute_parallel_for_simd, SourceLocation(), SourceLocation(), CollapsedNum, NumClauses) {} public: /// Creates directive with a list of \a Clauses. /// /// \param C AST context. /// \param StartLoc Starting location of the directive kind. /// \param EndLoc Ending Location of the directive. /// \param CollapsedNum Number of collapsed loops. /// \param Clauses List of clauses. /// \param AssociatedStmt Statement, associated with the directive. /// \param Exprs Helper expressions for CodeGen. /// static OMPTargetTeamsDistributeParallelForSimdDirective * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc, unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt, const HelperExprs &Exprs); /// Creates an empty directive with the place for \a NumClauses clauses. /// /// \param C AST context. /// \param CollapsedNum Number of collapsed nested loops. /// \param NumClauses Number of clauses. /// static OMPTargetTeamsDistributeParallelForSimdDirective * CreateEmpty(const ASTContext &C, unsigned NumClauses, unsigned CollapsedNum, EmptyShell); static bool classof(const Stmt *T) { return T->getStmtClass() == OMPTargetTeamsDistributeParallelForSimdDirectiveClass; } }; } // end namespace clang #endif
seqramp.c
#include<Python.h> #include<numpy/arrayobject.h> #include<math.h> #include<omp.h> #define IND(a,i) *((double *)(a->data+i*a->strides[0])) static PyObject *seqramp(PyObject *self, PyObject *args, PyObject *keywds); static PyObject *seqramp(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *etc; PyArrayObject *x,*y, *rampparams; double goal,r0,r1,r2,r3,x0,pm; int i; npy_intp dims[1]; // etc = PyList_New(0); static char *kwlist[] = {"rampparams","x","etc",NULL}; if(!PyArg_ParseTupleAndKeywords(args,keywds,"OO|O",kwlist,&rampparams,&x,&etc)) { return NULL; } goal = IND(rampparams,0); r0 = IND(rampparams,1); r1 = IND(rampparams,2); r2 = IND(rampparams,3); r3 = IND(rampparams,4); x0 = IND(rampparams,5); pm = IND(rampparams,6); dims[0] = x->dimensions[0]; y = (PyArrayObject *) PyArray_SimpleNew(1,dims,PyArray_DOUBLE); #pragma omp parallel for for(i=0;i<dims[0];i++) { IND(y,i) = goal + pm*exp(-r0*IND(x,i)+r1) + r2*(IND(x,i)-x0) + r3*pow((IND(x,i)-x0),2); } return PyArray_Return(y); } static char module_docstring[]="\ This function NEEDS A DOC_STRING.\n\ \n\ Parameters\n\ ----------\n\ \n\ Returns\n\ -------\n\ \n\ Revisions\n\ ---------\n\ 2010-07-30 Kevin Stevenson, UCF \n\ kevin218@knights.ucf.edu\n\ Original version\n\n\ 2010-12-24 Nate Lust, UCF\n\ natelust at linux dot com\n\ Converted to C\n\n\ 2018-11-22 Jonathan Fraine, SSI\n\ jfraine at spacescience.org\n\ Updated c extensions to python3, with support for python2.7\n\n\ "; static PyMethodDef module_methods[] = { {"seqramp",(PyCFunction)seqramp,METH_VARARGS|METH_KEYWORDS,module_docstring},{NULL}}; PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_seqramp(void) #else initseqramp(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "seqramp", /* m_name */ module_docstring, /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); if (!module) return NULL; /* Load `numpy` functionality. */ import_array(); return module; #else PyObject *m = Py_InitModule3("seqramp", module_methods, module_docstring); if (m == NULL) return; /* Load `numpy` functionality. */ import_array(); #endif }
feature.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/feature.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register Quantum *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (Quantum *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MagickPathExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); /* Filter out noise. */ (void) FormatLocaleString(geometry,MagickPathExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImage(image,ConvolveMorphology,1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace,exception) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,OffAlphaChannel,exception); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const Quantum *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p+=GetPixelChannels(edge_image); } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } *q=0; q+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const Quantum *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif proceed=SetImageProgress(image,CannyEdgeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageFeatures(image,1,exception); % contrast=channel_features[RedPixelChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageFeatures method is: % % ChannelFeatures *GetImageFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { PixelInfo direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; PixelPacket gray, *grays; MagickBooleanType status; register ssize_t i, r; size_t length; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=MaxPixelChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (PixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].alpha=(~0U); grays[i].black=(~0U); } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,r,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(image,p))].red= ScaleQuantumToMap(GetPixelRed(image,p)); grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green= ScaleQuantumToMap(GetPixelGreen(image,p)); grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue= ScaleQuantumToMap(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black= ScaleQuantumToMap(GetPixelBlack(image,p)); if (image->alpha_trait != UndefinedPixelTrait) grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha= ScaleQuantumToMap(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].black != ~0U) grays[gray.black++].black=grays[i].black; if (image->alpha_trait != UndefinedPixelTrait) if (grays[i].alpha != ~0U) grays[gray.alpha++].alpha=grays[i].alpha; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.black > number_grays) number_grays=gray.black; if (image->alpha_trait != UndefinedPixelTrait) if (gray.alpha > number_grays) number_grays=gray.alpha; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; ssize_t offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,r,image->columns+ 2*distance,distance+2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } p+=distance*GetPixelChannels(image);; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p))) u++; while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p))) u++; while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].black++; cooccurrence[v][u].direction[i].black++; } if (image->alpha_trait != UndefinedPixelTrait) { u=0; v=0; while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p))) u++; while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].alpha++; cooccurrence[v][u].direction[i].alpha++; } } p+=GetPixelChannels(image); } } grays=(PixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].black*=normalize; if (image->alpha_trait != UndefinedPixelTrait) cooccurrence[x][y].direction[i].alpha*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BluePixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].black* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].alpha* cooccurrence[x][y].direction[i].alpha; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].black+=x*y* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) correlation.direction[i].alpha+=x*y* cooccurrence[x][y].direction[i].alpha; /* Inverse Difference Moment. */ channel_features[RedPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BluePixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[y+x+2].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Entropy. */ channel_features[RedPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BluePixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].alpha* MagickLog10(cooccurrence[x][y].direction[i].alpha); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->alpha_trait != UndefinedPixelTrait) density_x[x].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].black+= cooccurrence[x][y].direction[i].black; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_y[y].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].black+=y*sum[y].direction[i].black; sum_squares.direction[i].black+=y*y*sum[y].direction[i].black; } if (image->alpha_trait != UndefinedPixelTrait) { mean.direction[i].alpha+=y*sum[y].direction[i].alpha; sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedPixelChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenPixelChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BluePixelChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].correlation[i]= (correlation.direction[i].black-mean.direction[i].black* mean.direction[i].black)/(sqrt(sum_squares.direction[i].black- (mean.direction[i].black*mean.direction[i].black))*sqrt( sum_squares.direction[i].black-(mean.direction[i].black* mean.direction[i].black))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].correlation[i]= (correlation.direction[i].alpha-mean.direction[i].alpha* mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha- (mean.direction[i].alpha*mean.direction[i].alpha))*sqrt( sum_squares.direction[i].alpha-(mean.direction[i].alpha* mean.direction[i].alpha))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].alpha; /* Sum entropy. */ channel_features[RedPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Sum variance. */ channel_features[RedPixelChannel].sum_variance[i]+= (x-channel_features[RedPixelChannel].sum_entropy[i])* (x-channel_features[RedPixelChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_variance[i]+= (x-channel_features[GreenPixelChannel].sum_entropy[i])* (x-channel_features[GreenPixelChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_variance[i]+= (x-channel_features[BluePixelChannel].sum_entropy[i])* (x-channel_features[BluePixelChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_variance[i]+= (x-channel_features[BlackPixelChannel].sum_entropy[i])* (x-channel_features[BlackPixelChannel].sum_entropy[i])* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_variance[i]+= (x-channel_features[AlphaPixelChannel].sum_entropy[i])* (x-channel_features[AlphaPixelChannel].sum_entropy[i])* density_xy[x].direction[i].alpha; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=(y-mean.direction[i].black+1)* (y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)* (y-mean.direction[i].alpha+1)* cooccurrence[x][y].direction[i].alpha; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy.direction[i].alpha-= cooccurrence[x][y].direction[i].alpha*MagickLog10( cooccurrence[x][y].direction[i].alpha); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].black-=( cooccurrence[x][y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy1.direction[i].alpha-=( cooccurrence[x][y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].black-=(density_x[x].direction[i].black* density_y[y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha* density_y[y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); } } channel_features[RedPixelChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenPixelChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BluePixelChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].variance_sum_of_squares[i]= variance.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].variance_sum_of_squares[i]= variance.direction[i].alpha; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=density_xy[x].direction[i].alpha; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].black+=density_xy[x].direction[i].black* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha* density_xy[x].direction[i].alpha; /* Difference entropy. */ channel_features[RedPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].black-=(density_x[x].direction[i].black* MagickLog10(density_x[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha* MagickLog10(density_x[x].direction[i].alpha)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].black-=(density_y[x].direction[i].black* MagickLog10(density_y[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha* MagickLog10(density_y[x].direction[i].alpha)); } /* Difference variance. */ channel_features[RedPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BluePixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].black)- (variance.direction[i].black*variance.direction[i].black))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].alpha)- (variance.direction[i].alpha*variance.direction[i].alpha))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BluePixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/ (entropy_x.direction[i].black > entropy_y.direction[i].black ? entropy_x.direction[i].black : entropy_y.direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/ (entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ? entropy_x.direction[i].alpha : entropy_y.direction[i].alpha); channel_features[RedPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BluePixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].black- entropy_xy.direction[i].black))))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].alpha- entropy_xy.direction[i].alpha))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) pixel.direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } /* Maximum Correlation Coefficient. */ Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/ density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black* cooccurrence[y][x].direction[i].black/ density_x[z].direction[i].black/density_y[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) Q[z][y].direction[i].alpha+= cooccurrence[z][x].direction[i].alpha* cooccurrence[y][x].direction[i].alpha/ density_x[z].direction[i].alpha/ density_y[x].direction[i].alpha; } } channel_features[RedPixelChannel].contrast[i]+=z*z* pixel.direction[i].red; channel_features[GreenPixelChannel].contrast[i]+=z*z* pixel.direction[i].green; channel_features[BluePixelChannel].contrast[i]+=z*z* pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].contrast[i]+=z*z* pixel.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].contrast[i]+=z*z* pixel.direction[i].alpha; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BluePixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator matrix % of angle vs distance. The size of the accumulator is 180x(diagonal/2). Next % it searches this space for peaks in counts and converts the locations of the % peaks to slope and intercept in the normal x,y input image space. Use the % slope/intercepts to find the endpoints clipped to the bounds of the image. The % lines are then drawn. The counts are a measure of the length of the lines % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->resolution.x == 0.0 ? 1.0 : image->resolution.x/ DefaultResolution; draw_info->affine.sy=image->resolution.y == 0.0 ? 1.0 : image->resolution.y/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MagickPathExtent], path[MagickPathExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif proceed=SetImageProgress(image,CannyEdgeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MagickPathExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "viewbox 0 0 %.20g %.20g\n",(double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MagickPathExtent, "line %g,%g %g,%g # %g\n",line.x1,line.y1,line.x2,line.y2,maxima); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MagickPathExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsStringTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); mean_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_MeanShiftImage) #endif proceed=SetImageProgress(image,MeanShiftImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
network.c
#include <stdio.h> #include <time.h> #include <assert.h> #include "network.h" #include "image.h" #include "data.h" #include "utils.h" #include "blas.h" #include "crop_layer.h" #include "connected_layer.h" #include "gru_layer.h" #include "rnn_layer.h" #include "crnn_layer.h" #include "local_layer.h" #include "convolutional_layer.h" #include "activation_layer.h" #include "detection_layer.h" #include "region_layer.h" #include "yolo_layer.h" #include "normalization_layer.h" #include "batchnorm_layer.h" #include "maxpool_layer.h" #include "reorg_layer.h" #include "avgpool_layer.h" #include "cost_layer.h" #include "softmax_layer.h" #include "dropout_layer.h" #include "route_layer.h" #include "upsample_layer.h" #include "shortcut_layer.h" #include "parser.h" #include "data.h" #include <unistd.h> load_args get_base_args(network *net) { load_args args = { 0 }; args.w = net->w; args.h = net->h; args.size = net->w; args.min = net->min_crop; args.max = net->max_crop; args.angle = net->angle; args.aspect = net->aspect; args.exposure = net->exposure; args.center = net->center; args.saturation = net->saturation; args.hue = net->hue; return args; } network *load_network(char *cfg, char *weights, int clear) { network *net = parse_network_cfg(cfg); if (weights && weights[0] != 0) { load_weights(net, weights); } if (clear) (*net->seen) = 0; return net; } size_t get_current_batch(network *net) { size_t batch_num = (*net->seen) / (net->batch * net->subdivisions); return batch_num; } void reset_network_state(network *net, int b) { int i; for (i = 0; i < net->n; ++i) { #ifdef GPU layer l = net->layers[i]; if (l.state_gpu) { fill_gpu(l.outputs, 0, l.state_gpu + l.outputs * b, 1, net->st); } if (l.h_gpu) { fill_gpu(l.outputs, 0, l.h_gpu + l.outputs * b, 1, net->st); } #endif } } void reset_rnn(network *net) { reset_network_state(net, 0); } real_t get_current_rate(network *net) { size_t batch_num = get_current_batch(net); int i; real_t rate; if (batch_num < net->burn_in) return net->learning_rate * pow((real_t) batch_num / net->burn_in, net->power); switch (net->policy) { case CONSTANT: return net->learning_rate; case STEP: return net->learning_rate * pow(net->scale, batch_num / net->step); case STEPS: rate = net->learning_rate; for (i = 0; i < net->num_steps; ++i) { if (net->steps[i] > batch_num) return rate; rate *= net->scales[i]; } return rate; case EXP: return net->learning_rate * pow(net->gamma, batch_num); case POLY: return net->learning_rate * pow(1 - (real_t) batch_num / net->max_batches, net->power); case RANDOM: return net->learning_rate * pow(rand_uniform(0, 1), net->power); case SIG: return net->learning_rate * (1. / (1. + exp(net->gamma * (batch_num - net->step)))); default: fprintf(stderr, "Policy is weird!\n"); return net->learning_rate; } } char *get_layer_string(LAYER_TYPE a) { switch (a) { case CONVOLUTIONAL: return "convolutional"; case ACTIVE: return "activation"; case LOCAL: return "local"; case DECONVOLUTIONAL: return "deconvolutional"; case CONNECTED: return "connected"; case RNN: return "rnn"; case GRU: return "gru"; case LSTM: return "lstm"; case CRNN: return "crnn"; case MAXPOOL: return "maxpool"; case REORG: return "reorg"; case AVGPOOL: return "avgpool"; case SOFTMAX: return "softmax"; case DETECTION: return "detection"; case REGION: return "region"; case YOLO: return "yolo"; case DROPOUT: return "dropout"; case CROP: return "crop"; case COST: return "cost"; case ROUTE: return "route"; case SHORTCUT: return "shortcut"; case NORMALIZATION: return "normalization"; case BATCHNORM: return "batchnorm"; default: break; } return "none"; } network *make_network(int n) { network *net = calloc(1, sizeof(network)); net->n = n; net->layers = calloc(net->n, sizeof(layer)); net->seen = calloc(1, sizeof(size_t)); net->t = calloc(1, sizeof(int)); net->cost = calloc(1, sizeof(real_t)); return net; } void forward_network(network *netp) { #ifdef GPU if (netp->gpu_index >= 0) { forward_network_gpu(netp); return; } #endif network net = *netp; int i; for (i = 0; i < net.n; ++i) { net.index = i; layer l = net.layers[i]; if (l.delta) { fill_cpu(l.outputs * l.batch, 0, l.delta, 1); } l.forward(l, net); net.input = l.output; if (l.truth) { net.truth = l.output; } } calc_network_cost(netp); } void update_network(network *netp) { #ifdef GPU if (netp->gpu_index >= 0) { update_network_gpu(netp); return; } #endif network net = *netp; int i; update_args a = { 0 }; a.batch = net.batch * net.subdivisions; a.learning_rate = get_current_rate(netp); a.momentum = net.momentum; a.decay = net.decay; a.adam = net.adam; a.B1 = net.B1; a.B2 = net.B2; a.eps = net.eps; ++*net.t; a.t = *net.t; for (i = 0; i < net.n; ++i) { layer l = net.layers[i]; if (l.update) { l.update(l, a); } } } void calc_network_cost(network *netp) { network net = *netp; int i; real_t sum = 0; int count = 0; for (i = 0; i < net.n; ++i) { if (net.layers[i].cost) { sum += net.layers[i].cost[0]; ++count; } } *net.cost = sum / count; } int get_predicted_class_network(network *net) { return max_index(net->output, net->outputs); } void backward_network(network *netp) { #ifdef GPU if (netp->gpu_index >= 0) { backward_network_gpu(netp); return; } #endif network net = *netp; int i; network orig = net; for (i = net.n - 1; i >= 0; --i) { layer l = net.layers[i]; if (l.stopbackward) break; if (i == 0) { net = orig; } else { layer prev = net.layers[i - 1]; net.input = prev.output; net.delta = prev.delta; } net.index = i; l.backward(l, net); } } real_t train_network_datum(network *net) { *net->seen += net->batch; net->train = 1; forward_network(net); backward_network(net); real_t error = *net->cost; if (((*net->seen) / net->batch) % net->subdivisions == 0) update_network(net); return error; } real_t train_network_sgd(network *net, data d, int n) { int batch = net->batch; int i; real_t sum = 0; for (i = 0; i < n; ++i) { get_random_batch(d, batch, net->input, net->truth); real_t err = train_network_datum(net); sum += err; } return (real_t) sum / (n * batch); } real_t train_network(network *net, data d) { assert(d.X.rows % net->batch == 0); int batch = net->batch; int n = d.X.rows / batch; int i; real_t sum = 0; for (i = 0; i < n; ++i) { get_next_batch(d, batch, i * batch, net->input, net->truth); real_t err = train_network_datum(net); sum += err; } return (real_t) sum / (n * batch); } void set_temp_network(network *net, real_t t) { int i; for (i = 0; i < net->n; ++i) { net->layers[i].temperature = t; } } void set_batch_network(network *net, int b) { net->batch = b; int i; for (i = 0; i < net->n; ++i) { net->layers[i].batch = b; #ifdef CUDNN if(net->layers[i].type == CONVOLUTIONAL) { cudnn_convolutional_setup(net->layers + i); } if(net->layers[i].type == DECONVOLUTIONAL) { layer *l = net->layers + i; cudnnSetTensor4dDescriptor(l->dstTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, l->out_c, l->out_h, l->out_w); cudnnSetTensor4dDescriptor(l->normTensorDesc, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, l->out_c, 1, 1); } #endif } } int resize_network(network *net, int w, int h) { #ifdef GPU cuda_set_device(net->gpu_index); cuda_free(net->workspace); #endif int i; //if(w == net->w && h == net->h) return 0; net->w = w; net->h = h; int inputs = 0; size_t workspace_size = 0; //fprintf(stderr, "Resizing to %d x %d...\n", w, h); //fflush(stderr); for (i = 0; i < net->n; ++i) { layer l = net->layers[i]; if (l.type == CONVOLUTIONAL) { resize_convolutional_layer(&l, w, h); } else if (l.type == CROP) { resize_crop_layer(&l, w, h); } else if (l.type == MAXPOOL) { resize_maxpool_layer(&l, w, h); } else if (l.type == REGION) { resize_region_layer(&l, w, h); } else if (l.type == YOLO) { resize_yolo_layer(&l, w, h); } else if (l.type == ROUTE) { resize_route_layer(&l, net); } else if (l.type == SHORTCUT) { resize_shortcut_layer(&l, w, h); } else if (l.type == UPSAMPLE) { resize_upsample_layer(&l, w, h); } else if (l.type == REORG) { resize_reorg_layer(&l, w, h); } else if (l.type == AVGPOOL) { resize_avgpool_layer(&l, w, h); } else if (l.type == NORMALIZATION) { resize_normalization_layer(&l, w, h); } else if (l.type == COST) { resize_cost_layer(&l, inputs); } else { error("Cannot resize this type of layer"); } if (l.workspace_size > workspace_size) workspace_size = l.workspace_size; if (l.workspace_size > 2000000000) assert(0); inputs = l.outputs; net->layers[i] = l; w = l.out_w; h = l.out_h; if (l.type == AVGPOOL) break; } layer out = get_network_output_layer(net); net->inputs = net->layers[0].inputs; net->outputs = out.outputs; net->truths = out.outputs; if (net->layers[net->n - 1].truths) net->truths = net->layers[net->n - 1].truths; net->output = out.output; free(net->input); free(net->truth); net->input = calloc(net->inputs * net->batch, sizeof(real_t)); net->truth = calloc(net->truths * net->batch, sizeof(real_t)); #ifdef GPU if (gpu_index >= 0) { cuda_free(net->input_gpu); cuda_free(net->truth_gpu); net->input_gpu = cuda_make_array(net->input, net->inputs * net->batch); net->truth_gpu = cuda_make_array(net->truth, net->truths * net->batch); if (workspace_size) { net->workspace = cuda_make_array(0, (workspace_size - 1) / sizeof(real_t) + 1); } } else { free(net->workspace); net->workspace = calloc(1, workspace_size); } #else free(net->workspace); net->workspace = calloc(1, workspace_size); #endif //fprintf(stderr, " Done!\n"); return 0; } layer get_network_detection_layer(network *net) { int i; for (i = 0; i < net->n; ++i) { if (net->layers[i].type == DETECTION) { return net->layers[i]; } } fprintf(stderr, "Detection layer not found!!\n"); layer l = { 0 }; return l; } image get_network_image_layer(network *net, int i) { layer l = net->layers[i]; #ifdef GPU //cuda_pull_array(l.output_gpu, l.output, l.outputs); #endif if (l.out_w && l.out_h && l.out_c) { return real_t_to_image(l.out_w, l.out_h, l.out_c, l.output); } image def = { 0 }; return def; } image get_network_image(network *net) { int i; for (i = net->n - 1; i >= 0; --i) { image m = get_network_image_layer(net, i); if (m.h != 0) return m; } image def = { 0 }; return def; } void visualize_network(network *net) { image *prev = 0; int i; char buff[256]; for (i = 0; i < net->n; ++i) { sprintf(buff, "Layer %d", i); layer l = net->layers[i]; if (l.type == CONVOLUTIONAL) { prev = visualize_convolutional_layer(l, buff, prev); } } } void top_predictions(network *net, int k, int *index) { top_k(net->output, net->outputs, k, index); } real_t *network_predict(network *net, real_t *input) { network orig = *net; net->input = input; net->truth = 0; net->train = 0; net->delta = 0; forward_network(net); real_t *out = net->output; *net = orig; return out; } void network_predict_smx_red(network **net, real_t **input) { int i; int smx_red = net[0]->smx_redundancy; network *orig_array = malloc(sizeof(network) * smx_red); if(orig_array == NULL){ printf("Error while creating redundancy on network predict %d %s\n", __LINE__, __FILE__); exit(1); } for (i = 0; i < smx_red; i++) { orig_array[i] = *net[i]; net[i]->input = input[i]; net[i]->truth = 0; net[i]->train = 0; net[i]->delta = 0; } #ifdef GPU forward_network_gpu_parallel(net); #else #pragma omp parallel for for(int i = 0; i < smx_red; i++){ forward_network(net[i]); } #endif for (i = 0; i < smx_red; i++) { // out[i] = net[i]->output; *(net[i]) = orig_array[i]; } free(orig_array); // return out; } int num_detections(network *net, real_t thresh) { int i; int s = 0; for (i = 0; i < net->n; ++i) { layer l = net->layers[i]; if (l.type == YOLO) { s += yolo_num_detections(l, thresh); } if (l.type == DETECTION || l.type == REGION) { s += l.w * l.h * l.n; } } return s; } detection *make_network_boxes(network *net, real_t thresh, int *num) { layer l = net->layers[net->n - 1]; int i; int nboxes = num_detections(net, thresh); if (num) *num = nboxes; detection *dets = calloc(nboxes, sizeof(detection)); for (i = 0; i < nboxes; ++i) { dets[i].prob = calloc(l.classes, sizeof(real_t)); if (l.coords > 4) { dets[i].mask = calloc(l.coords - 4, sizeof(real_t)); } } return dets; } void fill_network_boxes(network *net, int w, int h, real_t thresh, real_t hier, int *map, int relative, detection *dets) { int j; for (j = 0; j < net->n; ++j) { layer l = net->layers[j]; if (l.type == YOLO) { int count = get_yolo_detections(l, w, h, net->w, net->h, thresh, map, relative, dets); dets += count; } if (l.type == REGION) { get_region_detections(l, w, h, net->w, net->h, thresh, map, hier, relative, dets); dets += l.w * l.h * l.n; } if (l.type == DETECTION) { get_detection_detections(l, w, h, thresh, dets); dets += l.w * l.h * l.n; } } } detection *get_network_boxes(network *net, int w, int h, real_t thresh, real_t hier, int *map, int relative, int *num) { detection *dets = make_network_boxes(net, thresh, num); fill_network_boxes(net, w, h, thresh, hier, map, relative, dets); return dets; } void free_detections(detection *dets, int n) { int i; for (i = 0; i < n; ++i) { free(dets[i].prob); if (dets[i].mask) free(dets[i].mask); } free(dets); } real_t *network_predict_image(network *net, image im) { image imr = letterbox_image(im, net->w, net->h); set_batch_network(net, 1); real_t *p = network_predict(net, imr.data); free_image(imr); return p; } int network_width(network *net) { return net->w; } int network_height(network *net) { return net->h; } matrix network_predict_data_multi(network *net, data test, int n) { int i, j, b, m; int k = net->outputs; matrix pred = make_matrix(test.X.rows, k); real_t *X = calloc(net->batch * test.X.rows, sizeof(real_t)); for (i = 0; i < test.X.rows; i += net->batch) { for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; memcpy(X + b * test.X.cols, test.X.vals[i + b], test.X.cols * sizeof(real_t)); } for (m = 0; m < n; ++m) { real_t *out = network_predict(net, X); for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; for (j = 0; j < k; ++j) { pred.vals[i + b][j] += out[j + b * k] / n; } } } } free(X); return pred; } matrix network_predict_data(network *net, data test) { int i, j, b; int k = net->outputs; matrix pred = make_matrix(test.X.rows, k); real_t *X = calloc(net->batch * test.X.cols, sizeof(real_t)); for (i = 0; i < test.X.rows; i += net->batch) { for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; memcpy(X + b * test.X.cols, test.X.vals[i + b], test.X.cols * sizeof(real_t)); } real_t *out = network_predict(net, X); for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; for (j = 0; j < k; ++j) { pred.vals[i + b][j] = out[j + b * k]; } } } free(X); return pred; } void print_network(network *net) { int i, j; for (i = 0; i < net->n; ++i) { layer l = net->layers[i]; real_t *output = l.output; int n = l.outputs; real_t mean = mean_array(output, n); real_t vari = variance_array(output, n); fprintf(stderr, "Layer %d - Mean: %f, Variance: %f\n", i, mean, vari); if (n > 100) n = 100; for (j = 0; j < n; ++j) fprintf(stderr, "%f, ", output[j]); if (n == 100) fprintf(stderr, ".....\n"); fprintf(stderr, "\n"); } } void compare_networks(network *n1, network *n2, data test) { matrix g1 = network_predict_data(n1, test); matrix g2 = network_predict_data(n2, test); int i; int a, b, c, d; a = b = c = d = 0; for (i = 0; i < g1.rows; ++i) { int truth = max_index(test.y.vals[i], test.y.cols); int p1 = max_index(g1.vals[i], g1.cols); int p2 = max_index(g2.vals[i], g2.cols); if (p1 == truth) { if (p2 == truth) ++d; else ++c; } else { if (p2 == truth) ++b; else ++a; } } printf("%5d %5d\n%5d %5d\n", a, b, c, d); real_t num = pow((abs(b - c) - 1.), 2.); real_t den = b + c; printf("%f\n", num / den); } real_t network_accuracy(network *net, data d) { matrix guess = network_predict_data(net, d); real_t acc = matrix_topk_accuracy(d.y, guess, 1); free_matrix(guess); return acc; } real_t *network_accuracies(network *net, data d, int n) { static real_t acc[2]; matrix guess = network_predict_data(net, d); acc[0] = matrix_topk_accuracy(d.y, guess, 1); acc[1] = matrix_topk_accuracy(d.y, guess, n); free_matrix(guess); return acc; } layer get_network_output_layer(network *net) { int i; for (i = net->n - 1; i >= 0; --i) { if (net->layers[i].type != COST) break; } return net->layers[i]; } real_t network_accuracy_multi(network *net, data d, int n) { matrix guess = network_predict_data_multi(net, d, n); real_t acc = matrix_topk_accuracy(d.y, guess, 1); free_matrix(guess); return acc; } void free_network(network *net) { int i; for (i = 0; i < net->n; ++i) { free_layer(net->layers[i]); } free(net->layers); if (net->input) free(net->input); if (net->truth) free(net->truth); #ifdef GPU if (net->input_gpu) cuda_free(net->input_gpu); if (net->truth_gpu) cuda_free(net->truth_gpu); #endif free(net); } // Some day... // ^ What the hell is this comment for? layer network_output_layer(network *net) { int i; for (i = net->n - 1; i >= 0; --i) { if (net->layers[i].type != COST) break; } return net->layers[i]; } int network_inputs(network *net) { return net->layers[0].inputs; } int network_outputs(network *net) { return network_output_layer(net).outputs; } real_t *network_output(network *net) { return network_output_layer(net).output; } #ifdef GPU void forward_network_gpu(network *netp) { network net = *netp; cuda_set_device(net.gpu_index); cuda_push_array(net.input_gpu, net.input, net.inputs * net.batch); if (net.truth) { cuda_push_array(net.truth_gpu, net.truth, net.truths * net.batch); } int i; for (i = 0; i < net.n; ++i) { // printf("passou aqui layer %d\n", i); net.index = i; layer l = net.layers[i]; if (l.delta_gpu) { fill_gpu(l.outputs * l.batch, 0, l.delta_gpu, 1, netp->st); } l.forward_gpu(l, net); net.input_gpu = l.output_gpu; net.input = l.output; if (l.truth) { net.truth_gpu = l.output_gpu; net.truth = l.output; } } pull_network_output(netp); calc_network_cost(netp); } void* forward_network_gpu_caller(void *netp) { forward_network_gpu((network*) netp); return NULL; } void forward_network_gpu_parallel(network **netp_array) { int mr = netp_array[0]->smx_redundancy; pthread_t *threads = (pthread_t*) malloc(sizeof(pthread_t) * mr); int i; for (i = 0; i < mr; i++) { if (pthread_create(&threads[i], NULL, forward_network_gpu_caller, netp_array[i])) { error("ERROR ON CREATING THREADs\n"); } } cudaDeviceSynchronize(); for (i = 0; i < mr; i++) { if (pthread_join(threads[i], NULL)) { error("ERROR ON FINISHING THREADs\n"); } } // printf("APSSKKKKKdddd %d\n", mr); free(threads); // printf("APSSKKKKKdddd dddddddddsfasdadfasddf%d\n", mr); } void backward_network_gpu(network *netp) { int i; network net = *netp; network orig = net; cuda_set_device(net.gpu_index); for (i = net.n - 1; i >= 0; --i) { layer l = net.layers[i]; if (l.stopbackward) break; if (i == 0) { net = orig; } else { layer prev = net.layers[i - 1]; net.input = prev.output; net.delta = prev.delta; net.input_gpu = prev.output_gpu; net.delta_gpu = prev.delta_gpu; } net.index = i; l.backward_gpu(l, net); } } void update_network_gpu(network *netp) { network net = *netp; cuda_set_device(net.gpu_index); int i; update_args a = {0}; a.batch = net.batch * net.subdivisions; a.learning_rate = get_current_rate(netp); a.momentum = net.momentum; a.decay = net.decay; a.adam = net.adam; a.B1 = net.B1; a.B2 = net.B2; a.eps = net.eps; ++*net.t; a.t = (*net.t); for (i = 0; i < net.n; ++i) { layer l = net.layers[i]; if (l.update_gpu) { l.update_gpu(l, a, netp->st); } } } void harmless_update_network_gpu(network *netp) { network net = *netp; cuda_set_device(net.gpu_index); int i; for (i = 0; i < net.n; ++i) { layer l = net.layers[i]; if (l.weight_updates_gpu) fill_gpu(l.nweights, 0, l.weight_updates_gpu, 1, netp->st); if (l.bias_updates_gpu) fill_gpu(l.nbiases, 0, l.bias_updates_gpu, 1, netp->st); if (l.scale_updates_gpu) fill_gpu(l.nbiases, 0, l.scale_updates_gpu, 1, netp->st); } } typedef struct { network *net; data d; real_t *err; }train_args; void *train_thread(void *ptr) { train_args args = *(train_args*) ptr; free(ptr); cuda_set_device(args.net->gpu_index); *args.err = train_network(args.net, args.d); return 0; } pthread_t train_network_in_thread(network *net, data d, real_t *err) { pthread_t thread; train_args *ptr = (train_args *) calloc(1, sizeof(train_args)); ptr->net = net; ptr->d = d; ptr->err = err; if (pthread_create(&thread, 0, train_thread, ptr)) error("Thread creation failed"); return thread; } void merge_weights(layer l, layer base) { if (l.type == CONVOLUTIONAL) { axpy_cpu(l.n, 1, l.bias_updates, 1, base.biases, 1); axpy_cpu(l.nweights, 1, l.weight_updates, 1, base.weights, 1); if (l.scales) { axpy_cpu(l.n, 1, l.scale_updates, 1, base.scales, 1); } } else if (l.type == CONNECTED) { axpy_cpu(l.outputs, 1, l.bias_updates, 1, base.biases, 1); axpy_cpu(l.outputs * l.inputs, 1, l.weight_updates, 1, base.weights, 1); } } void scale_weights(layer l, real_t s) { if (l.type == CONVOLUTIONAL) { scal_cpu(l.n, s, l.biases, 1); scal_cpu(l.nweights, s, l.weights, 1); if (l.scales) { scal_cpu(l.n, s, l.scales, 1); } } else if (l.type == CONNECTED) { scal_cpu(l.outputs, s, l.biases, 1); scal_cpu(l.outputs * l.inputs, s, l.weights, 1); } } void pull_weights(layer l) { if (l.type == CONVOLUTIONAL || l.type == DECONVOLUTIONAL) { cuda_pull_array(l.biases_gpu, l.bias_updates, l.n); cuda_pull_array(l.weights_gpu, l.weight_updates, l.nweights); if (l.scales) cuda_pull_array(l.scales_gpu, l.scale_updates, l.n); } else if (l.type == CONNECTED) { cuda_pull_array(l.biases_gpu, l.bias_updates, l.outputs); cuda_pull_array(l.weights_gpu, l.weight_updates, l.outputs * l.inputs); } } void push_weights(layer l) { if (l.type == CONVOLUTIONAL || l.type == DECONVOLUTIONAL) { cuda_push_array(l.biases_gpu, l.biases, l.n); cuda_push_array(l.weights_gpu, l.weights, l.nweights); if (l.scales) cuda_push_array(l.scales_gpu, l.scales, l.n); } else if (l.type == CONNECTED) { cuda_push_array(l.biases_gpu, l.biases, l.outputs); cuda_push_array(l.weights_gpu, l.weights, l.outputs * l.inputs); } } void distribute_weights(layer l, layer base) { if (l.type == CONVOLUTIONAL || l.type == DECONVOLUTIONAL) { cuda_push_array(l.biases_gpu, base.biases, l.n); cuda_push_array(l.weights_gpu, base.weights, l.nweights); if (base.scales) cuda_push_array(l.scales_gpu, base.scales, l.n); } else if (l.type == CONNECTED) { cuda_push_array(l.biases_gpu, base.biases, l.outputs); cuda_push_array(l.weights_gpu, base.weights, l.outputs * l.inputs); } } /* void pull_updates(layer l) { if(l.type == CONVOLUTIONAL){ cuda_pull_array(l.bias_updates_gpu, l.bias_updates, l.n); cuda_pull_array(l.weight_updates_gpu, l.weight_updates, l.nweights); if(l.scale_updates) cuda_pull_array(l.scale_updates_gpu, l.scale_updates, l.n); } else if(l.type == CONNECTED){ cuda_pull_array(l.bias_updates_gpu, l.bias_updates, l.outputs); cuda_pull_array(l.weight_updates_gpu, l.weight_updates, l.outputs*l.inputs); } } void push_updates(layer l) { if(l.type == CONVOLUTIONAL){ cuda_push_array(l.bias_updates_gpu, l.bias_updates, l.n); cuda_push_array(l.weight_updates_gpu, l.weight_updates, l.nweights); if(l.scale_updates) cuda_push_array(l.scale_updates_gpu, l.scale_updates, l.n); } else if(l.type == CONNECTED){ cuda_push_array(l.bias_updates_gpu, l.bias_updates, l.outputs); cuda_push_array(l.weight_updates_gpu, l.weight_updates, l.outputs*l.inputs); } } void update_layer(layer l, network net) { int update_batch = net.batch*net.subdivisions; real_t rate = get_current_rate(net); l.t = get_current_batch(net); if(l.update_gpu){ l.update_gpu(l, update_batch, rate*l.learning_rate_scale, net.momentum, net.decay); } } void merge_updates(layer l, layer base) { if (l.type == CONVOLUTIONAL) { axpy_cpu(l.n, 1, l.bias_updates, 1, base.bias_updates, 1); axpy_cpu(l.nweights, 1, l.weight_updates, 1, base.weight_updates, 1); if (l.scale_updates) { axpy_cpu(l.n, 1, l.scale_updates, 1, base.scale_updates, 1); } } else if(l.type == CONNECTED) { axpy_cpu(l.outputs, 1, l.bias_updates, 1, base.bias_updates, 1); axpy_cpu(l.outputs*l.inputs, 1, l.weight_updates, 1, base.weight_updates, 1); } } void distribute_updates(layer l, layer base) { if(l.type == CONVOLUTIONAL || l.type == DECONVOLUTIONAL){ cuda_push_array(l.bias_updates_gpu, base.bias_updates, l.n); cuda_push_array(l.weight_updates_gpu, base.weight_updates, l.nweights); if(base.scale_updates) cuda_push_array(l.scale_updates_gpu, base.scale_updates, l.n); } else if(l.type == CONNECTED){ cuda_push_array(l.bias_updates_gpu, base.bias_updates, l.outputs); cuda_push_array(l.weight_updates_gpu, base.weight_updates, l.outputs*l.inputs); } } */ /* void sync_layer(network *nets, int n, int j) { int i; network net = nets[0]; layer base = net.layers[j]; scale_weights(base, 0); for (i = 0; i < n; ++i) { cuda_set_device(nets[i].gpu_index); layer l = nets[i].layers[j]; pull_weights(l); merge_weights(l, base); } scale_weights(base, 1./n); for (i = 0; i < n; ++i) { cuda_set_device(nets[i].gpu_index); layer l = nets[i].layers[j]; distribute_weights(l, base); } } */ void sync_layer(network **nets, int n, int j) { int i; network *net = nets[0]; layer base = net->layers[j]; scale_weights(base, 0); for (i = 0; i < n; ++i) { cuda_set_device(nets[i]->gpu_index); layer l = nets[i]->layers[j]; pull_weights(l); merge_weights(l, base); } scale_weights(base, 1. / n); for (i = 0; i < n; ++i) { cuda_set_device(nets[i]->gpu_index); layer l = nets[i]->layers[j]; distribute_weights(l, base); } } typedef struct { network **nets; int n; int j; }sync_args; void *sync_layer_thread(void *ptr) { sync_args args = *(sync_args*) ptr; sync_layer(args.nets, args.n, args.j); free(ptr); return 0; } pthread_t sync_layer_in_thread(network **nets, int n, int j) { pthread_t thread; sync_args *ptr = (sync_args *) calloc(1, sizeof(sync_args)); ptr->nets = nets; ptr->n = n; ptr->j = j; if (pthread_create(&thread, 0, sync_layer_thread, ptr)) error("Thread creation failed"); return thread; } void sync_nets(network **nets, int n, int interval) { int j; int layers = nets[0]->n; pthread_t *threads = (pthread_t *) calloc(layers, sizeof(pthread_t)); *(nets[0]->seen) += interval * (n - 1) * nets[0]->batch * nets[0]->subdivisions; for (j = 0; j < n; ++j) { *(nets[j]->seen) = *(nets[0]->seen); } for (j = 0; j < layers; ++j) { threads[j] = sync_layer_in_thread(nets, n, j); } for (j = 0; j < layers; ++j) { pthread_join(threads[j], 0); } free(threads); } real_t train_networks(network **nets, int n, data d, int interval) { int i; int batch = nets[0]->batch; int subdivisions = nets[0]->subdivisions; assert(batch * subdivisions * n == d.X.rows); pthread_t *threads = (pthread_t *) calloc(n, sizeof(pthread_t)); real_t *errors = (real_t *) calloc(n, sizeof(real_t)); real_t sum = 0; for (i = 0; i < n; ++i) { data p = get_data_part(d, i, n); threads[i] = train_network_in_thread(nets[i], p, errors + i); } for (i = 0; i < n; ++i) { pthread_join(threads[i], 0); //printf("%f\n", errors[i]); sum += errors[i]; } //cudaDeviceSynchronize(); if (get_current_batch(nets[0]) % interval == 0) { printf("Syncing... "); fflush(stdout); sync_nets(nets, n, interval); printf("Done!\n"); } //cudaDeviceSynchronize(); free(threads); free(errors); return (real_t) sum / (n); } void pull_network_output(network *net) { layer l = get_network_output_layer(net); cuda_pull_array(l.output_gpu, l.output, l.outputs * l.batch); } #endif
Main.c
#include "XSbench_header.h" #include "marker_stub.h" #ifdef MPI #include<mpi.h> #endif int main( int argc, char* argv[] ) { // ===================================================================== // Initialization & Command Line Read-In // ===================================================================== int version = 13; int mype = 0; int max_procs = omp_get_num_procs(); int i, thread, mat; unsigned long seed; double omp_start, omp_end, p_energy; unsigned long long vhash = 0; int nprocs; #ifdef MPI MPI_Status stat; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &mype); #endif // rand() is only used in the serial initialization stages. // A custom RNG is used in parallel portions. #ifdef VERIFICATION srand(26); #else srand(time(NULL)); #endif // Process CLI Fields -- store in "Inputs" structure Inputs in = read_CLI( argc, argv ); // Set number of OpenMP Threads omp_set_num_threads(in.nthreads); // Print-out of Input Summary if( mype == 0 ) { MARKER_INIT; print_inputs( in, nprocs, version ); } // ===================================================================== // Prepare Nuclide Energy Grids, Unionized Energy Grid, & Material Data // ===================================================================== // Allocate & fill energy grids #ifndef BINARY_READ if( mype == 0) printf("Generating Nuclide Energy Grids...\n"); #endif NuclideGridPoint ** nuclide_grids = gpmatrix(in.n_isotopes,in.n_gridpoints); #ifdef VERIFICATION generate_grids_v( nuclide_grids, in.n_isotopes, in.n_gridpoints ); #else generate_grids( nuclide_grids, in.n_isotopes, in.n_gridpoints ); #endif // Sort grids by energy #ifndef BINARY_READ if( mype == 0) printf("Sorting Nuclide Energy Grids...\n"); sort_nuclide_grids( nuclide_grids, in.n_isotopes, in.n_gridpoints ); #endif // Prepare Unionized Energy Grid Framework #ifndef BINARY_READ GridPoint * energy_grid = generate_energy_grid( in.n_isotopes, in.n_gridpoints, nuclide_grids ); #else GridPoint * energy_grid = (GridPoint *)malloc( in.n_isotopes * in.n_gridpoints * sizeof( GridPoint ) ); int * index_data = (int *) malloc( in.n_isotopes * in.n_gridpoints * in.n_isotopes * sizeof(int)); for( i = 0; i < in.n_isotopes*in.n_gridpoints; i++ ) energy_grid[i].xs_ptrs = &index_data[i*in.n_isotopes]; #endif // Double Indexing. Filling in energy_grid with pointers to the // nuclide_energy_grids. #ifndef BINARY_READ set_grid_ptrs( energy_grid, nuclide_grids, in.n_isotopes, in.n_gridpoints ); #endif #ifdef BINARY_READ if( mype == 0 ) printf("Reading data from \"XS_data.dat\" file...\n"); binary_read(in.n_isotopes, in.n_gridpoints, nuclide_grids, energy_grid); #endif // Get material data if( mype == 0 ) printf("Loading Mats...\n"); int *num_nucs = load_num_nucs(in.n_isotopes); int **mats = load_mats(num_nucs, in.n_isotopes); #ifdef VERIFICATION double **concs = load_concs_v(num_nucs); #else double **concs = load_concs(num_nucs); #endif #ifdef BINARY_DUMP if( mype == 0 ) printf("Dumping data to binary file...\n"); binary_dump(in.n_isotopes, in.n_gridpoints, nuclide_grids, energy_grid); if( mype == 0 ) printf("Binary file \"XS_data.dat\" written! Exiting...\n"); return 0; #endif // ===================================================================== // Cross Section (XS) Parallel Lookup Simulation Begins // ===================================================================== // Outer benchmark loop can loop through all possible # of threads #ifdef BENCHMARK for( int bench_n = 1; bench_n <=omp_get_num_procs(); bench_n++ ) { in.nthreads = bench_n; omp_set_num_threads(in.nthreads); #endif if( mype == 0 ) { printf("\n"); border_print(); center_print("SIMULATION", 79); border_print(); } omp_start = omp_get_wtime(); //initialize papi with one thread (master) here #ifdef PAPI if ( PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT){ fprintf(stderr, "PAPI library init error!\n"); exit(1); } #endif MARKER_START(mype); #if defined(MPI) && defined(GEM5_MARKERS) MPI_Barrier(MPI_COMM_WORLD); #endif // OpenMP compiler directives - declaring variables as shared or private #pragma omp parallel default(none) \ private(i, thread, p_energy, mat, seed) \ shared( max_procs, in, energy_grid, nuclide_grids, \ mats, concs, num_nucs, mype, vhash) { // Initialize parallel PAPI counters #ifdef PAPI int eventset = PAPI_NULL; int num_papi_events; #pragma omp critical { counter_init(&eventset, &num_papi_events); } #endif double macro_xs_vector[5]; // Initialize RNG seeds for threads thread = omp_get_thread_num(); seed = (thread+1)*19+17; // XS Lookup Loop #pragma omp for schedule(dynamic) for( i = 0; i < in.lookups; i++ ) { // Status text if( INFO && mype == 0 && thread == 0 && i % 1000 == 0 ) printf("\rCalculating XS's... (%.0lf%% completed)", (i / ( (double)in.lookups / (double) in.nthreads )) / (double) in.nthreads * 100.0); // Randomly pick an energy and material for the particle #ifdef VERIFICATION #pragma omp critical { p_energy = rn_v(); mat = pick_mat(&seed); } #else p_energy = rn(&seed); mat = pick_mat(&seed); #endif // debugging //printf("E = %lf mat = %d\n", p_energy, mat); // This returns the macro_xs_vector, but we're not going // to do anything with it in this program, so return value // is written over. calculate_macro_xs( p_energy, mat, in.n_isotopes, in.n_gridpoints, num_nucs, concs, energy_grid, nuclide_grids, mats, macro_xs_vector ); // Verification hash calculation // This method provides a consistent hash accross // architectures and compilers. #ifdef VERIFICATION char line[256]; sprintf(line, "%.5lf %d %.5lf %.5lf %.5lf %.5lf %.5lf", p_energy, mat, macro_xs_vector[0], macro_xs_vector[1], macro_xs_vector[2], macro_xs_vector[3], macro_xs_vector[4]); unsigned long long vhash_local = hash(line, 10000); #pragma omp atomic vhash += vhash_local; #endif } // Prints out thread local PAPI counters #ifdef PAPI if( mype == 0 && thread == 0 ) { printf("\n"); border_print(); center_print("PAPI COUNTER RESULTS", 79); border_print(); printf("Count \tSmybol \tDescription\n"); } { #pragma omp barrier } counter_stop(&eventset, num_papi_events); #endif } #ifndef PAPI if( mype == 0) { printf("\n" ); printf("Simulation complete.\n" ); MARKER_STOP(mype); } #endif omp_end = omp_get_wtime(); // Print / Save Results and Exit print_results( in, mype, omp_end-omp_start, nprocs, vhash ); #ifdef BENCHMARK } #endif #ifdef MPI MPI_Finalize(); #endif return 0; }
transpose.h
#ifndef PARLAY_TRANSPOSE_H_ #define PARLAY_TRANSPOSE_H_ #include "../monoid.h" #include "../sequence.h" #include "../utilities.h" namespace parlay { namespace internal { #ifdef PAR_GRANULARITY constexpr const size_t TRANS_THRESHHOLD = PAR_GRANULARITY / 4; #else constexpr const size_t TRANS_THRESHHOLD = 500; #endif #ifdef DEBUG constexpr const size_t NON_CACHE_OBLIVIOUS_THRESHOLD = 10000; #else constexpr const size_t NON_CACHE_OBLIVIOUS_THRESHOLD = 1 << 22; #endif inline size_t split(size_t n) { return n / 2; } template <typename assignment_tag, typename Iterator> struct transpose { Iterator A, B; transpose(Iterator AA, Iterator BB) : A(AA), B(BB) {} void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart, size_t cCount, size_t cLength) { if (cCount * rCount < TRANS_THRESHHOLD) { for (size_t i = rStart; i < rStart + rCount; i++) for (size_t j = cStart; j < cStart + cCount; j++) assign_dispatch(B[j * cLength + i], A[i * rLength + j], assignment_tag()); } else if (cCount > rCount) { size_t l1 = split(cCount); size_t l2 = cCount - l1; auto left = [&]() { transR(rStart, rCount, rLength, cStart, l1, cLength); }; auto right = [&]() { transR(rStart, rCount, rLength, cStart + l1, l2, cLength); }; par_do(left, right); } else { size_t l1 = split(cCount); size_t l2 = rCount - l1; auto left = [&]() { transR(rStart, l1, rLength, cStart, cCount, cLength); }; auto right = [&]() { transR(rStart + l1, l2, rLength, cStart, cCount, cLength); }; par_do(left, right); } } void trans(size_t rCount, size_t cCount) { #if defined(OPENMP) #pragma omp parallel #pragma omp single #endif transR(0, rCount, cCount, 0, cCount, rCount); } }; template <typename assignment_tag, typename InIterator, typename OutIterator, typename CountIterator, typename DestIterator> struct blockTrans { InIterator A; OutIterator B; CountIterator OA; DestIterator OB; blockTrans(InIterator AA, OutIterator BB, CountIterator OOA, DestIterator OOB) : A(AA), B(BB), OA(OOA), OB(OOB) {} void transR(size_t rStart, size_t rCount, size_t rLength, size_t cStart, size_t cCount, size_t cLength) { if (cCount * rCount < TRANS_THRESHHOLD * 16) { parallel_for(rStart, rStart + rCount, [&](size_t i) { for (size_t j = cStart; j < cStart + cCount; j++) { size_t sa = OA[i * rLength + j]; size_t sb = OB[j * cLength + i]; size_t l = OA[i * rLength + j + 1] - sa; for (size_t k = 0; k < l; k++) assign_dispatch(B[k + sb], A[k + sa], assignment_tag()); } }); } else if (cCount > rCount) { size_t l1 = split(cCount); size_t l2 = cCount - l1; auto left = [&]() { transR(rStart, rCount, rLength, cStart, l1, cLength); }; auto right = [&]() { transR(rStart, rCount, rLength, cStart + l1, l2, cLength); }; par_do(left, right); } else { size_t l1 = split(cCount); size_t l2 = rCount - l1; auto left = [&]() { transR(rStart, l1, rLength, cStart, cCount, cLength); }; auto right = [&]() { transR(rStart + l1, l2, rLength, cStart, cCount, cLength); }; par_do(left, right); } } void trans(size_t rCount, size_t cCount) { #if defined(OPENMP) #pragma omp parallel #pragma omp single #endif transR(0, rCount, cCount, 0, cCount, rCount); } }; // Moves values from blocks to buckets // From is sorted by key within each block, in block major // counts is the # of keys in each bucket for each block, in block major // From and To are of lenght n // counts is of length num_blocks * num_buckets // Data is memcpy'd into To avoiding initializers and overloaded = template <typename assignment_tag, typename InIterator, typename OutIterator, typename s_size_t> sequence<size_t> transpose_buckets(InIterator From, OutIterator To, sequence<s_size_t>& counts, size_t n, size_t block_size, size_t num_blocks, size_t num_buckets) { size_t m = num_buckets * num_blocks; sequence<s_size_t> dest_offsets; auto add = addm<s_size_t>(); // for smaller input do non-cache oblivious version if (n < NON_CACHE_OBLIVIOUS_THRESHOLD || num_buckets <= 512 || num_blocks <= 512) { size_t block_bits = log2_up(num_blocks); size_t block_mask = num_blocks - 1; assert(size_t{1} << block_bits == num_blocks); // determine the destination offsets auto get = [&](size_t i) { return counts[(i >> block_bits) + num_buckets * (i & block_mask)]; }; // slow down? dest_offsets = sequence<s_size_t>::from_function(m, get); [[maybe_unused]] auto sum = scan_inplace(make_slice(dest_offsets), add); assert(sum == n); // send each key to correct location within its bucket auto f = [&](size_t i) { size_t s_offset = i * block_size; for (size_t j = 0; j < num_buckets; j++) { size_t d_offset = dest_offsets[i + num_blocks * j]; size_t len = counts[i * num_buckets + j]; for (size_t k = 0; k < len; k++) assign_dispatch(To[d_offset++], From[s_offset++], assignment_tag()); } }; parallel_for(0, num_blocks, f, 1); } else { // for larger input do cache efficient transpose // sequence<s_size_t> source_offsets(counts,m+1); dest_offsets = sequence<s_size_t>(m); transpose<assignment_tag, typename sequence<s_size_t>::iterator>(counts.begin(), dest_offsets.begin()) .trans(num_blocks, num_buckets); // do both scans inplace [[maybe_unused]] size_t total = scan_inplace(make_slice(dest_offsets), add); [[maybe_unused]] size_t total2 = scan_inplace(make_slice(counts), add); assert(total == n && total2 == n); counts[m] = static_cast<s_size_t>(n); blockTrans<assignment_tag, InIterator, OutIterator, typename sequence<s_size_t>::iterator, typename sequence<s_size_t>::iterator>( From, To, counts.begin(), dest_offsets.begin()) .trans(num_blocks, num_buckets); } // return the bucket offsets, padded with n at the end return sequence<size_t>::from_function(num_buckets + 1, [&](size_t i) { return (i == num_buckets) ? n : dest_offsets[i * num_blocks]; }); } } // namespace internal } // namespace parlay #endif // PARLAY_TRANSPOSE_H_
GB_unop__tan_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__tan_fp64_fp64 // op(A') function: GB_unop_tran__tan_fp64_fp64 // C type: double // A type: double // cast: double cij = aij // unaryop: cij = tan (aij) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = tan (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = tan (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TAN || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__tan_fp64_fp64 ( double *Cx, // Cx and Ax may be aliased const double *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = tan (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__tan_fp64_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
sparselu.ref.c
#include <sys/time.h> #include <time.h> #include <stdio.h> static unsigned long long current_time_ns() { #ifdef __MACH__ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); unsigned long long s = 1000000000ULL * (unsigned long long)mts.tv_sec; return (unsigned long long)mts.tv_nsec + s; #else struct timespec t ={0,0}; clock_gettime(CLOCK_MONOTONIC, &t); unsigned long long s = 1000000000ULL * (unsigned long long)t.tv_sec; return (((unsigned long long)t.tv_nsec)) + s; #endif } /**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* 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 02110-1301 USA */ /**********************************************************************************************/ #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <libgen.h> #include "bots.h" #include "sparselu.h" /*********************************************************************** * checkmat: **********************************************************************/ int checkmat (float *M, float *N) { int i, j; float r_err; for (i = 0; i < bots_arg_size_1; i++) { for (j = 0; j < bots_arg_size_1; j++) { r_err = M[i*bots_arg_size_1+j] - N[i*bots_arg_size_1+j]; if ( r_err == 0.0 ) continue; if (r_err < 0.0 ) r_err = -r_err; if ( M[i*bots_arg_size_1+j] == 0 ) { bots_message("Checking failure: A[%d][%d]=%f B[%d][%d]=%f; \n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j]); return FALSE; } r_err = r_err / M[i*bots_arg_size_1+j]; if(r_err > EPSILON) { bots_message("Checking failure: A[%d][%d]=%f B[%d][%d]=%f; Relative Error=%f\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); return FALSE; } } } return TRUE; } /*********************************************************************** * genmat: **********************************************************************/ void genmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); p++; } } } else { M[ii*bots_arg_size+jj] = NULL; } } } } /*********************************************************************** * print_structure: **********************************************************************/ void print_structure(char *name, float *M[]) { int ii, jj; bots_message("Structure for matrix %s @ 0x%p\n",name, M); for (ii = 0; ii < bots_arg_size; ii++) { for (jj = 0; jj < bots_arg_size; jj++) { if (M[ii*bots_arg_size+jj]!=NULL) {bots_message("x");} else bots_message(" "); } bots_message("\n"); } bots_message("\n"); } /*********************************************************************** * allocate_clean_block: **********************************************************************/ float * allocate_clean_block() { int i,j; float *p, *q; p = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); q=p; if (p!=NULL){ for (i = 0; i < bots_arg_size_1; i++) for (j = 0; j < bots_arg_size_1; j++){(*p)=0.0; p++;} } else { bots_message("Error: Out of memory\n"); exit (101); } return (q); } /*********************************************************************** * lu0: **********************************************************************/ void lu0(float *diag) { int i, j, k; for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } } /*********************************************************************** * bdiv: **********************************************************************/ void bdiv(float *diag, float *row) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (k=0; k<bots_arg_size_1; k++) { row[i*bots_arg_size_1+k] = row[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) row[i*bots_arg_size_1+j] = row[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*diag[k*bots_arg_size_1+j]; } } /*********************************************************************** * bmod: **********************************************************************/ void bmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * fwd: **********************************************************************/ void fwd(float *diag, float *col) { int i, j, k; for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) col[i*bots_arg_size_1+j] = col[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } void sparselu_init (float ***pBENCH, char *pass) { *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); genmat(*pBENCH); print_structure(pass, *pBENCH); } void sparselu_par_call(float **BENCH) { int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); const unsigned long long full_program_start = current_time_ns(); { #pragma omp parallel { #pragma omp single nowait { #pragma omp task untied for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) { #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } } #pragma omp taskwait ; for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } #pragma omp taskwait ; } } } } ; const unsigned long long full_program_end = current_time_ns(); printf("full_program %llu ns\n", full_program_end - full_program_start); bots_message(" completed!\n"); } void sparselu_seq_call(float **BENCH) { int ii, jj, kk; for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } } void sparselu_fini (float **BENCH, char *pass) { print_structure(pass, BENCH); } int sparselu_check(float **SEQ, float **BENCH) { int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; }
engine.h
#pragma once #ifndef ENGINE_H #define ENGINE_H // Node API includes #include <napi.h> // STL includes #include <memory> #include <unordered_map> #include <any> // Eigen includes #include <Eigen/Core> // Optimization lib includes #include <libs/optimization_lib/include/core/core.h> #include <libs/optimization_lib/include/core/utils.h> #include <libs/optimization_lib/include/data_providers/mesh_wrapper.h> #include <libs/optimization_lib/include/data_providers/empty_data_provider.h> #include <libs/optimization_lib/include/data_providers/plain_data_provider.h> #include <libs/optimization_lib/include/data_providers/edge_pair_data_provider.h> #include <libs/optimization_lib/include/objective_functions/summation_objective.h> #include <libs/optimization_lib/include/objective_functions/position/face_position_objective.h> #include <libs/optimization_lib/include/objective_functions/separation_objective.h> #include <libs/optimization_lib/include/objective_functions/symmetric_dirichlet_objective.h> #include <libs/optimization_lib/include/objective_functions/seamless_objective.h> #include <libs/optimization_lib/include/objective_functions/singularity/singular_points_position_objective.h> #include <libs/optimization_lib/include/iterative_methods/newton_method.h> #include <libs/optimization_lib/include/solvers/eigen_sparse_solver.h> #include <libs/optimization_lib/include/solvers/pardiso_solver.h> class Engine : public Napi::ObjectWrap<Engine> { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); Engine(const Napi::CallbackInfo& info); private: /** * Private type definitions */ enum class ModelFileType { OBJ, OFF, UNKNOWN }; enum class BufferedPrimitiveType : uint32_t { VERTEX = 0, EDGE, TRIANGLE }; enum class DataSource { DOMAIN_DATA, IMAGE_DATA }; enum class FacesSource { DOMAIN_FACES, IMAGE_FACES }; enum class EdgesSource { DOMAIN_EDGES, IMAGE_EDGES }; enum class VerticesSource { DOMAIN_VERTICES, IMAGE_VERTICES }; enum class AlgorithmType { AUTOCUTS, AUTOQUADS }; static Napi::FunctionReference constructor; /** * NAPI private instance setters */ void SetPositionWeight(const Napi::CallbackInfo& info, const Napi::Value& value); void SetSeamlessWeight(const Napi::CallbackInfo& info, const Napi::Value& value); void SetLambda(const Napi::CallbackInfo& info, const Napi::Value& value); void SetDelta(const Napi::CallbackInfo& info, const Napi::Value& value); /** * NAPI private instance getters */ Napi::Value GetPositionWeight(const Napi::CallbackInfo& info); Napi::Value GetSeamlessWeight(const Napi::CallbackInfo& info); Napi::Value GetLambda(const Napi::CallbackInfo& info); Napi::Value GetDelta(const Napi::CallbackInfo& info); Napi::Value GetObjectiveFunctionsData(const Napi::CallbackInfo& info); /** * NAPI private instance methods */ Napi::Value GetDomainFacesCount(const Napi::CallbackInfo& info); Napi::Value GetImageFacesCount(const Napi::CallbackInfo& info); Napi::Value GetDomainEdgesCount(const Napi::CallbackInfo& info); Napi::Value GetImageEdgesCount(const Napi::CallbackInfo& info); Napi::Value GetDomainVerticesCount(const Napi::CallbackInfo& info); Napi::Value GetImageVerticesCount(const Napi::CallbackInfo& info); Napi::Value GetDomainFaces(const Napi::CallbackInfo& info); Napi::Value GetImageFaces(const Napi::CallbackInfo& info); Napi::Value GetDomainEdges(const Napi::CallbackInfo& info); Napi::Value GetImageEdges(const Napi::CallbackInfo& info); Napi::Value GetDomainVertices(const Napi::CallbackInfo& info); Napi::Value GetImageVertices(const Napi::CallbackInfo& info); Napi::Value GetDomainBufferedFaces(const Napi::CallbackInfo& info); Napi::Value GetImageBufferedFaces(const Napi::CallbackInfo& info); Napi::Value GetDomainBufferedEdges(const Napi::CallbackInfo& info); Napi::Value GetImageBufferedEdges(const Napi::CallbackInfo& info); Napi::Value GetDomainBufferedVertices(const Napi::CallbackInfo& info); Napi::Value GetImageBufferedVertices(const Napi::CallbackInfo& info); Napi::Value GetDomainBufferedUvs(const Napi::CallbackInfo& info); Napi::Value GetImageBufferedUvs(const Napi::CallbackInfo& info); Napi::Value Engine::GetDomainFaceEdgeAdjacency(const Napi::CallbackInfo& info); Napi::Value Engine::GetDomainEdgeFaceAdjacency(const Napi::CallbackInfo& info); Napi::Value Engine::GetImageFaceEdgeAdjacency(const Napi::CallbackInfo& info); Napi::Value Engine::GetImageEdgeFaceAdjacency(const Napi::CallbackInfo& info); Napi::Value GetObjectiveFunctionProperty(const Napi::CallbackInfo& info); Napi::Value SetObjectiveFunctionProperty(const Napi::CallbackInfo& info); Napi::Value LoadModel(const Napi::CallbackInfo& info); Napi::Value ResumeSolver(const Napi::CallbackInfo& info); Napi::Value PauseSolver(const Napi::CallbackInfo& info); Napi::Value SetAlgorithmType(const Napi::CallbackInfo& info); Napi::Value ConstrainFacePosition(const Napi::CallbackInfo& info); Napi::Value UpdateConstrainedFacePosition(const Napi::CallbackInfo& info); Napi::Value UnconstrainFacePosition(const Napi::CallbackInfo& info); Napi::Value ReconstrainFacePosition(const Napi::CallbackInfo& info); /** * Regular private instance methods */ ModelFileType GetModelFileType(std::string filename); void TryUpdateImageVertices(); Napi::Int32Array GetBufferedFaces(const Napi::CallbackInfo& info, const FacesSource faces_source) const; Napi::Int32Array GetBufferedEdges(const Napi::CallbackInfo& info, const EdgesSource edges_source) const; Napi::Float32Array GetBufferedVertices(const Napi::CallbackInfo& info, const VerticesSource vertices_source); Napi::Int32Array CreateBufferedFacesArray(Napi::Env env, const Eigen::MatrixXi& F) const; Napi::Int32Array CreateBufferedEdgesArray(Napi::Env env, const Eigen::MatrixXi& E) const; Napi::Array CreateFaces(Napi::Env env, const Eigen::MatrixX3i& F); Napi::Array CreateEdges(Napi::Env env, const Eigen::MatrixX2i& E); Napi::Value NativeToJS(Napi::Env env, const std::any& property_value); Napi::Value NativeToJS(Napi::Env env, const Eigen::VectorXd& property_value); Napi::Value NativeToJS(Napi::Env env, const std::vector<RDS::VertexIndex>& property_value); Napi::Value NativeToJS(Napi::Env env, const double property_value); Napi::Value NativeToJS(Napi::Env env, const std::string& property_value); std::any JSToNative(Napi::Env env, const Napi::Value& value); Napi::Value Engine::GetFaceEdgeAdjacency(const Napi::CallbackInfo& info, const DataSource data_source); Napi::Value Engine::GetEdgeFaceAdjacency(const Napi::CallbackInfo& info, const DataSource data_source); AlgorithmType StringToAlgorithmType(const std::string& algorithm_type_string); Napi::Value CreateObjectiveFunctionDataObject(Napi::Env env, std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>> objective_function) const; std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>> GetObjectiveFunctionByName(const std::string& name); /** * Regular private templated instance methods */ template <typename Derived> Napi::Array CreateVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V) { Napi::Array vertices_array = Napi::Array::New(env, V.rows()); auto entries_per_vertex = V.cols(); for (int32_t vertex_index = 0; vertex_index < V.rows(); vertex_index++) { Napi::Object vertex_object = Napi::Object::New(env); float x = V(vertex_index, 0); float y = V(vertex_index, 1); vertex_object.Set("x", x); vertex_object.Set("y", y); if (entries_per_vertex == 3) { float z = V(vertex_index, 2); vertex_object.Set("z", z); } vertices_array[vertex_index] = vertex_object; } return vertices_array; } template <typename Derived> Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixX3i& F) { const uint32_t entries_per_face = 9; const uint32_t entries_per_vertex = V.cols(); Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, entries_per_face * F.rows()); //#pragma omp parallel for for (int32_t face_index = 0; face_index < F.rows(); face_index++) { const int base_index = entries_per_face * face_index; for (uint32_t i = 0; i < 3; i++) { uint32_t vertex_index = F(face_index, i); const float x = V(vertex_index, 0); const float y = V(vertex_index, 1); const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2); const int base_vertex_index = base_index + 3 * i; buffered_vertices_array[base_vertex_index] = x; buffered_vertices_array[base_vertex_index + 1] = y; buffered_vertices_array[base_vertex_index + 2] = z; } } return buffered_vertices_array; } template <typename Derived> Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixX2i& E) { const uint32_t entries_per_edge = 6; const uint32_t entries_per_vertex = V.cols(); Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, entries_per_edge * E.rows()); //#pragma omp parallel for for (int32_t edge_index = 0; edge_index < E.rows(); edge_index++) { const int base_index = entries_per_edge * edge_index; for (uint32_t i = 0; i < 2; i++) { uint32_t vertex_index = E(edge_index, i); const float x = V(vertex_index, 0); const float y = V(vertex_index, 1); const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2); const int base_vertex_index = base_index + 3 * i; buffered_vertices_array[base_vertex_index] = x; buffered_vertices_array[base_vertex_index + 1] = y; buffered_vertices_array[base_vertex_index + 2] = z; } } return buffered_vertices_array; } template <typename Derived> Napi::Float32Array CreateBufferedVerticesArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V) { Napi::Float32Array buffered_vertices_array = Napi::Float32Array::New(env, 3 * V.rows()); const uint32_t entries_per_vertex = V.cols(); //#pragma omp parallel for for (int32_t vertex_index = 0; vertex_index < V.rows(); vertex_index++) { const float x = V(vertex_index, 0); const float y = V(vertex_index, 1); const float z = entries_per_vertex == 2 ? 0 : V(vertex_index, 2); const int base_index = 3 * vertex_index; buffered_vertices_array[base_index] = x; buffered_vertices_array[base_index + 1] = y; buffered_vertices_array[base_index + 2] = z; } return buffered_vertices_array; } template <typename Derived> Napi::Float32Array CreateBufferedUvsArray(Napi::Env env, const Eigen::MatrixBase<Derived>& V, const Eigen::MatrixXi& F) { const uint32_t entries_per_face = 6; uint32_t entries_per_vertex = V.cols(); Napi::Float32Array buffered_uvs_array = Napi::Float32Array::New(env, entries_per_face * F.rows()); //#pragma omp parallel for for (int32_t face_index = 0; face_index < F.rows(); face_index++) { const int base_index = entries_per_face * face_index; for (uint32_t i = 0; i < 3; i++) { uint32_t vertex_index = F(face_index, i); float x = V(vertex_index, 0); float y = V(vertex_index, 1); const int base_vertex_index = base_index + 2 * i; buffered_uvs_array[base_vertex_index] = x; buffered_uvs_array[base_vertex_index + 1] = y; } } return buffered_uvs_array; } /** * Fields */ std::unordered_map<RDS::Face, std::shared_ptr<FacePositionObjective<Eigen::StorageOptions::RowMajor>>, RDS::VectorHash, RDS::VectorEquals> face_to_position_objective_map_; std::unordered_map<RDS::Face, std::shared_ptr<FaceDataProvider>, RDS::VectorHash, RDS::VectorEquals> face_to_face_data_provider_map_; std::shared_ptr<MeshWrapper> mesh_wrapper_; std::shared_ptr<PlainDataProvider> plain_data_provider_; std::shared_ptr<EmptyDataProvider> empty_data_provider_; std::vector<std::shared_ptr<EdgePairDataProvider>> edge_pair_data_providers_; std::vector<std::shared_ptr<FaceFanDataProvider>> face_fan_data_providers_; std::vector<std::shared_ptr<FaceDataProvider>> face_data_providers_; std::vector<std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>>> summation_objectives_; std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> summation_objective_; std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> autoquads_summation_objective_; std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> autocuts_summation_objective_; std::shared_ptr<SummationObjective<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>, Eigen::VectorXd>> position_; std::shared_ptr<Separation<Eigen::StorageOptions::RowMajor>> separation_; std::shared_ptr<SymmetricDirichlet<Eigen::StorageOptions::RowMajor>> symmetric_dirichlet_; std::shared_ptr<SeamlessObjective<Eigen::StorageOptions::RowMajor>> seamless_; std::shared_ptr<SingularPointsPositionObjective<Eigen::StorageOptions::RowMajor>> singular_points_; std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> objective_functions_; std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> autocuts_objective_functions_; std::vector<std::shared_ptr<ObjectiveFunction<Eigen::StorageOptions::RowMajor, Eigen::VectorXd>>> autoquads_objective_functions_; std::unique_ptr<NewtonMethod<PardisoSolver, Eigen::StorageOptions::RowMajor>> newton_method_; std::vector<Eigen::DenseIndex> constrained_faces_indices; Eigen::MatrixX2d image_vertices_; std::unordered_map<std::string, uint32_t> properties_map_; std::unordered_map<std::string, uint32_t> property_modifiers_map_; }; #endif
Test_IO_Compressed.h
/* * Test_IO_Compressed.h * CubismZ * * Copyright 2018 ETH Zurich. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include "Types_single.h" #include "SerializerIO_WaveletCompression_MPI_Simple.h" #include "Reader_WaveletCompression.h" #include <ArgumentParser.h> #include <GridMPI.h> #define VERBOSE 0 #ifdef _USE_HDF_ #include <hdf5.h> #endif #ifdef _FLOAT_PRECISION_ #define HDF_REAL H5T_NATIVE_FLOAT #else #define HDF_REAL H5T_NATIVE_DOUBLE #endif //#define _PARALLEL_IO_ //#define _COLLECTIVE_IO_ typedef GridMPI < FluidGrid > G; class Test_IO_Compressed : public Simulation { protected: int BPDX, BPDY, BPDZ; int NPROCX, NPROCY, NPROCZ; int channel; int step_id; bool VERBOSITY; G * grid; ArgumentParser parser; string inputfile_name, inputfile_dataset, outputfile_name; int myrank, size; SerializerIO_WaveletCompression_MPI_SimpleBlocking<G, StreamerGridPointIterative> mywaveletdumper; void _ic(G& grid) { vector<BlockInfo> vInfo = grid.getResidentBlocksInfo(); #if VERBOSE Real min_u = 1e8, max_u = -1e8; #endif int myrank, mypeindex[3], pesize[3]; int periodic[3]; MPI_Comm cartcomm; periodic[0] = 1; periodic[1] = 1; periodic[2] = 1; pesize[0] = NPROCX; pesize[1] = NPROCY; pesize[2] = NPROCZ; MPI_Comm_size(MPI_COMM_WORLD, &size); assert(NPROCX*NPROCY*NPROCZ == size); MPI_Cart_create(MPI_COMM_WORLD, 3, pesize, periodic, true, &cartcomm); MPI_Comm_rank(cartcomm, &myrank); MPI_Cart_coords(cartcomm, myrank, 3, mypeindex); // open HDF5 // read data block // store in grid blocks int rank; char filename[256]; herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int coords[3]; coords[0] = mypeindex[0]; coords[1] = mypeindex[1]; coords[2] = mypeindex[2]; const int NX = BPDX*_BLOCKSIZE_; const int NY = BPDY*_BLOCKSIZE_; const int NZ = BPDZ*_BLOCKSIZE_; #if VERBOSE printf("coords = %d,%d,%d\n", coords[0], coords[1], coords[2]); printf("NX,NY,NZ = %d,%d,%d\n", NX, NY, NZ); #endif static const int NCHANNELS = TOTAL_CHANNELS; Real * array_all = new Real[NX * NY * NZ * NCHANNELS]; vector<BlockInfo> vInfo_local = grid.getResidentBlocksInfo(); static const int sX = 0; static const int sY = 0; static const int sZ = 0; const int eX = _BLOCKSIZE_; const int eY = _BLOCKSIZE_; const int eZ = _BLOCKSIZE_; hsize_t count[4] = { (hsize_t)NX, (hsize_t)NY, (hsize_t)NZ, (hsize_t)NCHANNELS}; // global domain size as specified by the process grid, the block layout and the block size hsize_t dims[4] = { (hsize_t)grid.getBlocksPerDimension(0)*_BLOCKSIZE_, (hsize_t)grid.getBlocksPerDimension(1)*_BLOCKSIZE_, (hsize_t)grid.getBlocksPerDimension(2)*_BLOCKSIZE_, (hsize_t)NCHANNELS}; hsize_t offset[4] = { (hsize_t)coords[0]*NX, (hsize_t)coords[1]*NY, (hsize_t)coords[2]*NZ, (hsize_t)0}; #if VERBOSE printf("count = [%d, %d, %d, %d]\n", count[0], count[1], count[2], count[3]); printf("dims = [%d, %d, %d, %d]\n", dims[0], dims[1], dims[2], dims[3]); printf("offset = [%d, %d, %d, %d]\n", offset[0], offset[1], offset[2], offset[3]); #endif sprintf(filename, "%s", inputfile_name.c_str()); H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); #if defined(_PARALLEL_IO_) status = H5Pset_fapl_mpio(fapl_id, MPI_COMM_WORLD, MPI_INFO_NULL); #endif file_id = H5Fopen(filename, H5F_ACC_RDONLY, fapl_id); status = H5Pclose(fapl_id); dataset_id = H5Dopen2(file_id, inputfile_dataset.c_str(), H5P_DEFAULT); fapl_id = H5Pcreate(H5P_DATASET_XFER); #if defined(_COLLECTIVE_IO_) H5Pset_dxpl_mpio(fapl_id, H5FD_MPIO_COLLECTIVE); #endif fspace_id = H5Dget_space(dataset_id); if (myrank == 0) { // Before reading any data, we perform a check that we have specified the correct and exact domain size //https://stackoverflow.com/questions/15786626/get-the-dimensions-of-a-hdf5-dataset //If your data space is simple (i.e. not null or scalar), then you can get the number of dimensions using H5Sget_simple_extent_ndims: const int ndims = H5Sget_simple_extent_ndims(fspace_id); //and the size of each dimension using H5Sget_simple_extent_dims: hsize_t hdims[ndims]; H5Sget_simple_extent_dims(fspace_id, hdims, NULL); //The dimensions are now stored in hdims. for (int i = 0; i < ndims; i++) printf("hdims[%d] = %llu\n", i, hdims[i]); for (int i = 0; i < ndims; i++) if (hdims[i] != dims[i]) { printf("The dataset size does not match the one specified by the user. Aborting... \n"); MPI_Abort(MPI_COMM_WORLD, 1); } } MPI_Barrier(MPI_COMM_WORLD); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); status = H5Dread(dataset_id, HDF_REAL, mspace_id, fspace_id, fapl_id, array_all); MPI_Barrier(MPI_COMM_WORLD); // fill in the blocks #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<(int)vInfo.size(); i++) { BlockInfo info = vInfo[i]; const int idx[3] = {info.index[0], info.index[1], info.index[2]}; FluidBlock& b = *(FluidBlock*)info.ptrBlock; #if VERBOSE printf("idx=[%d,%d,%d]\n", idx[0], idx[1], idx[2]); #endif for(int ix=sX; ix<eX; ix++) for(int iy=sY; iy<eY; iy++) for(int iz=sZ; iz<eZ; iz++) { const int gx = idx[0]*_BLOCKSIZE_ + ix; const int gy = idx[1]*_BLOCKSIZE_ + iy; const int gz = idx[2]*_BLOCKSIZE_ + iz; Real * const ptr_input = array_all + NCHANNELS*(gz + NZ * (gy + NY * gx)); Real val = ptr_input[channel]; b(ix, iy, iz).u = val; #if VERBOSE if (val < min_u) min_u = val; if (val > max_u) max_u = val; #endif } } #if VERBOSE printf("min_u = %lf max_u = %lf\n", min_u, max_u); #endif status = H5Pclose(fapl_id); status = H5Dclose(dataset_id); status = H5Sclose(fspace_id); status = H5Sclose(mspace_id); status = H5Fclose(file_id); H5close(); MPI_Comm_free(&cartcomm); delete [] array_all; } void _setup_mpi_constants(int& nprocx, int& nprocy, int& nprocz) { nprocx = parser("-nprocx").asInt(1); nprocy = parser("-nprocy").asInt(1); nprocz = parser("-nprocz").asInt(1); } public: const bool isroot; Test_IO_Compressed(const bool isroot, const int argc, const char ** argv): grid(NULL), parser(argc,argv), isroot(isroot) { } void setup() { parser.unset_strict_mode(); BPDX = parser("-bpdx").asInt(1); BPDY = parser("-bpdy").asInt(1); BPDZ = parser("-bpdz").asInt(1); step_id = parser("-stepid").asInt(0); channel = parser("-channel").asInt(0); MPI_Comm_rank(MPI_COMM_WORLD, &myrank); inputfile_name = parser("-h5file").asString("none"); inputfile_dataset = parser("-dataset").asString("/data"); outputfile_name = parser("-czfile").asString("none"); if (parser.exist("-help") || ((inputfile_name == "none")||(outputfile_name == "none"))) { printf("Usage: %s -h5file <hdf5 file> -czfile <cz file> -threshold <e> [-wtype <wt>] [-bpdx <nbx>] [-bpdy <nby>] [-bpdz <nbz>] [-nprocx <npx>] [-nprocy <npy>] [-nprocz <npz>]\n", "hdf2cz"); exit(1); } _setup_mpi_constants(NPROCX, NPROCY, NPROCZ); VERBOSITY = 0; if (isroot) VERBOSITY = 1; if (VERBOSITY) { printf("////////////////////////////////////////////////////////////\n"); printf("//////////// TEST IO Compressed MPI ///////////////\n"); printf("////////////////////////////////////////////////////////////\n"); } parser.loud(); if (!isroot) parser.mute(); grid = new G(NPROCX, NPROCY, NPROCZ, BPDX, BPDY, BPDZ); assert(grid != NULL); _ic(*grid); vp(*grid, step_id); } void vp(G& grid, const int step_id) { if (isroot) std::cout << "Creating MPI CZ dump...\n" ; const string path = parser("-fpath").asString("."); const int wtype = parser("-wtype").asInt(3); //3rd order average interpolating wavelets std::stringstream streamer; streamer<<path; streamer<<"/"; streamer<<outputfile_name; #if defined(_USE_SZ_) SZ_Init((char *)"sz.config"); #ifdef _OPENMP omp_set_num_threads(1); #endif #endif double threshold = parser("-threshold").asDouble(0); mywaveletdumper.verbose(); if (isroot) printf("setting threshold to %f\n", threshold); mywaveletdumper.set_threshold(threshold); mywaveletdumper.set_wtype_write(wtype); MPI_Barrier(MPI_COMM_WORLD); double t0 = MPI_Wtime(); mywaveletdumper.Write<0>(grid, streamer.str()); double t1 = MPI_Wtime(); if (isroot) std::cout << "done" << endl; int nthreads; #ifdef _OPENMP #pragma omp parallel #pragma omp master nthreads = omp_get_num_threads(); #else nthreads = 1; #endif if (isroot) std::cout << "Threads: " << nthreads << " Elapsed time: " << t1-t0 << " seconds" << endl; } void dispose() { #if defined(_USE_SZ_) SZ_Finalize(); #endif if (grid!=NULL) { delete grid; grid = NULL; } } };
tree.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_TREE_H_ #define LIGHTGBM_TREE_H_ #include <LightGBM/dataset.h> #include <LightGBM/meta.h> #include <LightGBM/random_generator.h> #include <string> #include <map> #include <memory> #include <unordered_map> #include <vector> namespace LightGBM { #define kCategoricalMask (1) #define kDefaultLeftMask (2) /*! * \brief Tree model */ class Tree { public: /*! * \brief Constructor * \param max_leaves The number of max leaves */ explicit Tree(int max_leaves); /*! * \brief Construtor, from a string * \param str Model string * \param used_len used count of str */ Tree(const char* str, size_t* used_len); ~Tree(); /*! * \brief Performing a split on tree leaves. * \param leaf Index of leaf to be split * \param feature Index of feature; the converted index after removing useless features * \param real_feature Index of feature, the original index on data * \param threshold_bin Threshold(bin) of split * \param threshold_double Threshold on feature value * \param left_value Model Left child output * \param right_value Model Right child output * \param left_cnt Count of left child * \param right_cnt Count of right child * \param gain Split gain * \param missing_type missing type * \param default_left default direction for missing value * \return The index of new leaf. */ int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin, double threshold_double, double left_value, double right_value, int left_cnt, int right_cnt, float gain, MissingType missing_type, bool default_left); /*! * \brief Performing a split on tree leaves, with categorical feature * \param leaf Index of leaf to be split * \param feature Index of feature; the converted index after removing useless features * \param real_feature Index of feature, the original index on data * \param threshold_bin Threshold(bin) of split, use bitset to represent * \param num_threshold_bin size of threshold_bin * \param threshold Thresholds of real feature value, use bitset to represent * \param num_threshold size of threshold * \param left_value Model Left child output * \param right_value Model Right child output * \param left_cnt Count of left child * \param right_cnt Count of right child * \param gain Split gain * \return The index of new leaf. */ int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin, const uint32_t* threshold, int num_threshold, double left_value, double right_value, int left_cnt, int right_cnt, float gain, MissingType missing_type); /*! \brief Get the output of one leaf */ inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; } /*! \brief Set the output of one leaf */ inline void SetLeafOutput(int leaf, double output) { leaf_value_[leaf] = output; } /*! * \brief Adding prediction value of this tree model to scores * \param data The dataset * \param num_data Number of total data * \param score Will add prediction to score */ void AddPredictionToScore(const Dataset* data, data_size_t num_data, double* score) const; /*! * \brief Adding prediction value of this tree model to scorese * \param data The dataset * \param used_data_indices Indices of used data * \param num_data Number of total data * \param score Will add prediction to score */ void AddPredictionToScore(const Dataset* data, const data_size_t* used_data_indices, data_size_t num_data, double* score) const; /*! * \brief Prediction on one record * \param feature_values Feature value of this record * \return Prediction result */ inline double Predict(const double* feature_values) const; inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const; inline int PredictLeafIndex(const double* feature_values) const; inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const; inline void PredictContrib(const double* feature_values, int num_features, double* output); /*! \brief Get Number of leaves*/ inline int num_leaves() const { return num_leaves_; } /*! \brief Get depth of specific leaf*/ inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; } /*! \brief Get feature of specific split*/ inline int split_feature(int split_idx) const { return split_feature_[split_idx]; } inline double split_gain(int split_idx) const { return split_gain_[split_idx]; } /*! \brief Get the number of data points that fall at or below this node*/ inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; } /*! * \brief Shrinkage for the tree's output * shrinkage rate (a.k.a learning rate) is used to tune the traning process * \param rate The factor of shrinkage */ inline void Shrinkage(double rate) { #pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048) for (int i = 0; i < num_leaves_; ++i) { leaf_value_[i] *= rate; } shrinkage_ *= rate; } inline void proportional_prune(int iter, float base, std::string boost_method, float g_m, int geo_clip) { float threshold; // if(iter <= 20) threshold = 1; // else if(boost_method == std::string("DPBoost") || boost_method == std::string("DPBoost_bagging") || boost_method == std::string("DPBoost_2level")) { if(geo_clip) threshold = (float) std::pow(base, iter) * g_m; else threshold = 1000; } else{ threshold = 1; } // threshold = 1; // float threshold = 0.1; for (int i = 0; i < num_leaves_; ++i) { // std::cout<<leaf_value_[i]<<" "; if(threshold < std::fabs(leaf_value_[i])){ leaf_value_[i] = leaf_value_[i] > 0 ? threshold : -threshold; } // std::cout<<leaf_value_[i]<<" "; } } inline void add_noise(float scale, int seed){ for(int i = 0; i < num_leaves_; i++) { Laplace lap(scale, seed); std::cout<<leaf_value_[i]<<" "; float noise = lap.return_a_random_variable(); leaf_value_[i] += noise; std::cout<<leaf_value_[i]<<" "; } } inline void add_noise(Laplace& lap, float scale){ // Laplace lap(scale, seed); for(int i = 0; i < num_leaves_; i++) { // int seed = std::chrono::system_clock::now().time_since_epoch().count(); // Laplace lap(scale, seed); // std::cout<<leaf_value_[i]<<" "; float noise = lap.return_a_random_variable(scale); leaf_value_[i] += noise; // std::cout<<leaf_value_[i]<<" "; } } inline double shrinkage() const { return shrinkage_; } inline void AddBias(double val) { #pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048) for (int i = 0; i < num_leaves_; ++i) { leaf_value_[i] = val + leaf_value_[i]; } // force to 1.0 shrinkage_ = 1.0f; } inline void AsConstantTree(double val) { num_leaves_ = 1; shrinkage_ = 1.0f; leaf_value_[0] = val; } /*! \brief Serialize this object to string*/ std::string ToString() const; /*! \brief Serialize this object to json*/ std::string ToJSON() const; /*! \brief Serialize this object to if-else statement*/ std::string ToIfElse(int index, bool predict_leaf_index) const; inline static bool IsZero(double fval) { if (fval > -kZeroThreshold && fval <= kZeroThreshold) { return true; } else { return false; } } inline static bool GetDecisionType(int8_t decision_type, int8_t mask) { return (decision_type & mask) > 0; } inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) { if (input) { (*decision_type) |= mask; } else { (*decision_type) &= (127 - mask); } } inline static int8_t GetMissingType(int8_t decision_type) { return (decision_type >> 2) & 3; } inline static void SetMissingType(int8_t* decision_type, int8_t input) { (*decision_type) &= 3; (*decision_type) |= (input << 2); } void RecomputeMaxDepth(); private: std::string NumericalDecisionIfElse(int node) const; std::string CategoricalDecisionIfElse(int node) const; inline int NumericalDecision(double fval, int node) const { uint8_t missing_type = GetMissingType(decision_type_[node]); if (std::isnan(fval)) { if (missing_type != 2) { fval = 0.0f; } } if ((missing_type == 1 && IsZero(fval)) || (missing_type == 2 && std::isnan(fval))) { if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) { return left_child_[node]; } else { return right_child_[node]; } } if (fval <= threshold_[node]) { return left_child_[node]; } else { return right_child_[node]; } } inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const { uint8_t missing_type = GetMissingType(decision_type_[node]); if ((missing_type == 1 && fval == default_bin) || (missing_type == 2 && fval == max_bin)) { if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) { return left_child_[node]; } else { return right_child_[node]; } } if (fval <= threshold_in_bin_[node]) { return left_child_[node]; } else { return right_child_[node]; } } inline int CategoricalDecision(double fval, int node) const { uint8_t missing_type = GetMissingType(decision_type_[node]); int int_fval = static_cast<int>(fval); if (int_fval < 0) { return right_child_[node];; } else if (std::isnan(fval)) { // NaN is always in the right if (missing_type == 2) { return right_child_[node]; } int_fval = 0; } int cat_idx = static_cast<int>(threshold_[node]); if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx], cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) { return left_child_[node]; } return right_child_[node]; } inline int CategoricalDecisionInner(uint32_t fval, int node) const { int cat_idx = static_cast<int>(threshold_in_bin_[node]); if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx], cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) { return left_child_[node]; } return right_child_[node]; } inline int Decision(double fval, int node) const { if (GetDecisionType(decision_type_[node], kCategoricalMask)) { return CategoricalDecision(fval, node); } else { return NumericalDecision(fval, node); } } inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const { if (GetDecisionType(decision_type_[node], kCategoricalMask)) { return CategoricalDecisionInner(fval, node); } else { return NumericalDecisionInner(fval, node, default_bin, max_bin); } } inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt, float gain); /*! * \brief Find leaf index of which record belongs by features * \param feature_values Feature value of this record * \return Leaf index */ inline int GetLeaf(const double* feature_values) const; inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const; /*! \brief Serialize one node to json*/ std::string NodeToJSON(int index) const; /*! \brief Serialize one node to if-else statement*/ std::string NodeToIfElse(int index, bool predict_leaf_index) const; std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const; double ExpectedValue() const; /*! \brief This is used fill in leaf_depth_ after reloading a model*/ inline void RecomputeLeafDepths(int node = 0, int depth = 0); /*! * \brief Used by TreeSHAP for data we keep about our decision path */ struct PathElement { int feature_index; double zero_fraction; double one_fraction; // note that pweight is included for convenience and is not tied with the other attributes, // the pweight of the i'th path element is the permuation weight of paths with i-1 ones in them double pweight; PathElement() {} PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {} }; /*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/ void TreeSHAP(const double *feature_values, double *phi, int node, int unique_depth, PathElement *parent_unique_path, double parent_zero_fraction, double parent_one_fraction, int parent_feature_index) const; /*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/ static void ExtendPath(PathElement *unique_path, int unique_depth, double zero_fraction, double one_fraction, int feature_index); /*! \brief Undo a previous extension of the decision path for TreeSHAP*/ static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index); /*! determine what the total permuation weight would be if we unwound a previous extension in the decision path*/ static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index); /*! \brief Number of max leaves*/ int max_leaves_; /*! \brief Number of current levas*/ int num_leaves_; // following values used for non-leaf node /*! \brief A non-leaf node's left child */ std::vector<int> left_child_; /*! \brief A non-leaf node's right child */ std::vector<int> right_child_; /*! \brief A non-leaf node's split feature */ std::vector<int> split_feature_inner_; /*! \brief A non-leaf node's split feature, the original index */ std::vector<int> split_feature_; /*! \brief A non-leaf node's split threshold in bin */ std::vector<uint32_t> threshold_in_bin_; /*! \brief A non-leaf node's split threshold in feature value */ std::vector<double> threshold_; int num_cat_; std::vector<int> cat_boundaries_inner_; std::vector<uint32_t> cat_threshold_inner_; std::vector<int> cat_boundaries_; std::vector<uint32_t> cat_threshold_; /*! \brief Store the information for categorical feature handle and mising value handle. */ std::vector<int8_t> decision_type_; /*! \brief A non-leaf node's split gain */ std::vector<float> split_gain_; // used for leaf node /*! \brief The parent of leaf */ std::vector<int> leaf_parent_; /*! \brief Output of leaves */ std::vector<double> leaf_value_; /*! \brief DataCount of leaves */ std::vector<int> leaf_count_; /*! \brief Output of non-leaf nodes */ std::vector<double> internal_value_; /*! \brief DataCount of non-leaf nodes */ std::vector<int> internal_count_; /*! \brief Depth for leaves */ std::vector<int> leaf_depth_; double shrinkage_; int max_depth_; }; inline void Tree::Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt, float gain) { int new_node_idx = num_leaves_ - 1; // update parent info int parent = leaf_parent_[leaf]; if (parent >= 0) { // if cur node is left child if (left_child_[parent] == ~leaf) { left_child_[parent] = new_node_idx; } else { right_child_[parent] = new_node_idx; } } // add new node split_feature_inner_[new_node_idx] = feature; split_feature_[new_node_idx] = real_feature; split_gain_[new_node_idx] = Common::AvoidInf(gain); // add two new leaves left_child_[new_node_idx] = ~leaf; right_child_[new_node_idx] = ~num_leaves_; // update new leaves leaf_parent_[leaf] = new_node_idx; leaf_parent_[num_leaves_] = new_node_idx; // save current leaf value to internal node before change internal_value_[new_node_idx] = leaf_value_[leaf]; internal_count_[new_node_idx] = left_cnt + right_cnt; leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value; leaf_count_[leaf] = left_cnt; leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value; leaf_count_[num_leaves_] = right_cnt; // update leaf depth leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1; leaf_depth_[leaf]++; } inline double Tree::Predict(const double* feature_values) const { if (num_leaves_ > 1) { int leaf = GetLeaf(feature_values); return LeafOutput(leaf); } else { return leaf_value_[0]; } } inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const { if (num_leaves_ > 1) { int leaf = GetLeafByMap(feature_values); return LeafOutput(leaf); } else { return leaf_value_[0]; } } inline int Tree::PredictLeafIndex(const double* feature_values) const { if (num_leaves_ > 1) { int leaf = GetLeaf(feature_values); return leaf; } else { return 0; } } inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const { if (num_leaves_ > 1) { int leaf = GetLeafByMap(feature_values); return leaf; } else { return 0; } } inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) { output[num_features] += ExpectedValue(); // Run the recursion with preallocated space for the unique path data if (num_leaves_ > 1) { CHECK(max_depth_ >= 0); const int max_path_len = max_depth_ + 1; std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2); TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1); } } inline void Tree::RecomputeLeafDepths(int node, int depth) { if (node == 0) leaf_depth_.resize(num_leaves()); if (node < 0) { leaf_depth_[~node] = depth; } else { RecomputeLeafDepths(left_child_[node], depth + 1); RecomputeLeafDepths(right_child_[node], depth + 1); } } inline int Tree::GetLeaf(const double* feature_values) const { int node = 0; if (num_cat_ > 0) { while (node >= 0) { node = Decision(feature_values[split_feature_[node]], node); } } else { while (node >= 0) { node = NumericalDecision(feature_values[split_feature_[node]], node); } } return ~node; } inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const { int node = 0; if (num_cat_ > 0) { while (node >= 0) { node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node); } } else { while (node >= 0) { node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node); } } return ~node; } } // namespace LightGBM #endif // LightGBM_TREE_H_
order-3.c
void foo (void); int v; #ifdef __cplusplus extern "C" { #endif int omp_get_thread_num (void); int omp_get_num_threads (void); int omp_target_is_present (const void *, int); int omp_get_cancellation (void); #ifdef __cplusplus } #endif void f1 (int *a) { int i; #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp parallel /* { dg-error "OpenMP constructs other than 'ordered simd', 'simd', 'loop' or 'atomic' may not be nested inside 'simd' region" } */ foo (); } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { int j; #pragma omp simd for (j = 0; j < 64; j++) a[64 * i + j] = i + j; } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp critical /* { dg-error "OpenMP constructs other than 'ordered simd', 'simd', 'loop' or 'atomic' may not be nested inside 'simd' region" } */ foo (); } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp ordered simd /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ foo (); } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ v++; } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic read /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ a[i] = v; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic write /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ v = a[i]; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_thread_num (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_thread_num\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_num_threads (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_num_threads\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_target_is_present (a + i, 0); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_target_is_present\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_cancellation (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_cancellation\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ } void f2 (int *a) { int i; #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp parallel /* { dg-error "OpenMP constructs other than 'ordered simd', 'simd', 'loop' or 'atomic' may not be nested inside 'simd' region" } */ foo (); } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { int j; #pragma omp simd for (j = 0; j < 64; j++) a[64 * i + j] = i + j; } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp critical /* { dg-error "OpenMP constructs other than 'ordered simd', 'simd', 'loop' or 'atomic' may not be nested inside 'simd' region" } */ foo (); } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp ordered simd /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ foo (); } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ v++; } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic read /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ a[i] = v; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic write /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ v = a[i]; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_thread_num (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_thread_num\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_num_threads (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_num_threads\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_target_is_present (a + i, 0); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_target_is_present\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for simd order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_cancellation (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_cancellation\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ } void f3 (int *a) { int i; #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp parallel foo (); } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { int j; #pragma omp simd for (j = 0; j < 64; j++) a[64 * i + j] = i + j; } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp critical /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ foo (); } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp ordered simd /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ foo (); } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ v++; } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic read /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ a[i] = v; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp atomic write /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c++ } } */ v = a[i]; /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" "" { target c } } */ } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { #pragma omp task /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ a[i]++; } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) { int j; #pragma omp taskloop /* { dg-error "OpenMP constructs other than 'parallel', 'loop' or 'simd' may not be nested inside a region with the 'order\\(concurrent\\)' clause" } */ for (j = 0; j < 64; j++) a[64 * i + j] = i + j; } #pragma omp for order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_thread_num (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_thread_num\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_num_threads (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_num_threads\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_target_is_present (a + i, 0); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_target_is_present\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ #pragma omp for order(concurrent) for (i = 0; i < 64; i++) a[i] += omp_get_cancellation (); /* { dg-error "OpenMP runtime API call '\[^\n\r]*omp_get_cancellation\[^\n\r]*' in a region with 'order\\(concurrent\\)' clause" } */ }
ChooserDemandCalculator.h
#pragma once #include <cassert> #include <fstream> #include <iostream> #include <random> #include <string> #include "DataStructures/Graph/Graph.h" #include "Tools/CommandLine/ProgressBar.h" #include "Tools/OpenMP.h" #include "Tools/Timer.h" // A travel demand calculator based on repeatedly choosing random sources and corresponding targets. // Each source is chosen with probability proportional to its population. The target is chosen to be // the closest opportunity with sufficiently high fitness. template <typename GraphT, template <typename> class OpportunityChooserT> class ChooserDemandCalculator { public: // Constructs a travel demand calculator for the specified network. explicit ChooserDemandCalculator(const GraphT& graph, const int seed, const bool verbose) noexcept : graph(graph), numOpportunities(0), seed(seed), verbose(verbose) { FORALL_VERTICES(graph, v) numOpportunities += graph.numOpportunities(v); assert(numOpportunities > 0); assert(seed >= 0); } // Generates OD pairs and writes them to the specified file. template <typename ...ChooserParameters> void calculateDemand( int numODPairs, double lambda, double swapProb, const std::string& fileName, ChooserParameters&& ...params) const { Timer timer; if (verbose) std::cout << "Calculating demand: "; ProgressBar bar(numODPairs, verbose); const auto firstWeight = &graph.population(0); const auto lastWeight = &graph.population(graph.numVertices() - 1) + 1; #pragma omp parallel { OpportunityChooserT<GraphT> chooser(graph, seed, params...); std::minstd_rand rand(seed + omp_get_thread_num() + 1); std::discrete_distribution<> sourceDist(firstWeight, lastWeight); std::uniform_int_distribution<> rankDist(1, numOpportunities); std::bernoulli_distribution swapDist(swapProb); std::ofstream out(fileName + ".part" + std::to_string(omp_get_thread_num())); assert(out.good()); #pragma omp for schedule(static, 1) nowait for (auto i = 0; i < numODPairs; ++i) { Timer tripTimer; auto src = sourceDist(rand); auto dst = src; while (src == dst) { auto numFitOpportunities = 0; while (numFitOpportunities == 0) { const auto rank = rankDist(rand); numFitOpportunities = std::binomial_distribution<>(rank, 1 - lambda)(rand); } dst = chooser.findClosestOpportunityWithHighFitness(src, numFitOpportunities); } if (swapDist(rand)) std::swap(src, dst); const auto timeToCalculateTrip = tripTimer.elapsed<std::chrono::nanoseconds>(); out << src << ',' << dst << ',' << timeToCalculateTrip << '\n'; ++bar; } } bar.finish(); if (verbose) std::cout << "done (" << timer.elapsed() << "ms)." << std::endl; } private: const GraphT& graph; // The network we work on. int numOpportunities; // The total number of opportunities in the network. const int seed; // The seed with which the random number generators will be started. const bool verbose; // Should we display informative messages? };
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/imperative.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_MKLDNN == 1 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #define DEBUG_OP_EXECUTOR 0 // Use 1 for activation of the output // of input/output parameters of MxNet operators #if DEBUG_OP_EXECUTOR #define OUTPUT_CONTAINER(ptr, shape, dtype, gpu) \ std::cout << "Pointer: " << ptr << std::endl; \ std::cout << "Shape: " << shape << std::endl; \ std::cout << "Type: " << dtype << std::endl; \ auto sTotal = shape.Size(); \ auto size = sTotal; \ if (size) { \ if (size > 100) size = 100; \ char buffer[512], *pntr; \ const char *pFrmt = "%+e "; \ const size_t l = sizeof(buffer); \ switch (dtype) { \ case mshadow::kInt32: pFrmt = "%5d "; break; \ case mshadow::kInt64: pFrmt = "%5l "; break; \ case mshadow::kUint8: pFrmt = "%5ud "; break; \ } \ MSHADOW_TYPE_SWITCH(dtype, DType, { \ DType *debug = gpu? new DType[size] : static_cast<DType *>(ptr); \ if (gpu) \ cudaMemcpy(debug, ptr, size * sizeof(DType), cudaMemcpyDeviceToHost); \ if (size > 1) { \ std::cout << "Values (" << sTotal << "):" << std::endl;\ for (size_t i = 0; i < size; i += 10) { \ pntr += snprintf(pntr = buffer, l, "%4lu: ", i); \ const size_t jMax = size - i < 10? size : i + 10; \ for (size_t j = i; j < jMax; ++j) \ pntr += snprintf(pntr, l - (pntr-buffer), pFrmt, debug[j]); \ std::cout << buffer << std::endl; \ } \ } else { \ std::cout << "Value: " << debug[0] << std::endl; \ } \ if (gpu) \ delete [] debug; \ }); \ if (size < shape.Size()) \ std::cout << " . . ." << std::endl; \ } \ else \ std::cout << "Values: None" << std::endl; \ std::cout << "End of element" << std::endl; #define OUTPUT_BLOB(blob, gpu) \ OUTPUT_CONTAINER(blob.dptr_, blob.shape_, blob.type_flag_, gpu) #define OUTPUT_ARRAY(arr, gpu) \ OUTPUT_CONTAINER(arr.storage_handle().dptr, arr.shape(), blob.dtype(), gpu) #define OUTPUT_VECTOR_INFO(data, io, gpu, OUTPUT_ELEMENT) \ std::cout << io << "s:" << std::endl; \ for (size_t i = 0; i < data.size(); ++i) { \ const auto& blob = data[i]; \ std::cout << io << " " << i << std::endl; \ OUTPUT_ELEMENT(blob, gpu); \ } \ std::cout << "End of "<< io << "s" << std::endl; #define BLOBS_INFO(data, io, gpu) OUTPUT_VECTOR_INFO(data, io, gpu, OUTPUT_BLOB) #define ARRAYS_INFO(data, io, gpu) OUTPUT_VECTOR_INFO(data, io, gpu, OUTPUT_ARRAY) #define INPUT_INFO(INFO, vect, fName, opPntr, aPntr, gpu, opNames) \ static const char *silentOps[] = opNames; \ char buf[512], *pBuf = buf; \ size_t l = sizeof(buffer); \ auto my_op = static_cast<const nnvm::Op*>(opPntr); \ int i = my_op? sizeof(silentOps)/sizeof(silentOps[0]) : 0; \ while (i-- && my_op->name != silentOps[i]) {} \ const bool silentOp = i >= 0; \ if (!silentOp) { \ if (my_op) \ pBuf += snprintf(pBuf, l, fName" start %cpu operation: %s", \ gpu? 'g' : 'c', my_op->name.c_str()); \ else \ pBuf += snprintf(pBuf, l, fName" started on %cpu", \ gpu? 'g' : 'c'); \ l -= pBuf - buf; \ auto pAttr = static_cast<const nnvm::NodeAttrs*>(aPntr); \ if (pAttr && !pAttr->name.empty()) \ snprintf(pBuf, l, " Attrs: %s\n", pAttr->name.c_str()); \ else \ snprintf(pBuf, l, "\n"); \ std::cout << buf; \ INFO(vect, "Input", gpu); \ } #define OUTPUT_INFO(INFO, vect, funcName, opPntr) \ const char *frmt; \ if (!silentOp) { \ cudaDeviceSynchronize(); \ INFO(vect, "Output", true); \ frmt = funcName" finish operation: %s\n"; \ } else { \ frmt = funcName" silent op: %s\n"; \ } \ if (opPntr) { \ auto my_op = static_cast<const nnvm::Op*>(opPntr); \ snprintf(buf, sizeof(buf), frmt, my_op->name.c_str()); \ } else { \ snprintf(buf, sizeof(buf), "Finishing in %s", funcName); \ } \ std::cout << buf; #define OUTPUT_ELEMENT(elem, funcName, start, gpu, OUT_ELEM) \ if (start) std::cout << funcName << " start" << std::endl; \ OUT_ELEM(elem, gpu); \ if (!start) std::cout << funcName << " finish" << std::endl; #else #define INPUT_INFO(INFO, vect, funcName, op, attrs, isGPU, silentOpNames) #define OUTPUT_INFO(INFO, vect, funcName, op) #define OUTPUT_ELEMENT(elem, funcName, start, gpu, OUT_ELEM) #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template<typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i+1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i+1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; /*! * \brief Class connects MXInitializeALM function from c_api and ALM. * It provides simple interface for adding new targets * and stores this data to be used later, while running ALM. */ class ALMParams { public: using ALMTargetsT = std::unordered_map<std::string, std::string>; static ALMParams& getALMParams() { static ALMParams alm; return alm; } bool empty() const { return targets_.empty(); } void addTarget(std::string opname, std::string targetLayout) { targets_[opname] = targetLayout; } int setTargets(ALMTargetsT new_targets) { targets_.clear(); targets_ = new_targets; return targets_.size(); } const ALMTargetsT& getTargets() const { return targets_; } ALMParams(ALMParams&) = delete; ALMParams operator=(ALMParams&) = delete; private: ALMTargetsT targets_; ALMParams() { } }; // class ALM_params template<typename xpu> void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template<typename xpu> void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template<typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu> *s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } inline std::string attr_value_string(const nnvm::NodeAttrs& attrs, const std::string& attr_name, std::string default_val = "") { if (attrs.dict.find(attr_name) == attrs.dict.end()) { return default_val; } return attrs.dict.at(attr_name); } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\nThe operator with default storage type will be dispatched " "for execution. You're seeing this warning message because the operator above is unable " "to process the given ndarrays with specified storage types, context and parameter. " "Temporary dense ndarrays are generated in order to execute the operator. " "This does not affect the correctness of the programme. " "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " "0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_MKLDNN == 1 if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. " "You can re-enable by setting MXNET_MKLDNN_ENABLED=1"); if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max(): size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } template <> constexpr size_t MaxIntegerValue<mshadow::bfloat::bf16_t>() { return size_t(2) << 14; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape &shape, const Context &ctx, const int dtype, std::vector<NDArray> *vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template<typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { std::memcpy(dst, src, sizeof(DType) * size); } } /*! * \breif parallelize add by OpenMP */ template<typename DType> inline void ParallelAdd(DType* dst, const DType* src, index_t size) { static index_t add_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= add_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } else { for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } void ExecuteMonInputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); void ExecuteMonOutputCallback( const nnvm::IndexedGraph &idx, const std::vector<NDArray *> &state_arrays, size_t nid, const std::function<void(const char *, const char *, void *)> &monitor_callback); /*! * \brief This is function can return the output names of a NodeEntry. */ static inline std::string GetOutputName(const nnvm::NodeEntry& e) { nnvm::Symbol sym; sym.outputs.push_back(e); return sym.ListOutputNames()[0]; } inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) { // convert negative axes to positive values const int ndim = src.ndim(); mxnet::TShape axes = src; for (int i = 0; i < ndim; ++i) { if (axes[i] < 0) { axes[i] += ndim; } CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")"; } return axes; } inline bool is_float(const int dtype) { return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16; } inline bool is_int(const int dtype) { return dtype == mshadow::kUint8 || dtype == mshadow::kInt8 || dtype == mshadow::kInt32 || dtype == mshadow::kInt64; } inline int get_more_precise_type(const int type1, const int type2) { if (type1 == type2) return type1; if (is_float(type1) && is_float(type2)) { if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) { return mshadow::kFloat64; } if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) { return mshadow::kFloat32; } return mshadow::kFloat16; } else if (is_float(type1) || is_float(type2)) { return is_float(type1) ? type1 : type2; } if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) { return mshadow::kInt64; } if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) { return mshadow::kInt32; } CHECK(!((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) || (type1 == mshadow::kInt8 && type2 == mshadow::kUint8))) << "1 is UInt8 and 1 is Int8 should not get here"; if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) { return mshadow::kUint8; } return mshadow::kInt8; } inline int np_binary_out_infer_type(const int type1, const int type2) { if ((type1 == mshadow::kUint8 && type2 == mshadow::kInt8) || (type1 == mshadow::kInt8 && type2 == mshadow::kUint8)) { return mshadow::kInt32; } return get_more_precise_type(type1, type2); } inline int GetDefaultDtype() { return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } inline int GetDefaultDtype(int dtype) { if (dtype != -1) return dtype; return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } struct MShadowTypeInfo { std::string name; int size; int acc_size; MShadowTypeInfo(const std::string name, const int size, const int acc_size) : name(std::move(name)), size(size), acc_size(acc_size) {} MShadowTypeInfo(const std::string name, const int size) : MShadowTypeInfo(name, size, size) {} }; inline const std::string NodeAttrsGetProfilerScope(const nnvm::NodeAttrs& attrs) { // obtain the profiler scope name, if assigned previously std::string profiler_scope = MXNET_STORAGE_DEFAULT_PROFILER_SCOPE_CSTR; const std::unordered_map<std::string, std::string>& node_attrs_dict = attrs.dict; const std::unordered_map<std::string, std::string>::const_iterator profiler_scope_iter = node_attrs_dict.find("__profiler_scope__"); if (profiler_scope_iter != node_attrs_dict.end()) { profiler_scope = profiler_scope_iter->second; } return profiler_scope; } MShadowTypeInfo mshadow_type_info(const int type_flag); inline index_t div_round(const index_t a, const index_t b) { return (a + b - 1) / b; } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
loopct_r6.c
/* * Input: ntabs nchannels padded_size * Output: ntabs ntimes -nchannels ; ntimes < padded_size * * We process a finished tab directly, so no need to build up the full ntabs array */ void deinterleave(const char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) { int tab; for (tab = 0; tab < ntabs; tab++) { int channel; #pragma omp parallel for for (channel = 0; channel < nchannels; channel+=6) { const char *channelA = &page[(tab*nchannels + channel + 0)*padded_size]; const char *channelB = &page[(tab*nchannels + channel + 1)*padded_size]; const char *channelC = &page[(tab*nchannels + channel + 2)*padded_size]; const char *channelD = &page[(tab*nchannels + channel + 3)*padded_size]; const char *channelE = &page[(tab*nchannels + channel + 4)*padded_size]; const char *channelF = &page[(tab*nchannels + channel + 5)*padded_size]; int time; for (time = 0; time < ntimes; time++) { // reverse freq order to comply with header transposed[time*nchannels+nchannels-(channel+0)-1] = channelA[time]; transposed[time*nchannels+nchannels-(channel+1)-1] = channelB[time]; transposed[time*nchannels+nchannels-(channel+2)-1] = channelC[time]; transposed[time*nchannels+nchannels-(channel+3)-1] = channelD[time]; transposed[time*nchannels+nchannels-(channel+4)-1] = channelE[time]; transposed[time*nchannels+nchannels-(channel+5)-1] = channelF[time]; } } } }
parallelJacobi_mp.c
/************************************************************ * Program to solve a finite difference * discretization of the screened Poisson equation: * (d2/dx2)u + (d2/dy2)u - alpha u = f * with zero Dirichlet boundary condition using the iterative * Jacobi method with overrelaxation. * * RHS (source) function * f(x,y) = -alpha*(1-x^2)(1-y^2)-2*[(1-x^2)+(1-y^2)] * * Analytical solution to the PDE * u(x,y) = (1-x^2)(1-y^2) * * Current Version: Christian Iwainsky, RWTH Aachen University * MPI C Version: Christian Terboven, RWTH Aachen University, 2006 * MPI Fortran Version: Dieter an Mey, RWTH Aachen University, 1999 - 2005 * Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998 * Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998 * * Unless READ_INPUT is defined, a meaningful input dataset is used (CT). * * Input : n - grid dimension in x direction * m - grid dimension in y direction * alpha - constant (always greater than 0.0) * tol - error tolerance for the iterative solver * relax - Successice Overrelaxation parameter * mits - maximum iterations for the iterative solver * * On output * : u(n,m) - Dependent variable (solution) * : f(n,m,alpha) - Right hand side function * *************************************************************/ #include <math.h> #include <mpi.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> /************************************************************* * Performs one iteration of the Jacobi method and computes * the residual value. * * NOTE: u(0,*), u(maxXCount-1,*), u(*,0) and u(*,maxYCount-1) * are BOUNDARIES and therefore not part of the solution. *************************************************************/ /********************************************************** * Checks the error between numerical and exact solutions **********************************************************/ double checkSolution(double xStart, double yStart, int maxXCount, int maxYCount, double *u, double deltaX, double deltaY, double alpha) { #define U(XX, YY) u[(YY)*maxXCount + (XX)] int x, y; double fX, fY; double localError, error = 0.0; for (y = 1; y < (maxYCount - 1); y++) { fY = yStart + (y - 1) * deltaY; for (x = 1; x < (maxXCount - 1); x++) { fX = xStart + (x - 1) * deltaX; localError = U(x, y) - (1.0 - fX * fX) * (1.0 - fY * fY); error += localError * localError; } } return error; // return sqrt(error) / ((maxXCount - 2) * (maxYCount - 2)); } int main(int argc, char **argv) { int n, m, mits, comm_sz, my_rank; double alpha, tol, relax; double maxAcceptableError; double error; double global_sum; double global_error; double *u, *u_old, *tmp; int allocCount; int iterationCount, maxIterationCount; double t1, t2; MPI_Comm initialComm; initialComm = MPI_COMM_WORLD; MPI_Init(NULL, NULL); MPI_Comm_size(initialComm, &comm_sz); //Create mpi cart int dims[2] = {0, 0}; MPI_Dims_create(comm_sz, 2, dims); int periods[2] = {false, false}; MPI_Comm comm; MPI_Cart_create(initialComm, 2, dims, periods, true, &comm); MPI_Comm_rank(comm, &my_rank); int my_coords[2]; MPI_Cart_coords(comm, my_rank, 2, my_coords); if (my_rank == 0) { // printf("Input n,m - grid dimension in x,y direction:\n"); scanf("%d,%d", &n, &m); // printf("Input alpha - Helmholtz constant:\n"); scanf("%lf", &alpha); // printf("Input relax - successive over-relaxation parameter:\n"); scanf("%lf", &relax); // printf("Input tol - error tolerance for the iterrative solver:\n"); scanf("%lf", &tol); // printf("Input mits - maximum solver iterations:\n"); scanf("%d", &mits); printf("-> rank %d : %d, %d, %g, %g, %g, %d\n", my_rank, n, m, alpha, relax, tol, mits); allocCount = (n + 2) * (m + 2); } MPI_Bcast(&n, 1, MPI_INT, 0, comm); //todo: make all in parent MPI_Bcast(&m, 1, MPI_INT, 0, comm); MPI_Bcast(&alpha, 1, MPI_DOUBLE, 0, comm); MPI_Bcast(&relax, 1, MPI_DOUBLE, 0, comm); MPI_Bcast(&tol, 1, MPI_DOUBLE, 0, comm); MPI_Bcast(&mits, 1, MPI_INT, 0, comm); // Those two calls also zero the boundary elements // printf("-> rank %d, %d \n", my_rank, n); maxIterationCount = mits; maxAcceptableError = tol; // Solve in [-1, 1] x [-1, 1] double xLeft = -1.0, xRight = 1.0; double yBottom = -1.0, yUp = 1.0; iterationCount = 0; error = HUGE_VAL; clock_t start = clock(), diff; int size_n = n / (int)sqrt(comm_sz); int size_m = m / (int)sqrt(comm_sz); int squareComm = (int)sqrt(comm_sz); double deltaX = (xRight - xLeft) / (n - 1); double deltaY = (yUp - yBottom) / (m - 1); MPI_Barrier(comm); t1 = MPI_Wtime(); // double xStart = xLeft + deltaX * size_n * (my_rank % (int)sqrt(comm_sz)); // double yStart = yBottom + deltaY * size_m * (((comm_sz - (int)sqrt(comm_sz)) / (int)sqrt(comm_sz)) - (my_rank / (int)sqrt(comm_sz))); xLeft = xLeft + deltaX * size_n * (my_rank % (int)sqrt(comm_sz)); yBottom = yBottom + deltaY * size_m * (((comm_sz - (int)sqrt(comm_sz)) / (int)sqrt(comm_sz)) - (my_rank / (int)sqrt(comm_sz))); enum directions { DOWN, UP, LEFT, RIGHT }; char *neighbour_names[4] = { "left", "right", "up", "down"}; int neighbour_ranks[4]; MPI_Cart_shift(comm, 0, 1, &neighbour_ranks[LEFT], &neighbour_ranks[RIGHT]); MPI_Cart_shift(comm, 1, 1, &neighbour_ranks[DOWN], &neighbour_ranks[UP]); MPI_Comm_rank(comm, &my_rank); // for (int i = 0; i < 4; i++) { // if (neighbour_ranks[i] == MPI_PROC_NULL) // printf("[MPI process %d] I have no %s neighbour. neighbour_ranks %d\n", my_rank, neighbour_names[i], neighbour_ranks[i]); // else // printf("[MPI process %d] I have a %s neighbour: process %d neighbour_ranks.\n", my_rank, neighbour_names[i], neighbour_ranks[i]); // } /* Iterate as long as it takes to meet the convergence criterion */ u = (double *)calloc(((size_n + 2) * (size_m + 2)), sizeof(double)); //reverse order u_old = (double *)calloc(((size_n + 2) * (size_m + 2)), sizeof(double)); if (u == NULL || u_old == NULL) { printf("Not enough memory for two %ix%i matrices\n", n + 2, m + 2); exit(1); } // maxIterationCount while (iterationCount < maxIterationCount && error > maxAcceptableError) { // printf("Iteration %i", iterationCount); #define SRC(XX, YY) u_old[(YY) * (size_n + 2) + (XX)] #define DST(XX, YY) u[(YY) * (size_n + 2) + (XX)] int x, y; double fX, fY; error = 0.0; double updateVal; double f; // Coefficients double cx = 1.0 / (deltaX * deltaX); double cy = 1.0 / (deltaY * deltaY); double cc = -2.0 * cx - 2.0 * cy - alpha; int neighbourUp = my_rank - squareComm; int neighbourDown = my_rank + squareComm; int neighbourLeft = my_rank - 1; int neighbourRight = my_rank + 1; int firstColumn = (my_rank % squareComm == 0); int lastColumn = ((my_rank + 1) % squareComm) == 0; int firstRow = (my_rank / squareComm) == 0; int lastRow = (my_rank / squareComm) == (squareComm - 1); //Define Column and Row Types MPI_Datatype column_type; MPI_Type_vector(size_n, 1, size_n + 2, MPI_DOUBLE, &column_type); MPI_Type_commit(&column_type); MPI_Datatype row_type; MPI_Type_contiguous(size_n, MPI_DOUBLE, &row_type); MPI_Type_commit(&row_type); MPI_Request sendRequests[4]; MPI_Request receiveRequests[4]; double dataRight[size_n]; double dataLeft[size_n]; double dataUp[size_n]; double dataDown[size_n]; for(int i =0 ; i < size_n ; i ++){ dataLeft[i] = 0.0; } for(int i =0 ; i < size_n ; i ++){ dataRight[i] = 0.0; } for(int i =0 ; i < size_n ; i ++){ dataUp[i] = 0.0; } for(int i =0 ; i < size_n ; i ++){ dataDown[i] = 0.0; } MPI_Irecv(&dataLeft, size_n, MPI_DOUBLE, neighbour_ranks[0], 0, comm, &receiveRequests[0]); MPI_Irecv(&dataRight, size_n, MPI_DOUBLE, neighbour_ranks[1], 0, comm, &receiveRequests[1]); MPI_Irecv(&dataUp, size_n, MPI_DOUBLE, neighbour_ranks[2], 0, comm, &receiveRequests[2]); MPI_Irecv(&dataDown, size_n, MPI_DOUBLE, neighbour_ranks[3], 0, comm, &receiveRequests[3]); MPI_Isend(&(SRC(1, 1)), 1, column_type, neighbour_ranks[0], 0, comm, &sendRequests[0]); MPI_Isend(&(SRC(size_n, 1)), 1, column_type, neighbour_ranks[1], 0, comm, &sendRequests[1]); MPI_Isend(&(SRC(1, 1)), 1, row_type, neighbour_ranks[2], 0, comm, &sendRequests[2]); MPI_Isend(&(SRC(1, size_n)), 1, row_type, neighbour_ranks[3], 0, comm, &sendRequests[3]); #pragma omp parallel for num_threads(4) collapse(2) private(fX,f,fY,updateVal)\ reduction(+: error) schedule(static,1) for (y = 2; y < (size_m); y++) { // white boxes for (x = 2; x < (size_n); x++) { fY = yBottom + (y - 1) * deltaY; fX = xLeft + (x - 1) * deltaX; f = -alpha * (1.0 - fX * fX) * (1.0 - fY * fY) - 2.0 * (1.0 - fX * fX) - 2.0 * (1.0 - fY * fY); updateVal = ((SRC(x - 1, y) + SRC(x + 1, y)) * cx + (SRC(x, y - 1) + SRC(x, y + 1)) * cy + SRC(x, y) * cc - f) / cc; DST(x, y) = SRC(x, y) - relax * updateVal; error += updateVal * updateVal; // if ((my_rank == 0 && (!(y%50))&&(!(x%50)))){ // printf("y = %d x = %d updateval = %g\n",y,x,updateVal); // } } } MPI_Waitall(4, receiveRequests, MPI_STATUSES_IGNORE); // if(!my_rank && iterationCount==10){ // for(int i = 0;i<size_n;i++){ // printf("%g %g \n",dataRight[i],SRC(size_n,i+1)); // } // printf("\n"); // } for (int i = 1; i < size_n + 1; i++) { SRC(size_n + 1, i) = dataRight[i - 1]; SRC(0, i) = dataLeft[i - 1]; SRC(i, 0) = dataUp[i - 1]; SRC(i, size_n+1) = dataDown[i - 1]; } // error = sqrt(error) / ((size_n - 2) * (size_m - 2)); // #pragma omp parallel num_threads(4) // #pragma omp for collapse(2) private(updateVal,fY,fX,f) \ // reduction(+: error) schedule(static,1) // if ((my_rank == 0 && (!(y%50))&&(!(x%50)))){ // thread_rank = omp_get_thread_num(); // printf("Hello from thread: %d y= %d x= %d updateval = %g\n", thread_rank,y,x,updateVal); // } y = 1; fY = yBottom + (y - 1) * deltaY; #pragma omp parallel for num_threads(4) private(fX,f,updateVal)\ reduction(+: error) schedule(static,1) for (x = 1; x < size_n + 1; x++) { fX = xLeft + (x - 1) * deltaX; f = -alpha * (1.0 - fX * fX) * (1.0 - fY * fY) - 2.0 * (1.0 - fX * fX) - 2.0 * (1.0 - fY * fY); updateVal = ((SRC(x - 1, y) + SRC(x + 1, y)) * cx + (SRC(x, y - 1) + SRC(x, y + 1)) * cy + SRC(x, y) * cc - f) / cc; DST(x, y) = SRC(x, y) - relax * updateVal; error += updateVal * updateVal; } y = size_m; fY = yBottom + (y - 1) * deltaY; #pragma omp parallel for num_threads(4) private(fX,f,updateVal)\ reduction(+: error) schedule(static,1) for (x = 1; x < size_n + 1; x++) { fX = xLeft + (x - 1) * deltaX; f = -alpha * (1.0 - fX * fX) * (1.0 - fY * fY) - 2.0 * (1.0 - fX * fX) - 2.0 * (1.0 - fY * fY); updateVal = ((SRC(x - 1, y) + SRC(x + 1, y)) * cx + (SRC(x, y - 1) + SRC(x, y + 1)) * cy + SRC(x, y) * cc - f) / cc; DST(x, y) = SRC(x, y) - relax * updateVal; error += updateVal * updateVal; } x = 1; fX = xLeft + (x - 1) * deltaX; #pragma omp parallel for num_threads(4) private(fY,f,updateVal)\ reduction(+: error) schedule(static,1) for (y = 1; y < size_m + 1; y++) { // green columns fY = yBottom + (y - 1) * deltaY; f = -alpha * (1.0 - fX * fX) * (1.0 - fY * fY) - 2.0 * (1.0 - fX * fX) - 2.0 * (1.0 - fY * fY); updateVal = ((SRC(x - 1, y) + SRC(x + 1, y)) * cx + (SRC(x, y - 1) + SRC(x, y + 1)) * cy + SRC(x, y) * cc - f) / cc; DST(x, y) = SRC(x, y) - relax * updateVal; error += updateVal * updateVal; // printf("%d column error \n", error); } x = size_n; fX = xLeft + (x - 1) * deltaX; #pragma omp parallel for num_threads(4) private(fY,f,updateVal)\ reduction(+: error) schedule(static,1) for (y = 1; y < size_m + 1; y++) { // green columns fY = yBottom + (y - 1) * deltaY; f = -alpha * (1.0 - fX * fX) * (1.0 - fY * fY) - 2.0 * (1.0 - fX * fX) - 2.0 * (1.0 - fY * fY); updateVal = ((SRC(x - 1, y) + SRC(x + 1, y)) * cx + (SRC(x, y - 1) + SRC(x, y + 1)) * cy + SRC(x, y) * cc - f) / cc; DST(x, y) = SRC(x, y) - relax * updateVal; error += updateVal * updateVal; // printf("%d column error \n", error); } MPI_Allreduce(&error, &global_sum, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); error = sqrt(global_sum) / (((n + 2) - 2) * ((m + 2) - 2)); MPI_Waitall(4, sendRequests, MPI_STATUSES_IGNORE); iterationCount++; tmp = u_old; u_old = u; u = tmp; // printf("\tError %g IN IT %d\n", error,iterationCount); } t2 = MPI_Wtime(); printf("Iterations=%3d Elapsed MPI Wall time is %f\n", iterationCount, t2 - t1); diff = clock() - start; int msec = diff * 1000 / CLOCKS_PER_SEC; printf("Time taken %d seconds %d milliseconds\n", msec / 1000, msec % 1000); printf("Residual %g\n", error); // u_old holds the solution after the most recent buffers swap double absoluteError = checkSolution(xLeft, yBottom, size_n + 2, size_m + 2, u_old, deltaX, deltaY, alpha); MPI_Allreduce(&absoluteError, &global_error, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); global_error = sqrt(global_error) / (((n + 2) - 2) * ((m + 2) - 2)); printf("The error of the iterative solution is %g\n", global_error); MPI_Finalize(); return 0; }
fold.c
/* * minimum free energy * RNA secondary structure prediction * * c Ivo Hofacker, Chrisoph Flamm * original implementation by * Walter Fontana * g-quadruplex support and threadsafety * by Ronny Lorenz * * Vienna RNA package */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include <limits.h> #include "ViennaRNA/utils/basic.h" #include "ViennaRNA/params/default.h" #include "ViennaRNA/datastructures/basic.h" #include "ViennaRNA/fold_vars.h" #include "ViennaRNA/params/basic.h" #include "ViennaRNA/constraints/hard.h" #include "ViennaRNA/constraints/soft.h" #include "ViennaRNA/gquad.h" #include "ViennaRNA/loops/all.h" #include "ViennaRNA/fold.h" #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY #ifdef _OPENMP #include <omp.h> #endif #endif #define MAXSECTORS 500 /* dimension for a backtrack array */ /* ################################# # GLOBAL VARIABLES # ################################# */ /* ################################# # PRIVATE VARIABLES # ################################# */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /* some backward compatibility stuff */ PRIVATE int backward_compat = 0; PRIVATE vrna_fold_compound_t *backward_compat_compound = NULL; #ifdef _OPENMP #pragma omp threadprivate(backward_compat_compound, backward_compat) #endif #endif /* ################################# # PRIVATE FUNCTION DECLARATIONS # ################################# */ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY /* wrappers for old API compatibility */ PRIVATE float wrap_fold(const char *string, char *structure, vrna_param_t *parameters, int is_constrained, int is_circular); PRIVATE void wrap_array_export(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p); PRIVATE void wrap_array_export_circ(int *Fc_p, int *FcH_p, int *FcI_p, int *FcM_p, int **fM2_p); #endif /* ################################# # BEGIN OF FUNCTION DEFINITIONS # ################################# */ /*###########################################*/ /*# deprecated functions below #*/ /*###########################################*/ #ifndef VRNA_DISABLE_BACKWARD_COMPATIBILITY PRIVATE void wrap_array_export(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p) { /* make the DP arrays available to routines such as subopt() */ if (backward_compat_compound) { *f5_p = backward_compat_compound->matrices->f5; *c_p = backward_compat_compound->matrices->c; *fML_p = backward_compat_compound->matrices->fML; *fM1_p = backward_compat_compound->matrices->fM1; *indx_p = backward_compat_compound->jindx; *ptype_p = backward_compat_compound->ptype; } } PRIVATE void wrap_array_export_circ(int *Fc_p, int *FcH_p, int *FcI_p, int *FcM_p, int **fM2_p) { /* make the DP arrays available to routines such as subopt() */ if (backward_compat_compound) { *Fc_p = backward_compat_compound->matrices->Fc; *FcH_p = backward_compat_compound->matrices->FcH; *FcI_p = backward_compat_compound->matrices->FcI; *FcM_p = backward_compat_compound->matrices->FcM; *fM2_p = backward_compat_compound->matrices->fM2; } } PRIVATE float wrap_fold(const char *string, char *structure, vrna_param_t *parameters, int is_constrained, int is_circular) { vrna_fold_compound_t *vc; vrna_param_t *P; float mfe; #ifdef _OPENMP /* Explicitly turn off dynamic threads */ omp_set_dynamic(0); #endif /* we need the parameter structure for hard constraints */ if (parameters) { P = vrna_params_copy(parameters); } else { vrna_md_t md; set_model_details(&md); md.temperature = temperature; P = vrna_params(&md); } P->model_details.circ = is_circular; vc = vrna_fold_compound(string, &(P->model_details), VRNA_OPTION_DEFAULT); if (parameters) { /* replace params if necessary */ free(vc->params); vc->params = P; } else { free(P); } /* handle hard constraints in pseudo dot-bracket format if passed via simple interface */ if (is_constrained && structure) { unsigned int constraint_options = 0; constraint_options |= VRNA_CONSTRAINT_DB | VRNA_CONSTRAINT_DB_PIPE | VRNA_CONSTRAINT_DB_DOT | VRNA_CONSTRAINT_DB_X | VRNA_CONSTRAINT_DB_ANG_BRACK | VRNA_CONSTRAINT_DB_RND_BRACK; vrna_constraints_add(vc, (const char *)structure, constraint_options); } if (backward_compat_compound && backward_compat) vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = vc; backward_compat = 1; /* call mfe() function without backtracking */ mfe = vrna_mfe(vc, NULL); /* backtrack structure */ if (structure && vc->params->model_details.backtrack) { char *ss; int length; sect bt_stack[MAXSECTORS]; vrna_bp_stack_t *bp; length = vc->length; /* add a guess of how many G's may be involved in a G quadruplex */ bp = (vrna_bp_stack_t *)vrna_alloc(sizeof(vrna_bp_stack_t) * (4 * (1 + length / 2))); vrna_backtrack_from_intervals(vc, bp, bt_stack, 0); ss = vrna_db_from_bp_stack(bp, length); strncpy(structure, ss, length + 1); free(ss); if (base_pair) free(base_pair); base_pair = bp; } return mfe; } PUBLIC void free_arrays(void) { if (backward_compat_compound && backward_compat) { vrna_fold_compound_free(backward_compat_compound); backward_compat_compound = NULL; backward_compat = 0; } } PUBLIC float fold_par(const char *string, char *structure, vrna_param_t *parameters, int is_constrained, int is_circular) { return wrap_fold(string, structure, parameters, is_constrained, is_circular); } PUBLIC float fold(const char *string, char *structure) { return wrap_fold(string, structure, NULL, fold_constrained, 0); } PUBLIC float circfold(const char *string, char *structure) { return wrap_fold(string, structure, NULL, fold_constrained, 1); } PUBLIC void initialize_fold(int length) { /* DO NOTHING */ } PUBLIC void update_fold_params(void) { vrna_md_t md; if (backward_compat_compound && backward_compat) { set_model_details(&md); vrna_params_reset(backward_compat_compound, &md); } } PUBLIC void update_fold_params_par(vrna_param_t *parameters) { vrna_md_t md; if (backward_compat_compound && backward_compat) { if (parameters) { vrna_params_subst(backward_compat_compound, parameters); } else { set_model_details(&md); vrna_params_reset(backward_compat_compound, &md); } } } PUBLIC void export_fold_arrays(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p) { wrap_array_export(f5_p, c_p, fML_p, fM1_p, indx_p, ptype_p); } PUBLIC void export_fold_arrays_par(int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p, vrna_param_t **P_p) { wrap_array_export(f5_p, c_p, fML_p, fM1_p, indx_p, ptype_p); if (backward_compat_compound) *P_p = backward_compat_compound->params; } PUBLIC void export_circfold_arrays(int *Fc_p, int *FcH_p, int *FcI_p, int *FcM_p, int **fM2_p, int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p) { wrap_array_export(f5_p, c_p, fML_p, fM1_p, indx_p, ptype_p); wrap_array_export_circ(Fc_p, FcH_p, FcI_p, FcM_p, fM2_p); } PUBLIC void export_circfold_arrays_par(int *Fc_p, int *FcH_p, int *FcI_p, int *FcM_p, int **fM2_p, int **f5_p, int **c_p, int **fML_p, int **fM1_p, int **indx_p, char **ptype_p, vrna_param_t **P_p) { wrap_array_export(f5_p, c_p, fML_p, fM1_p, indx_p, ptype_p); wrap_array_export_circ(Fc_p, FcH_p, FcI_p, FcM_p, fM2_p); if (backward_compat_compound) *P_p = backward_compat_compound->params; } PUBLIC char * backtrack_fold_from_pair(char *sequence, int i, int j) { char *structure = NULL; unsigned int length = 0; vrna_bp_stack_t *bp = NULL; sect bt_stack[MAXSECTORS]; /* stack of partial structures for backtracking */ if (sequence) { length = strlen(sequence); bp = (vrna_bp_stack_t *)vrna_alloc(sizeof(vrna_bp_stack_t) * (1 + length / 2)); } else { vrna_message_warning("backtrack_fold_from_pair: " "no sequence given"); return NULL; } bt_stack[1].i = i; bt_stack[1].j = j; bt_stack[1].ml = 2; bp[0].i = 0; /* ??? this is set by backtrack anyway... */ vrna_backtrack_from_intervals(backward_compat_compound, bp, bt_stack, 1); structure = vrna_db_from_bp_stack(bp, length); /* backward compatibitlity stuff */ if (base_pair) free(base_pair); base_pair = bp; return structure; } #define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */ #define NEW_NINIO 1 /* new asymetry penalty */ PUBLIC int HairpinE(int size, int type, int si1, int sj1, const char *string) { vrna_param_t *P = backward_compat_compound->params; int energy; energy = (size <= 30) ? P->hairpin[size] : P->hairpin[30] + (int)(P->lxc * log((size) / 30.)); if (tetra_loop) { if (size == 4) { /* check for tetraloop bonus */ char tl[7] = { 0 }, *ts; strncpy(tl, string, 6); if ((ts = strstr(P->Tetraloops, tl))) return P->Tetraloop_E[(ts - P->Tetraloops) / 7]; } if (size == 6) { char tl[9] = { 0 }, *ts; strncpy(tl, string, 8); if ((ts = strstr(P->Hexaloops, tl))) return energy = P->Hexaloop_E[(ts - P->Hexaloops) / 9]; } if (size == 3) { char tl[6] = { 0, 0, 0, 0, 0, 0 }, *ts; strncpy(tl, string, 5); if ((ts = strstr(P->Triloops, tl))) return P->Triloop_E[(ts - P->Triloops) / 6]; if (type > 2) /* neither CG nor GC */ energy += P->TerminalAU; /* penalty for closing AU GU pair IVOO?? * sind dass jetzt beaunuesse oder mahlnuesse (vorzeichen?)*/ return energy; } } energy += P->mismatchH[type][si1][sj1]; return energy; } /*---------------------------------------------------------------------------*/ PUBLIC int oldLoopEnergy(int i, int j, int p, int q, int type, int type_2) { vrna_param_t *P = backward_compat_compound->params; short *S1 = backward_compat_compound->sequence_encoding; /* compute energy of degree 2 loop (stack bulge or interior) */ int n1, n2, m, energy; n1 = p - i - 1; n2 = j - q - 1; if (n1 > n2) { m = n1; n1 = n2; n2 = m; } /* so that n2>=n1 */ if (n2 == 0) { energy = P->stack[type][type_2]; /* stack */ } else if (n1 == 0) { /* bulge */ energy = (n2 <= MAXLOOP) ? P->bulge[n2] : (P->bulge[30] + (int)(P->lxc * log(n2 / 30.))); #if STACK_BULGE1 if (n2 == 1) energy += P->stack[type][type_2]; #endif } else { /* interior loop */ if ((n1 + n2 == 2) && (james_rule)) { /* special case for loop size 2 */ energy = P->int11[type][type_2][S1[i + 1]][S1[j - 1]]; } else { energy = (n1 + n2 <= MAXLOOP) ? (P->internal_loop[n1 + n2]) : (P->internal_loop[30] + (int)(P->lxc * log((n1 + n2) / 30.))); #if NEW_NINIO energy += MIN2(MAX_NINIO, (n2 - n1) * P->ninio[2]); #else m = MIN2(4, n1); energy += MIN2(MAX_NINIO, ((n2 - n1) * P->ninio[m])); #endif energy += P->mismatchI[type][S1[i + 1]][S1[j - 1]] + P->mismatchI[type_2][S1[q + 1]][S1[p - 1]]; } } return energy; } /*--------------------------------------------------------------------------*/ PUBLIC int LoopEnergy(int n1, int n2, int type, int type_2, int si1, int sj1, int sp1, int sq1) { vrna_param_t *P = backward_compat_compound->params; /* compute energy of degree 2 loop (stack bulge or interior) */ int nl, ns, energy; if (n1 > n2) { nl = n1; ns = n2; } else { nl = n2; ns = n1; } if (nl == 0) return P->stack[type][type_2]; /* stack */ if (ns == 0) { /* bulge */ energy = (nl <= MAXLOOP) ? P->bulge[nl] : (P->bulge[30] + (int)(P->lxc * log(nl / 30.))); if (nl == 1) { energy += P->stack[type][type_2]; } else { if (type > 2) energy += P->TerminalAU; if (type_2 > 2) energy += P->TerminalAU; } return energy; } else { /* interior loop */ if (ns == 1) { if (nl == 1) /* 1x1 loop */ return P->int11[type][type_2][si1][sj1]; if (nl == 2) { /* 2x1 loop */ if (n1 == 1) energy = P->int21[type][type_2][si1][sq1][sj1]; else energy = P->int21[type_2][type][sq1][si1][sp1]; return energy; } else { /* 1xn loop */ energy = (nl + 1 <= MAXLOOP) ? (P->internal_loop[nl + 1]) : (P->internal_loop[30] + (int)(P->lxc * log((nl + 1) / 30.))); energy += MIN2(MAX_NINIO, (nl - ns) * P->ninio[2]); energy += P->mismatch1nI[type][si1][sj1] + P->mismatch1nI[type_2][sq1][sp1]; return energy; } } else if (ns == 2) { if (nl == 2) { /* 2x2 loop */ return P->int22[type][type_2][si1][sp1][sq1][sj1]; } else if (nl == 3) { /* 2x3 loop */ energy = P->internal_loop[5] + P->ninio[2]; energy += P->mismatch23I[type][si1][sj1] + P->mismatch23I[type_2][sq1][sp1]; return energy; } } { /* generic interior loop (no else here!)*/ energy = (n1 + n2 <= MAXLOOP) ? (P->internal_loop[n1 + n2]) : (P->internal_loop[30] + (int)(P->lxc * log((n1 + n2) / 30.))); energy += MIN2(MAX_NINIO, (nl - ns) * P->ninio[2]); energy += P->mismatchI[type][si1][sj1] + P->mismatchI[type_2][sq1][sp1]; } } return energy; } #endif
Trap_Gian_A01638108.c
/** * @file Trap_Gian_A01638108.c * @author Giancarlo Franco Carrillo * @brief Trapezoidal aproximation for integral calculation using omp library. * @date 2021-12-3 */ #include <stdio.h> #include <omp.h> #include <math.h> // Function to compute integral #define f(x) sin(x) int main(){ // main variables float k; int i; int lower = 0; int upper = 5; int interval = 10; // step size or delta x float delta = (float)(upper - lower) / interval; // Compute integration values float integration = f(lower) + f(upper); // Number of threas EXPORT NUM_OF_THREADS=x int thread_count = 12; # pragma omp parallel num_threads(thread_count) shared(integration, k) private(i) { #pragma omp for for (i = 1; i <= interval - 1; i++) { k = lower + i * delta; integration = integration + 2 * f(k); } } integration = integration * delta/2; printf("Integral pproximation: %.5f\n", integration); return 0; }
im2collifted.c
#include <stdlib.h> #include "im2collifted.h" void im2collifted(float* x,float* w,int RR,int W,int K,int B,int A,float*output){ float* tmp2 = (float*) calloc(1,(W) * (RR) * sizeof (float)); for (int H10 = 0; H10 < W; H10++) { for (int H11 = 0; H11 < RR; H11++) { if (H10 + H11 < K) { tmp2[(RR) * (H10) + H11] = x[H10 + H11]; } } } float* x1 = tmp2; #pragma omp parallel for for (int H13 = 0; H13 < K; H13++) { for (int H14 = 0; H14 < W; H14++) { for (int H15 = 0; H15 < RR; H15++) { float tmp3 = 0; float tmp4 = 0; tmp4 = w[(((B)) * (H13)) + H15]; float tmp5 = 0; tmp5 = x1[(((RR)) * (H14)) + H15]; tmp3 = tmp4 * tmp5; output[(W) * (H13) + H14] = output[(W) * (H13) + H14] + tmp3; } } } free(tmp2); }
rankmatrix.c
/* This file is part of ParTI!. ParTI! is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ParTI! 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 Lesser General Public License along with ParTI!. If not, see <http://www.gnu.org/licenses/>. */ #include <HiParTI.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> /** * Initialize a new dense rank matrix * * @param mtx a valid pointer to an uninitialized ptiMatrix variable * @param nrows the number of rows * @param ncols the number of columns * * The memory layout of this dense matrix is a flat 2D array, with `ncols` * rounded up to multiples of 8 */ int ptiNewRankMatrix(ptiRankMatrix *mtx, ptiIndex const nrows, ptiElementIndex const ncols) { mtx->nrows = nrows; mtx->ncols = ncols; mtx->cap = nrows != 0 ? nrows : 1; mtx->stride = ((ncols-1)/8+1)*8; #ifdef _ISOC11_SOURCE mtx->values = aligned_alloc(8 * sizeof (ptiValue), mtx->cap * mtx->stride * sizeof (ptiValue)); #elif _POSIX_C_SOURCE >= 200112L { int result = posix_memalign((void **) &mtx->values, 8 * sizeof (ptiValue), mtx->cap * mtx->stride * sizeof (ptiValue)); if(result != 0) { mtx->values = NULL; } } #else mtx->values = malloc(mtx->cap * mtx->stride * sizeof (ptiValue)); #endif pti_CheckOSError(!mtx->values, "RankMtx New"); return 0; } /** * Build a matrix with random number * * @param mtx a pointer to an uninitialized matrix * @param nrows fill the specified number of rows * @param ncols fill the specified number of columns * * The matrix is filled with uniform distributed pseudorandom number in [0, 1] * The random number will have a precision of 31 bits out of 51 bits */ int ptiRandomizeRankMatrix(ptiRankMatrix *mtx, ptiIndex const nrows, ptiElementIndex const ncols) { srand(time(NULL)); for(ptiIndex i=0; i<nrows; ++i) for(ptiElementIndex j=0; j<ncols; ++j) { mtx->values[i * mtx->stride + j] = i + j + 1; //ptiRandomValue(); } return 0; } /** * Fill an existed dense rank matrix with a specified constant * * @param mtx a pointer to a valid matrix * @param val a given value constant * */ int ptiConstantRankMatrix(ptiRankMatrix *mtx, ptiValue const val) { for(ptiIndex i=0; i<mtx->nrows; ++i) for(ptiElementIndex j=0; j<mtx->ncols; ++j) mtx->values[i * mtx->stride + j] = val; return 0; } /** * Shuffle matrix row indices. * * @param[in] mtx matrix to be shuffled * @param[out] map_inds is the renumbering mapping * */ void ptiRankMatrixInverseShuffleIndices(ptiRankMatrix *mtx, ptiIndex * mode_map_inds) { /* Renumber matrix rows */ ptiIndex new_i; ptiValue * tmp_values = malloc(mtx->cap * mtx->stride * sizeof (ptiValue)); for(ptiIndex i=0; i<mtx->nrows; ++i) { new_i = mode_map_inds[i]; for(ptiElementIndex j=0; j<mtx->ncols; ++j) { tmp_values[i * mtx->stride + j] = mtx->values[new_i * mtx->stride + j]; } } free(mtx->values); mtx->values = tmp_values; } /** * Release the memory buffer a dense rank matrix is holding * * @param mtx a pointer to a valid matrix * * By using `ptiFreeMatrix`, a valid matrix would become uninitialized and * should not be used anymore prior to another initialization */ void ptiFreeRankMatrix(ptiRankMatrix *mtx) { free(mtx->values); mtx->nrows = 0; mtx->ncols = 0; mtx->cap = 0; mtx->stride = 0; } /* mats (aTa) only stores upper triangle elements. */ int ptiRankMatrixDotMulSeqTriangle(ptiIndex const mode, ptiIndex const nmodes, ptiRankMatrix ** mats) { ptiIndex const nrows = mats[0]->nrows; ptiElementIndex const ncols = mats[0]->ncols; ptiElementIndex const stride = mats[0]->stride; for(ptiIndex m=1; m<nmodes+1; ++m) { assert(mats[m]->ncols == ncols); assert(mats[m]->nrows == nrows); } ptiValue * ovals = mats[nmodes]->values; #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { ovals[j * stride + i] = 1.0; } } for(ptiIndex m=1; m < nmodes; ++m) { ptiIndex const pm = (mode + m) % nmodes; ptiValue const * vals = mats[pm]->values; #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=i; j < ncols; ++j) { ovals[i * stride + j] *= vals[i * stride + j]; } } } /* Copy upper triangle to lower part */ #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < i; ++j) { ovals[i * stride + j] = ovals[j * stride + i]; } } return 0; } // Row-major int ptiRankMatrix2Norm(ptiRankMatrix * const A, ptiValue * const lambda) { ptiIndex const nrows = A->nrows; ptiElementIndex const ncols = A->ncols; ptiElementIndex const stride = A->stride; ptiValue * const vals = A->values; ptiValue * buffer_lambda; int nthreads = 1; #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiElementIndex j=0; j < ncols; ++j) { lambda[j] = 0.0; } #ifdef HIPARTI_USE_OPENMP #pragma omp parallel { nthreads = omp_get_num_threads(); } buffer_lambda = (ptiValue *)malloc(nthreads * ncols * sizeof(ptiValue)); #endif #ifdef HIPARTI_USE_OPENMP #pragma omp parallel { #pragma omp for schedule(static) for(ptiNnzIndex j=0; j < (ptiNnzIndex)nthreads * ncols; ++j) buffer_lambda[j] = 0.0; int const tid = omp_get_thread_num(); int const nthreads = omp_get_num_threads(); ptiValue * loc_lambda = buffer_lambda + tid * ncols; #pragma omp for for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { loc_lambda[j] += vals[i*stride + j] * vals[i*stride + j]; } } #pragma omp for schedule(static) for(ptiElementIndex j=0; j < ncols; ++j) { for(ptiIndex i=0; i < (ptiIndex)nthreads; ++i) { lambda[j] += buffer_lambda[i*ncols + j]; } } } /* end parallel pragma */ #else for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { lambda[j] += vals[i*stride + j] * vals[i*stride + j]; } } #endif #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiElementIndex j=0; j < ncols; ++j) { lambda[j] = sqrt(lambda[j]); } #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for #endif for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { vals[i*stride + j] /= lambda[j]; } } #ifdef HIPARTI_USE_OPENMP free(buffer_lambda); #endif return 0; } // Row-major int ptiRankMatrixMaxNorm(ptiRankMatrix * const A, ptiValue * const lambda) { ptiIndex const nrows = A->nrows; ptiElementIndex const ncols = A->ncols; ptiElementIndex const stride = A->stride; ptiValue * const vals = A->values; ptiValue * buffer_lambda; int nthreads = 1; #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiElementIndex j=0; j < ncols; ++j) { lambda[j] = 0.0; } #ifdef HIPARTI_USE_OPENMP #pragma omp parallel { nthreads = omp_get_num_threads(); } buffer_lambda = (ptiValue *)malloc(nthreads * ncols * sizeof(ptiValue)); #endif #ifdef HIPARTI_USE_OPENMP #pragma omp parallel { #pragma omp for schedule(static) for(ptiNnzIndex j=0; j < (ptiNnzIndex)nthreads * ncols; ++j) buffer_lambda[j] = 0.0; int const tid = omp_get_thread_num(); int const nthreads = omp_get_num_threads(); ptiValue * loc_lambda = buffer_lambda + tid * ncols; #pragma omp for for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { if(vals[i*stride + j] > loc_lambda[j]) loc_lambda[j] = vals[i*stride + j]; } } #pragma omp for schedule(static) for(ptiElementIndex j=0; j < ncols; ++j) { for(ptiIndex i=0; i < (ptiIndex)nthreads; ++i) { if(buffer_lambda[i*ncols + j] > lambda[j]) lambda[j] = buffer_lambda[i*ncols + j]; } } } /* end parallel pragma */ #else for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { if(vals[i*stride + j] > lambda[j]) lambda[j] = vals[i*stride + j]; } } #endif #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for schedule(static) #endif for(ptiElementIndex j=0; j < ncols; ++j) { if(lambda[j] < 1) lambda[j] = 1; } #ifdef HIPARTI_USE_OPENMP #pragma omp parallel for #endif for(ptiIndex i=0; i < nrows; ++i) { for(ptiElementIndex j=0; j < ncols; ++j) { vals[i*stride + j] /= lambda[j]; } } #ifdef HIPARTI_USE_OPENMP free(buffer_lambda); #endif return 0; } void GetRankFinalLambda( ptiElementIndex const rank, ptiIndex const nmodes, ptiRankMatrix ** mats, ptiValue * const lambda) { ptiValue * tmp_lambda = (ptiValue *) malloc(rank * sizeof(*tmp_lambda)); for(ptiIndex m=0; m < nmodes; ++m) { ptiRankMatrix2Norm(mats[m], tmp_lambda); for(ptiElementIndex r=0; r < rank; ++r) { lambda[r] *= tmp_lambda[r]; } } free(tmp_lambda); }
raytracer.h
#pragma once #include "resource.h" #include <linalg.h> #include <memory> #include <omp.h> #include <random> #include <time.h> using namespace linalg::aliases; namespace cg::renderer { struct ray { ray(float3 position, float3 direction) : position(position) { this->direction = normalize(direction); } float3 position; float3 direction; }; struct payload { float t; float3 bary; cg::color color; }; template<typename VB> struct triangle { triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c); float3 a; float3 b; float3 c; float3 ba; float3 ca; float3 na; float3 nb; float3 nc; float3 ambient; float3 diffuse; float3 emissive; }; template<typename VB> inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c) { a = float3{ vertex_a.x, vertex_a.y, vertex_a.z }; b = float3{ vertex_b.x, vertex_b.y, vertex_b.z }; c = float3{ vertex_c.x, vertex_c.y, vertex_c.z }; ba = b - a; ca = c - a; na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz }; nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz }; nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz }; ambient = { vertex_a.ambient_r, vertex_a.ambient_g, vertex_a.ambient_b, }; diffuse = { vertex_a.diffuse_r, vertex_a.diffuse_g, vertex_a.diffuse_b, }; emissive = { vertex_a.emissive_r, vertex_a.emissive_g, vertex_a.emissive_b, }; } template<typename VB> class aabb { public: void add_triangle(const triangle<VB> triangle); const std::vector<triangle<VB>>& get_triangles() const; bool aabb_test(const ray& ray) const; protected: std::vector<triangle<VB>> triangles; float3 aabb_min; float3 aabb_max; }; struct light { float3 position; float3 color; }; template<typename VB, typename RT> class raytracer { public: raytracer() {}; ~raytracer() {}; void set_render_target(std::shared_ptr<resource<RT>> in_render_target); void clear_render_target(const RT& in_clear_value); void set_viewport(size_t in_width, size_t in_height); void set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer); void build_acceleration_structure(); std::vector<aabb<VB>> acceleration_structures; void ray_generation(float3 position, float3 direction, float3 right, float3 up, float frame_weight = 1); payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const; payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const; std::function<payload(const ray& ray)> miss_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle, size_t depth)> closest_hit_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader = nullptr; float get_random(const int thread_num, float range = 0.1f) const; protected: std::shared_ptr<cg::resource<RT>> render_target; std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer; size_t width = 1920; size_t height = 1080; }; template<typename VB, typename RT> inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target) { render_target = in_render_target; } template<typename VB, typename RT> inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value) { for (size_t i = 0; i < render_target->get_number_of_elements(); i++) { render_target->item(i) = in_clear_value; } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer) { per_shape_vertex_buffer = in_per_shape_vertex_buffer; } template<typename VB, typename RT> inline void raytracer<VB, RT>::build_acceleration_structure() { for (auto& vertex_buffer: per_shape_vertex_buffer) { size_t vertex_id = 0; aabb<VB> aabb; while (vertex_id < vertex_buffer->get_number_of_elements()) { triangle<VB> triangle( vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++) ); aabb.add_triangle(triangle); } acceleration_structures.push_back(aabb); } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height) { width = in_width; height = in_height; } template<typename VB, typename RT> inline void raytracer<VB, RT>::ray_generation( float3 position, float3 direction, float3 right, float3 up, float frame_weight) { for (int x = 0; x < width; x++) { #pragma omp parallel for for (int y = 0; y < height; y++) { float x_jitter = get_random(omp_get_thread_num() + clock()); float y_jitter = get_random(omp_get_thread_num() + clock()); // go from [0; width-1] to [-1; 1] float u = (2.f * x) / static_cast<float>(width - 1) - 1.f; // multiply by aspect ratio u *= static_cast<float>(width) / static_cast<float>(height); float v = (2.f * y) / static_cast<float>(height - 1) - 1.f; // TAA float3 ray_dir = direction + (u) * right - (v) * up; ray ray(position, ray_dir); payload payload = trace_ray(ray, 5); cg::color accumed = cg::color::from_float3(render_target->item(x, y).to_float3()); float fw = frame_weight; float ifw = 1.f - frame_weight; cg::color result_color{ (accumed.r * ifw + payload.color.r * fw), (accumed.g * ifw + payload.color.g * fw), (accumed.b * ifw + payload.color.b * fw)}; // SSAA /* float3 ray_dir = direction + u * right - v * up; float u_delta = .5f / static_cast<float>(width - 1); u_delta *= static_cast<float>(width) / static_cast<float>(height); float v_delta = .5f / static_cast<float>(height - 1); ray ray0(position, ray_dir); payload payload0 = trace_ray(ray0, 1); ray ray1(position, ray_dir + u_delta * right); payload payload1 = trace_ray(ray1, 1); ray ray2(position, ray_dir - v_delta * up); payload payload2 = trace_ray(ray2, 1); ray ray3(position, ray_dir + u_delta * right - v_delta * up); payload payload3 = trace_ray(ray3, 1); cg::color result_color{ (payload0.color.r + payload1.color.r + payload2.color.r + payload3.color.r) / 4.f, (payload0.color.g + payload1.color.g + payload2.color.g + payload3.color.g) / 4.f, (payload0.color.b + payload1.color.b + payload2.color.b + payload3.color.b) / 4.f };*/ render_target->item(x, y) = RT::from_color(result_color); } } } template<typename VB, typename RT> inline payload raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const { if (depth == 0) return miss_shader(ray); payload closest_hit_payload = {}; closest_hit_payload.t = max_t; const triangle<VB>* closest_triangle = nullptr; for (auto& aabb : acceleration_structures) { if (aabb.aabb_test(ray)) { for (auto& triangle : aabb.get_triangles()) { payload payload = intersection_shader(triangle, ray); if (payload.t > min_t && payload.t < closest_hit_payload.t) { closest_hit_payload = payload; closest_triangle = &triangle; if (any_hit_shader) return any_hit_shader(ray, payload, triangle); } } } } if (closest_hit_payload.t < max_t) { if (closest_hit_shader) return closest_hit_shader(ray, closest_hit_payload, *closest_triangle, depth - 1); } return miss_shader(ray); } template<typename VB, typename RT> inline payload raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const { payload payload{}; payload.t = -1.f; float3 pvec = cross(ray.direction, triangle.ca); float det = dot(triangle.ba, pvec); if (det > -1e-8 && det < 1e-8) return payload; float inv_det = 1.f / det; float3 tvec = ray.position - triangle.a; float u = dot(tvec, pvec) * inv_det; if (u < 0.f || u > 1.f) return payload; float3 qvec = cross(tvec, triangle.ba); float v = dot(ray.direction, qvec) * inv_det; if (v < 0.f || u + v > 1.f) return payload; payload.t = dot(triangle.ca, qvec) * inv_det; payload.bary = float3{ 1.f - u - v, u, v }; return payload; } template<typename VB, typename RT> inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const { static std::default_random_engine generator(thread_num); static std::normal_distribution<float> distribution(0.f, range); return distribution(generator); } template<typename VB> inline void aabb<VB>::add_triangle(const triangle<VB> triangle) { if (triangles.empty()) { aabb_min = aabb_max = triangle.a; } triangles.push_back(triangle); aabb_max = max(triangle.a, aabb_max); aabb_max = max(triangle.b, aabb_max); aabb_max = max(triangle.c, aabb_max); aabb_min = min(triangle.a, aabb_min); aabb_min = min(triangle.b, aabb_min); aabb_min = min(triangle.c, aabb_min); } template<typename VB> inline const std::vector<triangle<VB>>& aabb<VB>::get_triangles() const { return triangles; } template<typename VB> inline bool aabb<VB>::aabb_test(const ray& ray) const { float3 inv_ray_dir = float3(1.f) / ray.direction; float3 t0 = (aabb_max - ray.position) * inv_ray_dir; float3 t1 = (aabb_min - ray.position) * inv_ray_dir; float3 tmin = min(t0, t1); float3 tmax = max(t0, t1); return maxelem(tmin) <= minelem(tmax); } } // namespace cg::renderer
GB_unaryop__lnot_uint16_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint16_fp64 // op(A') function: GB_tran__lnot_uint16_fp64 // C type: uint16_t // A type: double // cast: uint16_t cij ; GB_CAST_UNSIGNED(cij,aij,16) // unaryop: cij = !(aij != 0) #define GB_ATYPE \ double #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ uint16_t z ; GB_CAST_UNSIGNED(z,x,16) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT16 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint16_fp64 ( uint16_t *restrict Cx, const double *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint16_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
task_codegen.c
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -x c -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s // RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -x c -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s // SIMD-ONLY0-NOT: {{__kmpc|__tgt}} // expected-no-diagnostics #ifndef HEADER #define HEADER void foo(); // CHECK-LABEL: @main int main() { // CHECK: call i32 @__kmpc_global_thread_num( // CHECK: call i8* @__kmpc_omp_task_alloc( // CHECK: call i32 @__kmpc_omp_task( #pragma omp task { #pragma omp taskgroup { #pragma omp task foo(); } } // CHECK: ret i32 0 return 0; } // CHECK: call void @__kmpc_taskgroup( // CHECK: call i8* @__kmpc_omp_task_alloc( // CHECK: call i32 @__kmpc_omp_task( // CHECK: call void @__kmpc_end_taskgroup( #endif
uts_shm.c
/* * ---- The Unbalanced Tree Search (UTS) Benchmark ---- * * Copyright (c) 2010 See AUTHORS file for copyright holders * * This file is part of the unbalanced tree search benchmark. This * project is licensed under the MIT Open Source license. See the LICENSE * file for copyright and licensing information. * * UTS is a collaborative project between researchers at the University of * Maryland, the University of North Carolina at Chapel Hill, and the Ohio * State University. See AUTHORS file for more information. * * One each node, a set of MAX_NUM_THREADS steal stacks is allocated in the * symmetric heap. The shmem_my_pe()-th member of this set is the stack * associated with this PE, which is primarily a set of node slots (Node) that * is the backing data of the stack with length MAXSTACKDEPTH and a top pointer * that is the index of the lowest empty slot in the stack. The stack * for PE 0 is initialized with a single Node before execution really starts. * * Each stack for each PE is separated in to three sections: the local section, * the non-local and non-stolen section, and the non-local and stolen section. * The non-local and stolen section is at the base, from index 0 to * ss.sharedStart. This region represents the locally created nodes that have * been stolen from the current PE by another PE. The non-local and non-stolen * section goes from ss.sharedStart to ss.local. This section contains nodes * that were locally created and are eligible for stealing, but have not been * stolen yet. These nodes may also be reclaimed in to the local section by * this PE if it needs more work. The local section is above that, from * ss.local to ss.top and contains locally created work that only this PE has * access to. If work-stealing is enabled and the size of the local section is * too big (as defined by chunkSize), then the local region is reduced by * incrementing ss.local to allow other PEs to steal work from this PE. * * During the parallel tree search, we loop until there are no more local nodes * left. Every time we visit a node we generate a certain number of children * for that node and push each of them on to the stack. Once we run out of * local work, we try to acquire locally-created work from the non-local region * by decrementing local (ss_acquire). If that fails, we then must try to find * a remote PE to steal from and grab a chunk of nodes from it using OpenSHMEM * copies (ss_steal) and placing them on the local stack of our PE. If this * succeeds, we loop back around to processing these nodes. * * If we are unable to find work locally or remotely, we enter a cancellable * barrier that waits for all PEs to enter it. This barrier is cancelled if any * PEs release nodes for stealing. If the barrier completes successfully with * all nodes having entered it, the search exits. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "uts.h" /*********************************************************** * * * Compiler Type (these flags are set by at compile time) * * (default) ANSI C compiler - sequential execution * * (_OPENMP) OpenMP enabled C compiler * * (__UPC__) UPC compiler * * (_SHMEM) Cray Shmem * * (__PTHREADS__) Pthreads multithreaded execution * * * ***********************************************************/ /**** OpenMP Definitions ****/ #ifdef _OPENMP #include <omp.h> #define PARALLEL 1 #define COMPILER_TYPE 1 #define SHARED #define SHARED_INDEF #define VOLATILE volatile #define MAX_THREADS 32 #define LOCK_T omp_lock_t #define GET_NUM_THREADS omp_get_num_threads() #define GET_THREAD_NUM omp_get_thread_num() #define SET_LOCK(zlk) omp_set_lock(zlk) #define UNSET_LOCK(zlk) omp_unset_lock(zlk) #define INIT_LOCK(zlk) zlk=omp_global_lock_alloc() #define INIT_SINGLE_LOCK(zlk) zlk=omp_global_lock_alloc() #define SMEMCPY memcpy #define ALLOC malloc #define BARRIER // OpenMP helper function to match UPC lock allocation semantics omp_lock_t * omp_global_lock_alloc() { omp_lock_t *lock = (omp_lock_t *) malloc(sizeof(omp_lock_t) + 128); omp_init_lock(lock); return lock; } /**** UPC Definitions ****/ #elif defined(__UPC__) #include <upc.h> #define PARALLEL 1 #define COMPILER_TYPE 2 #define SHARED shared #define SHARED_INDEF shared [0] #define VOLATILE strict #define MAX_THREADS (THREADS) #define LOCK_T upc_lock_t #define GET_NUM_THREADS (THREADS) #define GET_THREAD_NUM (MYTHREAD) #define SET_LOCK(zlk) upc_lock(zlk) #define UNSET_LOCK(zlk) upc_unlock(zlk) #define INIT_LOCK(zlk) zlk=upc_global_lock_alloc() #define INIT_SINGLE_LOCK(zlk) zlk=upc_all_lock_alloc() #define SMEMCPY upc_memget #define ALLOC upc_alloc #define BARRIER upc_barrier; /**** Shmem Definitions ****/ #elif defined(_SHMEM) #include <shmem.h> #define PARALLEL 1 #define COMPILER_TYPE 3 #define SHARED #define SHARED_INDEF #define VOLATILE volatile #define MAX_THREADS 1024 #define LOCK_T long #define GET_NUM_THREADS shmem_n_pes() #define GET_THREAD_NUM shmem_my_pe() #define SET_LOCK(zlk) shmem_set_lock(zlk) #define UNSET_LOCK(zlk) shmem_clear_lock(zlk) #define INIT_LOCK(zlk) zlk = shmem_global_lock_alloc() #define INIT_SINGLE_LOCK(zlk) zlk = shmem_global_lock_alloc() #define SMEMCPY shmem_getmem // Shmem's get has different semantics from memcpy(): // void shmem_getmem(void *target, const void *source, size_t len, int pe) #define ALLOC shmem_malloc #define BARRIER shmem_barrier_all(); // Shmem helper function to match UPC lock allocation semantics LOCK_T * shmem_global_lock_alloc() { LOCK_T *lock = (LOCK_T *) shmem_malloc(sizeof(LOCK_T)); *lock = 0; shmem_barrier_all(); return lock; } #define GET(target,source,from_id) shmem_int_get(&(target),&(source),1,from_id) #define PUT(target,source,to_id) shmem_int_put(&(target),&(source),1,to_id) #define PUT_ALL(a,b) \ do { \ int _iter, _node; \ for (_iter = 1; _iter < GET_NUM_THREADS; _iter++) { \ _node = (GET_THREAD_NUM + _iter) % GET_NUM_THREADS; \ shmem_int_put((int *)&a,(int *)&b,1,_node); \ } \ } while(0) /**** Pthreads Definitions ****/ #elif defined(__PTHREADS__) #include <pthread.h> #define PARALLEL 1 #define COMPILER_TYPE 4 #define SHARED #define SHARED_INDEF #define VOLATILE volatile #define MAX_THREADS 128 #define LOCK_T pthread_mutex_t #define GET_NUM_THREADS pthread_num_threads #define GET_THREAD_NUM *(int*)pthread_getspecific(pthread_thread_num) #define SET_LOCK(zlk) pthread_mutex_lock(zlk) #define UNSET_LOCK(zlk) pthread_mutex_unlock(zlk) #define INIT_LOCK(zlk) zlk = pthread_global_lock_alloc() #define INIT_SINGLE_LOCK(zlk) zlk = pthread_global_lock_alloc() #define SMEMCPY memcpy #define ALLOC malloc #define BARRIER int pthread_num_threads = 1; // Command line parameter - default to 1 pthread_key_t pthread_thread_num; // Key to store each thread's ID /* helper function to match UPC lock allocation semantics */ LOCK_T * pthread_global_lock_alloc() { LOCK_T *lock = (LOCK_T *) malloc(sizeof(LOCK_T)); pthread_mutex_init(lock, NULL); return lock; } /**** Default Sequential Definitions ****/ #else #define PARALLEL 0 #define COMPILER_TYPE 0 #define SHARED #define SHARED_INDEF #define VOLATILE #define MAX_THREADS 1 #define LOCK_T void #define GET_NUM_THREADS 1 #define GET_THREAD_NUM 0 #define SET_LOCK(zlk) #define UNSET_LOCK(zlk) #define INIT_LOCK(zlk) #define INIT_SINGLE_LOCK(zlk) #define SMEMCPY memcpy #define ALLOC malloc #define BARRIER #endif /* END Par. Model Definitions */ /*********************************************************** * Parallel execution parameters * ***********************************************************/ int doSteal = PARALLEL; // 1 => use work stealing int chunkSize = 20; // number of nodes to move to/from shared area int cbint = 64; // Cancellable barrier polling interval int pollint = 1; // BUPC Polling interval #ifdef __BERKELEY_UPC__ /* BUPC nonblocking I/O Handles */ bupc_handle_t cb_handle = BUPC_COMPLETE_HANDLE; const int local_cb_cancel = 1; #endif /*********************************************************** * Tree statistics (if selected via UTS_STAT) * * compute overall size and imbalance metrics * * and histogram size and imbalance per level * ***********************************************************/ #ifdef UTS_STAT /* Check that we are not being asked to compile parallel with stats. * Parallel stats collection is presently not supported. */ #if PARALLEL #error "ERROR: Parallel stats collection is not supported!" #endif #define MAXHISTSIZE 2000 // max tree depth in histogram int stats = 1; int unbType = 1; int maxHeight = 0; // maximum depth of tree double maxImb = 0; // maximum imbalance double minImb = 1; double treeImb =-1; // Overall imbalance, undefined int hist[MAXHISTSIZE+1][2]; // average # nodes per level double unbhist[MAXHISTSIZE+1][3]; // average imbalance per level int *rootSize; // size of the root's children double *rootUnb; // imbalance of root's children /* Tseng statistics */ int totalNodes = 0; double imb_max = 0; // % of work in largest child (ranges from 100/n to 100%) double imb_avg = 0; double imb_devmaxavg = 0; // ( % of work in largest child ) - ( avg work ) double imb_normdevmaxavg = 0; // ( % of work in largest child ) - ( avg work ) / ( 100% - avg work ) #else int stats = 0; int unbType = -1; #endif /*********************************************************** * Execution Tracing * ***********************************************************/ #define SS_WORK 0 #define SS_SEARCH 1 #define SS_IDLE 2 #define SS_OVH 3 #define SS_CBOVH 4 #define SS_NSTATES 5 /* session record for session visualization */ struct sessionRecord_t { double startTime, endTime; }; typedef struct sessionRecord_t SessionRecord; /* steal record for steal visualization */ struct stealRecord_t { long int nodeCount; /* count nodes generated during the session */ int victimThread; /* thread from which we stole the work */ }; typedef struct stealRecord_t StealRecord; /* Store debugging and trace data */ struct metaData_t { SessionRecord sessionRecords[SS_NSTATES][20000]; /* session time records */ StealRecord stealRecords[20000]; /* steal records */ }; typedef struct metaData_t MetaData; /* holds text string for debugging info */ char debug_str[1000]; /*********************************************************** * StealStack types * ***********************************************************/ #define MAXSTACKDEPTH 500000 /* stack of nodes */ struct stealStack_t { int stackSize; /* total space avail (in number of elements) */ int workAvail; /* elements available for stealing */ int sharedStart; /* index of start of shared portion of stack */ int local; /* index of start of local portion */ int top; /* index of stack top */ int maxStackDepth; /* stack stats */ int nNodes, maxTreeDepth; /* tree stats */ int nLeaves; int nAcquire, nRelease, nSteal, nFail; /* steal stats */ int wakeups, falseWakeups, nNodes_last; double time[SS_NSTATES], timeLast; /* perf measurements */ int entries[SS_NSTATES], curState; LOCK_T * stackLock; /* lock for manipulation of shared portion */ Node * stack; /* addr of actual stack of nodes in local addr space */ SHARED_INDEF Node * stack_g; /* addr of same stack in global addr space */ #ifdef TRACE MetaData * md; /* meta data used for debugging and tracing */ #endif }; typedef struct stealStack_t StealStack; typedef SHARED StealStack * SharedStealStackPtr; /*********************************************************** * Global shared state * ***********************************************************/ // shared access to each thread's stealStack SHARED SharedStealStackPtr stealStack[MAX_THREADS]; // termination detection VOLATILE SHARED int cb_cancel; VOLATILE SHARED int cb_count; VOLATILE SHARED int cb_done; LOCK_T * cb_lock; SHARED double startTime[MAX_THREADS]; /*********************************************************** * UTS Implementation Hooks * ***********************************************************/ // Return a string describing this implementation char * impl_getName() { char * name[] = {"Sequential C", "C/OpenMP", "UPC", "SHMEM", "PThreads"}; return name[COMPILER_TYPE]; } // construct string with all parameter settings int impl_paramsToStr(char *strBuf, int ind) { ind += sprintf(strBuf+ind, "Execution strategy: "); if (PARALLEL) { ind += sprintf(strBuf+ind, "Parallel search using %d threads\n", GET_NUM_THREADS); if (doSteal) { ind += sprintf(strBuf+ind, " Load balance by work stealing, chunk size = %d nodes\n",chunkSize); ind += sprintf(strBuf+ind, " CBarrier Interval: %d\n", cbint); ind += sprintf(strBuf+ind, " Polling Interval: %d\n", pollint); } else ind += sprintf(strBuf+ind, " No load balancing.\n"); } else ind += sprintf(strBuf+ind, "Iterative sequential search\n"); return ind; } int impl_parseParam(char *param, char *value) { int err = 0; // Return 0 on a match, nonzero on an error switch (param[1]) { #if (PARALLEL == 1) case 'c': chunkSize = atoi(value); break; case 's': doSteal = atoi(value); if (doSteal != 1 && doSteal != 0) err = 1; break; case 'i': cbint = atoi(value); break; #ifdef __BERKELEY_UPC__ case 'I': pollint = atoi(value); break; #endif #ifdef __PTHREADS__ case 'T': pthread_num_threads = atoi(value); if (pthread_num_threads > MAX_THREADS) { printf("Warning: Requested threads > MAX_THREADS. Truncated to %d threads\n", MAX_THREADS); pthread_num_threads = MAX_THREADS; } break; #endif #else /* !PARALLEL */ #ifdef UTS_STAT case 'u': unbType = atoi(value); if (unbType > 2) { err = 1; break; } if (unbType < 0) stats = 0; else stats = 1; break; #endif #endif /* PARALLEL */ default: err = 1; break; } return err; } void impl_helpMessage() { if (PARALLEL) { printf(" -s int zero/nonzero to disable/enable work stealing\n"); printf(" -c int chunksize for work stealing\n"); printf(" -i int set cancellable barrier polling interval\n"); #ifdef __BERKELEY_UPC__ printf(" -I int set working bupc_poll() interval\n"); #endif #ifdef __PTHREADS__ printf(" -T int set number of threads\n"); #endif } else { #ifdef UTS_STAT printf(" -u int unbalance measure (-1: none; 0: min/size; 1: min/n; 2: max/n)\n"); #else printf(" none.\n"); #endif } } void impl_abort(int err) { #if defined(__UPC__) upc_global_exit(err); #elif defined(_OPENMP) exit(err); #elif defined(_SHMEM) exit(err); #else exit(err); #endif } /*********************************************************** * * * FUNCTIONS * * * ***********************************************************/ /* * StealStack * Stack of nodes with sharing at the bottom of the stack * and exclusive access at the top for the "owning" thread * which has affinity to the stack's address space. * * * All operations on the shared portion of the stack * must be guarded using the stack-specific lock. * * Elements move between the shared and exclusive * portion of the stack solely under control of the * owning thread. (ss_release and ss_acquire) * * workAvail is the count of elements in the shared * portion of the stack. It may be read without * acquiring the stack lock, but of course its value * may not be acurate. Idle threads read workAvail in * this speculative fashion to minimize overhead to * working threads. * * Elements can be stolen from the bottom of the shared * portion by non-owning threads. The values are * reserved under lock by the stealing thread, and then * copied without use of the lock (currently space for * reserved values is never reclaimed). * */ /* restore stack to empty state */ void ss_mkEmpty(StealStack *s) { SET_LOCK(s->stackLock); s->sharedStart = 0; s->local = 0; s->top = 0; s->workAvail = 0; UNSET_LOCK(s->stackLock); } /* fatal error */ void ss_error(char *str) { printf("*** [Thread %i] %s\n",GET_THREAD_NUM, str); exit(4); } /* initialize the stack */ void ss_init(StealStack *s, int nelts) { int nbytes = nelts * sizeof(Node); if (debug & 1) printf("Thread %d intializing stealStack %p, sizeof(Node) = %X\n", GET_THREAD_NUM, s, (int)(sizeof(Node))); // allocate stack in shared addr space with affinity to calling thread // and record local addr for efficient access in sequel if(s->stack_g==NULL){ s->stack_g = (SHARED_INDEF Node *) ALLOC (nbytes); s->stack = (Node *) s->stack_g; if (s->stack == NULL) { printf("Request for %d bytes for stealStack on thread %d failed\n", nbytes, GET_THREAD_NUM); ss_error("ss_init: unable to allocate space for stealstack"); } } #ifdef TRACE s->md = (MetaData *) ALLOC (sizeof(MetaData)); if (s->md == NULL) ss_error("ss_init: out of memory"); #endif INIT_LOCK(s->stackLock); if (debug & 1) printf("Thread %d init stackLock %p\n", GET_THREAD_NUM, (void *) s->stackLock); s->stackSize = nelts; s->nNodes = 0; s->maxStackDepth = 0; s->maxTreeDepth = 0; s->nLeaves = 0; s->nAcquire = 0; s->nRelease = 0; s->nSteal = 0; s->nFail = 0; s->wakeups = 0; s->falseWakeups = 0; s->nNodes_last = 0; ss_mkEmpty(s); } /* local push */ void ss_push(StealStack *s, Node *c) { if (s->top >= s->stackSize) ss_error("ss_push: overflow"); if (debug & 1) printf("ss_push: Thread %d, posn %d: node %s [%d]\n", GET_THREAD_NUM, s->top, rng_showstate(c->state.state, debug_str), c->height); memcpy(&(s->stack[s->top]), c, sizeof(Node)); s->top++; s->nNodes++; s->maxStackDepth = (s->top > s->maxStackDepth ? s->top : s->maxStackDepth); s->maxTreeDepth = (s->maxTreeDepth > c->height ? s->maxTreeDepth : c->height); } /* local top: get local addr of node at top */ Node * ss_top(StealStack *s) { Node *r; if (s->top <= s->local) ss_error("ss_top: empty local stack"); r = &(s->stack[(s->top) - 1]); if (debug & 1) printf("ss_top: Thread %d, posn %d: node %s [%d] nchild = %d\n", GET_THREAD_NUM, s->top - 1, rng_showstate(r->state.state, debug_str), r->height, r->numChildren); return r; } /* local pop */ void ss_pop(StealStack *s) { Node *r; if (s->top <= s->local) ss_error("ss_pop: empty local stack"); s->top--; r = &(s->stack[s->top]); if (debug & 1) printf("ss_pop: Thread %d, posn %d: node %s [%d] nchild = %d\n", GET_THREAD_NUM, s->top, rng_showstate(r->state.state, debug_str), r->height, r->numChildren); } /* local top position: stack index of top element */ int ss_topPosn(StealStack *s) { if (s->top <= s->local) ss_error("ss_topPosn: empty local stack"); return s->top - 1; } /* local depth */ int ss_localDepth(StealStack *s) { return (s->top - s->local); } /* release k values from bottom of local stack */ void ss_release(StealStack *s, int k) { SET_LOCK(s->stackLock); if (s->top - s->local >= k) { s->local += k; s->workAvail += k; s->nRelease++; } else ss_error("ss_release: do not have k vals to release"); UNSET_LOCK(s->stackLock); } /* move k values from top of shared stack into local stack * return false if k vals are not avail on shared stack */ int ss_acquire(StealStack *s, int k) { int avail; SET_LOCK(s->stackLock); avail = s->local - s->sharedStart; if (avail >= k) { s->local -= k; s->workAvail -= k; s->nAcquire++; } UNSET_LOCK(s->stackLock); return (avail >= k); } /* steal k values from shared portion of victim thread's stealStack * onto local portion of current thread's stealStack. * return false if k vals are not avail in victim thread */ int ss_steal(StealStack *s, int victim, int k) { int victimLocal, victimShared, victimWorkAvail; int ok; if (s->sharedStart != s->top) ss_error("ss_steal: thief attempts to steal onto non-empty stack"); if (s->top + k >= s->stackSize) ss_error("ss_steal: steal will overflow thief's stack"); /* lock victim stack and try to reserve k elts */ if (debug & 32) printf("Thread %d wants SS %d\n", GET_THREAD_NUM, victim); SET_LOCK(stealStack[victim]->stackLock); #ifdef _SHMEM /* Get remote steal stack */ #ifdef TRACE SMEMCPY(stealStack[victim], stealStack[victim], sizeof(StealStack)-4*sizeof(void*), victim); #else SMEMCPY(stealStack[victim], stealStack[victim], sizeof(StealStack)-3*sizeof(void*), victim); #endif #endif if (debug & 32) printf("Thread %d acquires SS %d\n", GET_THREAD_NUM, victim); victimLocal = stealStack[victim]->local; victimShared = stealStack[victim]->sharedStart; victimWorkAvail = stealStack[victim]->workAvail; if (victimLocal - victimShared != victimWorkAvail) ss_error("ss_steal: stealStack invariant violated"); ok = victimWorkAvail >= k; if (ok) { /* reserve a chunk */ stealStack[victim]->sharedStart = victimShared + k; stealStack[victim]->workAvail = victimWorkAvail - k; #ifdef _SHMEM // FIXME: These transfers ought to be combined. They can't be // though because the data protected by the stacklock is not // the only data in the StealStack structure. PUT(stealStack[victim]->sharedStart, stealStack[victim]->sharedStart, victim); PUT(stealStack[victim]->workAvail, stealStack[victim]->workAvail, victim); #endif } UNSET_LOCK(stealStack[victim]->stackLock); if (debug & 32) printf("Thread %d releases SS %d\n", GET_THREAD_NUM, victim); /* if k elts reserved, move them to local portion of our stack */ if (ok) { SHARED_INDEF Node * victimStackBase = stealStack[victim]->stack_g; SHARED_INDEF Node * victimSharedStart = victimStackBase + victimShared; #ifdef _SHMEM SMEMCPY(&(s->stack[s->top]), victimSharedStart, k * sizeof(Node), victim); #else SMEMCPY(&(s->stack[s->top]), victimSharedStart, k * sizeof(Node)); #endif s->nSteal++; if (debug & 4) { int i; for (i = 0; i < k; i ++) { Node * r = &(s->stack[s->top + i]); printf("ss_steal: Thread %2d posn %d (steal #%d) receives %s [%d] from thread %d posn %d (%p)\n", GET_THREAD_NUM, s->top + i, s->nSteal, rng_showstate(r->state.state, debug_str), r->height, victim, victimShared + i, (void *) victimSharedStart); } } s->top += k; #ifdef TRACE /* update session record of theif */ s->md->stealRecords[s->entries[SS_WORK]].victimThread = victim; #endif } else { s->nFail++; if (debug & 4) { printf("Thread %d failed to steal %d nodes from thread %d, ActAv = %d, sh = %d, loc =%d\n", GET_THREAD_NUM, k, victim, victimWorkAvail, victimShared, victimLocal); } } return (ok); } /* search other threads for work to steal */ int findwork(int k) { int i,v; for (i = 1; i < GET_NUM_THREADS; i++) { v = (GET_THREAD_NUM + i) % GET_NUM_THREADS; #ifdef _SHMEM GET(stealStack[v]->workAvail, stealStack[v]->workAvail, v); #endif if (stealStack[v]->workAvail >= k) return v; } return -1; } /** * Tracing functions * Track changes in the search state for offline analysis. **/ void ss_initState(StealStack *s) { int i; s->timeLast = uts_wctime(); for (i = 0; i < SS_NSTATES; i++) { s->time[i] = 0.0; s->entries[i] = 0; } s->curState = SS_IDLE; if (debug & 8) printf("Thread %d start state %d (t = %f)\n", GET_THREAD_NUM, s->curState, s->timeLast); } void ss_setState(StealStack *s, int state){ double time; if (state < 0 || state >= SS_NSTATES) ss_error("ss_setState: thread state out of range"); if (state == s->curState) return; time = uts_wctime(); s->time[s->curState] += time - s->timeLast; #ifdef TRACE /* close out last session record */ s->md->sessionRecords[s->curState][s->entries[s->curState] - 1].endTime = time; if (s->curState == SS_WORK) { s->md->stealRecords[s->entries[SS_WORK] - 1].nodeCount = s->nNodes - s->md->stealRecords[s->entries[SS_WORK] - 1].nodeCount; } /* initialize new session record */ s->md->sessionRecords[state][s->entries[state]].startTime = time; if (state == SS_WORK) { s->md->stealRecords[s->entries[SS_WORK]].nodeCount = s->nNodes; } #endif s->entries[state]++; s->timeLast = time; s->curState = state; if(debug & 8) printf("Thread %d enter state %d [#%d] (t = %f)\n", GET_THREAD_NUM, state, s->entries[state], time); } #ifdef UTS_STAT /* * Statistics, * : number of nodes per level * : imbalanceness of nodes per level * */ void initHist() { int i; for (i=0; i<MAXHISTSIZE; i++){ hist[i][0]=0; hist[i][1]=0; unbhist[i][1]=1; unbhist[i][2]=0; } } void updateHist(Node* c, double unb) { if (c->height<MAXHISTSIZE){ hist[c->height][1]++; hist[c->height][0]+=c->numChildren; unbhist[c->height][0]+=unb; if (unbhist[c->height][1]>unb) unbhist[c->height][1]=unb; if (unbhist[c->height][2]<unb) unbhist[c->height][2]=unb; } else { hist[MAXHISTSIZE][1]++; hist[MAXHISTSIZE][0]+=c->numChildren; } } void showHist(FILE *fp) { int i; fprintf(fp, "depth\tavgNumChildren\t\tnumChildren\t imb\t maxImb\t minImb\t\n"); for (i=0; i<MAXHISTSIZE; i++){ if ((hist[i][0]!=0)&&(hist[i][1]!=0)) fprintf(fp, "%d\t%f\t%d\t %lf\t%lf\t%lf\n", i, (double)hist[i][0]/hist[i][1], hist[i][0], unbhist[i][0]/hist[i][1], unbhist[i][1], unbhist[i][2]); } } double getImb(Node *c) { int i=0; double avg=.0, tmp=.0; double unb=0.0; avg=(double)c->sizeChildren/c->numChildren; for (i=0; i<c->numChildren; i++){ if ((type==BIN)&&(c->pp==NULL)) { if (unbType<2) tmp=min((double)rootSize[i]/avg, avg/(double)rootSize[i]); else tmp=max((double)rootSize[i]/avg, avg/(double)rootSize[i]); if (unbType>0) unb+=tmp*rootUnb[i]; else unb+=tmp*rootUnb[i]*rootSize[i]; } else{ if (unbType<2) tmp=min((double)c->size[i]/avg, avg/(double)c->size[i]); else tmp=max((double)c->size[i]/avg, avg/(double)c->size[i]); if (unbType>0) unb+=tmp*c->unb[i]; else unb+=tmp*c->unb[i]*c->size[i]; } } if (unbType>0){ if (c->numChildren>0) unb=unb/c->numChildren; else unb=1.0; } else { if (c->sizeChildren>1) unb=unb/c->sizeChildren; else unb=1.0; } if ((debug & 1) && unb>1) printf("unb>1%lf\t%d\n", unb, c->numChildren); return unb; } void getImb_Tseng(Node *c) { double t_max, t_avg, t_devmaxavg, t_normdevmaxavg; if (c->numChildren==0) { t_avg =0; t_max =0; } else { t_max = (double)c->maxSizeChildren/(c->sizeChildren-1); t_avg = (double)1/c->numChildren; } t_devmaxavg = t_max-t_avg; if (debug & 1) printf("max\t%lf, %lf, %d, %d, %d\n", t_max, t_avg, c->maxSizeChildren, c->sizeChildren, c->numChildren); if (1-t_avg==0) t_normdevmaxavg = 1; else t_normdevmaxavg = (t_max-t_avg)/(1-t_avg); imb_max += t_max; imb_avg += t_avg; imb_devmaxavg += t_devmaxavg; imb_normdevmaxavg +=t_normdevmaxavg; } void updateParStat(Node *c) { double unb; totalNodes++; if (maxHeight<c->height) maxHeight=c->height; unb=getImb(c); maxImb=max(unb, maxImb); minImb=min(unb, minImb); updateHist(c, unb); getImb_Tseng(c); if (c->pp!=NULL){ if ((c->type==BIN)&&(c->pp->pp==NULL)){ rootSize[c->pp->ind]=c->sizeChildren; rootUnb[c->pp->ind]=unb; } else{ c->pp->size[c->pp->ind]=c->sizeChildren; c->pp->unb[c->pp->ind]=unb; } /* update statistics per node*/ c->pp->ind++; c->pp->sizeChildren+=c->sizeChildren; if (c->pp->maxSizeChildren<c->sizeChildren) c->pp->maxSizeChildren=c->sizeChildren; } else treeImb = unb; } #endif /* * Tree Implementation * */ void initNode(Node * child) { child->type = -1; child->height = -1; child->numChildren = -1; // not yet determined #ifdef UTS_STAT if (stats){ int i; child->ind = 0; child->sizeChildren = 1; child->maxSizeChildren = 0; child->pp = NULL; for (i = 0; i < MAXNUMCHILDREN; i++){ child->size[i] = 0; child->unb[i] = 0.0; } } #endif } void initRootNode(Node * root, int type) { uts_initRoot(root, type); #ifdef TRACE stealStack[0]->md->stealRecords[0].victimThread = 0; // first session is own "parent session" #endif #ifdef UTS_STAT if (stats){ int i; root->ind = 0; root->sizeChildren = 1; root->maxSizeChildren = 1; root->pp = NULL; if (type != BIN){ for (i=0; i<MAXNUMCHILDREN; i++){ root->size[i] = 0; root->unb[i] =.0; } } else { int rbf = (int) ceil(b_0); rootSize = malloc(rbf*sizeof(int)); rootUnb = malloc(rbf*sizeof(double)); for (i = 0; i < rbf; i++) { rootSize[i] = 0; rootUnb[i] = 0.0; } } } #endif } // forward decl void releaseNodes(StealStack *ss); /* * Generate all children of the parent * * details depend on tree type, node type and shape function * */ void genChildren(Node * parent, Node * child, StealStack * ss) { int parentHeight = parent->height; int numChildren, childType; numChildren = uts_numChildren(parent); childType = uts_childType(parent); // record number of children in parent parent->numChildren = numChildren; if (debug & 2) { printf("Gen: Thread %d, posn %2d: node %s [%d] has %2d children\n", GET_THREAD_NUM, ss_topPosn(ss), rng_showstate(parent->state.state, debug_str), parentHeight, numChildren); } // construct children and push onto stack if (numChildren > 0) { int i, j; child->type = childType; child->height = parentHeight + 1; #ifdef UTS_STAT if (stats) child->pp = parent; // pointer to parent #endif for (i = 0; i < numChildren; i++) { for (j = 0; j < computeGranularity; j++) { // TBD: add parent height to spawn // computeGranularity controls number of rng_spawn calls per node rng_spawn(parent->state.state, child->state.state, i); } ss_push(ss, child); releaseNodes(ss); } } else { ss->nLeaves++; } } /* * Parallel tree traversal * */ // cancellable barrier // initialize lock: single thread under omp, all threads under upc void cb_init(){ INIT_SINGLE_LOCK(cb_lock); if (debug & 4) printf("Thread %d, cb lock at %p\n", GET_THREAD_NUM, (void *) cb_lock); // fixme: no need for all upc threads to repeat this SET_LOCK(cb_lock); cb_count = 0; cb_cancel = 0; cb_done = 0; UNSET_LOCK(cb_lock); } // delay this thread until all threads arrive at barrier // or until barrier is cancelled int cbarrier_wait() { int l_count, l_done, l_cancel; int pe = GET_THREAD_NUM; SET_LOCK(cb_lock); cb_count++; // fprintf(stderr, "PE %d: cb_count=%d, # PEs=%d\n", shmem_my_pe(), cb_count, shmem_n_pes()); #ifdef _SHMEM PUT_ALL(cb_count, cb_count); #endif if (cb_count == GET_NUM_THREADS) { cb_done = 1; #ifdef _SHMEM PUT_ALL(cb_done, cb_done); #endif } l_count = cb_count; l_done = cb_done; if (stealStack[pe]->nNodes_last == stealStack[pe]->nNodes) { ++stealStack[pe]->falseWakeups; } stealStack[GET_THREAD_NUM]->nNodes_last = stealStack[pe]->nNodes; UNSET_LOCK(cb_lock); if (debug & 16) printf("Thread %d enter spin-wait, count = %d, done = %d\n", GET_THREAD_NUM, l_count, l_done); // spin do { #ifdef __BERKELEY_UPC__ bupc_poll(); #endif l_count = cb_count; l_cancel = cb_cancel; l_done = cb_done; } while (!l_cancel && !l_done); // fprintf(stderr, "PE %d: exiting spin loop because l_cancel=%d l_done=%d\n", shmem_my_pe(), l_cancel, l_done); if (debug & 16) printf("Thread %d exit spin-wait, count = %d, done = %d, cancel = %d\n", GET_THREAD_NUM, l_count, l_done, l_cancel); SET_LOCK(cb_lock); cb_count--; l_count = cb_count; #ifdef _SHMEM PUT_ALL(cb_count, cb_count); #endif cb_cancel = 0; l_done = cb_done; ++stealStack[GET_THREAD_NUM]->wakeups; UNSET_LOCK(cb_lock); if (debug & 16) printf("Thread %d exit idle state, count = %d, done = %d\n", GET_THREAD_NUM, l_count, cb_done); return cb_done; } // causes one or more threads waiting at barrier, if any, // to be released void cbarrier_cancel() { #ifdef _SHMEM cb_cancel = 1; PUT_ALL(cb_cancel, cb_cancel); #elif defined (__BERKELEY_UPC__) bupc_waitsync(cb_handle); cb_handle = bupc_memput_async((shared void*)&cb_cancel, (const void*)&local_cb_cancel, sizeof(int)); #else cb_cancel = 1; #endif /* _SHMEM */ } void releaseNodes(StealStack *ss){ if (doSteal) { if (ss_localDepth(ss) > 2 * chunkSize) { // Attribute this time to runtime overhead ss_setState(ss, SS_OVH); ss_release(ss, chunkSize); // This has significant overhead on clusters! if (ss->nNodes % cbint == 0) { ss_setState(ss, SS_CBOVH); cbarrier_cancel(); } #ifdef __BERKELEY_UPC__ if (ss->nNodes % pollint == 0) { ss_setState(ss, SS_OVH); bupc_poll(); } #endif ss_setState(ss, SS_WORK); } } } /* * parallel search of UTS trees using work stealing * * Note: tree size is measured by the number of * push operations */ void parTreeSearch(StealStack *ss) { int done = 0; Node * parent; Node child; /* template for children */ initNode(&child); /* tree search */ while (done == 0) { // fprintf(stderr, "PE %d: AAAAA\n", shmem_my_pe()); /* local work */ while (ss_localDepth(ss) > 0) { ss_setState(ss, SS_WORK); /* examine node at stack top */ parent = ss_top(ss); if (parent->numChildren < 0){ // fprintf(stderr, "PE %d: processed a node\n", shmem_my_pe()); // first time visited, construct children and place on stack genChildren(parent,&child,ss); } else { // second time visit, process accumulated statistics and pop #ifdef UTS_STAT if (stats) updateParStat(parent); #endif ss_pop(ss); } // release some nodes for stealing, if enough are available // and wake up quiescent threads releaseNodes(ss); } // fprintf(stderr, "PE %d: BBBBB\n", shmem_my_pe()); /* local work exhausted on this stack - resume tree search if able * to re-acquire work from shared portion of this thread's stack */ if (ss_acquire(ss, chunkSize)) continue; // fprintf(stderr, "PE %d: CCCCC\n", shmem_my_pe()); /* no work left in this thread's stack */ /* try to steal work from another thread's stack */ if (doSteal) { int goodSteal = 0; int victimId; // fprintf(stderr, "PE %d: DDDDD\n", shmem_my_pe()); ss_setState(ss, SS_SEARCH); victimId = findwork(chunkSize); while (victimId != -1 && !goodSteal) { // some work detected, try to steal it goodSteal = ss_steal(ss, victimId, chunkSize); if (!goodSteal) victimId = findwork(chunkSize); } // fprintf(stderr, "PE %d: EEEEE %d\n", shmem_my_pe(), goodSteal); if (goodSteal) continue; } /* unable to steal work from shared portion of other stacks - * enter quiescent state waiting for termination (done != 0) * or cancellation because some thread has made work available * (done == 0). */ ss_setState(ss, SS_IDLE); // fprintf(stderr, "PE %d: FFFFF\n", shmem_my_pe()); done = cbarrier_wait(); // fprintf(stderr, "PE %d: GGGGG\n", shmem_my_pe()); } /* tree search complete ! */ } #ifdef __PTHREADS__ /* Pthreads ParTreeSearch Arguments */ struct pthread_args { StealStack *ss; int id; }; /* Pthreads ParTreeSearch Wrapper */ void * pthread_spawn_search(void *arg) { pthread_setspecific(pthread_thread_num, &((struct pthread_args*)arg)->id); parTreeSearch(((struct pthread_args*)arg)->ss); return NULL; } #endif /* __PTHREADS__ */ #ifdef TRACE // print session records for each thread (used when trace is enabled) void printSessionRecords() { int i, j, k; double offset; for (i = 0; i < GET_NUM_THREADS; i++) { offset = startTime[i] - startTime[0]; for (j = 0; j < SS_NSTATES; j++) for (k = 0; k < stealStack[i]->entries[j]; k++) { printf ("%d %d %f %f", i, j, stealStack[i]->md->sessionRecords[j][k].startTime - offset, stealStack[i]->md->sessionRecords[j][k].endTime - offset); if (j == SS_WORK) printf (" %d %ld", stealStack[i]->md->stealRecords[k].victimThread, stealStack[i]->md->stealRecords[k].nodeCount); printf ("\n"); } } } #endif // display search statistics void showStats(double elapsedSecs) { int i; int tnodes = 0, tleaves = 0, trel = 0, tacq = 0, tsteal = 0, tfail= 0; int mdepth = 0, mheight = 0; double twork = 0.0, tsearch = 0.0, tidle = 0.0, tovh = 0.0, tcbovh = 0.0; #ifdef _SHMEM { int pe; /* Assemble all of the stealstacks so we can gather some stats. */ for (i = 1; i < GET_NUM_THREADS; i++) { pe = (GET_THREAD_NUM + i) % GET_NUM_THREADS; /* Collect up all of the StealStacks */ SMEMCPY(stealStack[pe], stealStack[pe], sizeof(StealStack), pe); #ifdef TRACE /* Get the MetaData as well */ SMEMCPY(stealStack[pe]->md, stealStack[pe]->md, sizeof(StealStack), pe); #endif } } #endif // combine measurements from all threads for (i = 0; i < GET_NUM_THREADS; i++) { tnodes += stealStack[i]->nNodes; tleaves += stealStack[i]->nLeaves; trel += stealStack[i]->nRelease; tacq += stealStack[i]->nAcquire; tsteal += stealStack[i]->nSteal; tfail += stealStack[i]->nFail; twork += stealStack[i]->time[SS_WORK]; tsearch += stealStack[i]->time[SS_SEARCH]; tidle += stealStack[i]->time[SS_IDLE]; tovh += stealStack[i]->time[SS_OVH]; tcbovh += stealStack[i]->time[SS_CBOVH]; mdepth = (mdepth > stealStack[i]->maxStackDepth ? mdepth : stealStack[i]->maxStackDepth); mheight = (mheight > stealStack[i]->maxTreeDepth ? mheight : stealStack[i]->maxTreeDepth); } if (trel != tacq + tsteal) { printf("*** error! total released != total acquired + total stolen\n"); } uts_showStats(GET_NUM_THREADS, chunkSize, elapsedSecs, tnodes, tleaves, mheight); if (verbose > 1) { if (doSteal) { printf("Total chunks released = %d, of which %d reacquired and %d stolen\n", trel, tacq, tsteal); printf("Failed steal operations = %d, ", tfail); } printf("Max stealStack size = %d\n", mdepth); printf("Avg time per thread: Work = %.6f, Search = %.6f, Idle = %.6f\n", (twork / GET_NUM_THREADS), (tsearch / GET_NUM_THREADS), (tidle / GET_NUM_THREADS)); printf(" Overhead = %6f, CB_Overhead = %6f\n\n", (tovh / GET_NUM_THREADS), (tcbovh/GET_NUM_THREADS)); } // per thread execution info if (verbose > 2) { for (i = 0; i < GET_NUM_THREADS; i++) { printf("** Thread %d\n", i); printf(" # nodes explored = %d\n", stealStack[i]->nNodes); printf(" # chunks released = %d\n", stealStack[i]->nRelease); printf(" # chunks reacquired = %d\n", stealStack[i]->nAcquire); printf(" # chunks stolen = %d\n", stealStack[i]->nSteal); printf(" # failed steals = %d\n", stealStack[i]->nFail); printf(" maximum stack depth = %d\n", stealStack[i]->maxStackDepth); printf(" work time = %.6f secs (%d sessions)\n", stealStack[i]->time[SS_WORK], stealStack[i]->entries[SS_WORK]); printf(" overhead time = %.6f secs (%d sessions)\n", stealStack[i]->time[SS_OVH], stealStack[i]->entries[SS_OVH]); printf(" search time = %.6f secs (%d sessions)\n", stealStack[i]->time[SS_SEARCH], stealStack[i]->entries[SS_SEARCH]); printf(" idle time = %.6f secs (%d sessions)\n", stealStack[i]->time[SS_IDLE], stealStack[i]->entries[SS_IDLE]); printf(" wakeups = %d, false wakeups = %d (%.2f%%)", stealStack[i]->wakeups, stealStack[i]->falseWakeups, (stealStack[i]->wakeups == 0) ? 0.00 : ((((double)stealStack[i]->falseWakeups)/stealStack[i]->wakeups)*100.0)); printf("\n"); } } #ifdef TRACE printSessionRecords(); #endif // tree statistics output to stat.txt, if requested #ifdef UTS_STAT if (stats) { FILE *fp; char * tmpstr; char strBuf[5000]; int ind = 0; fp = fopen("stat.txt", "a+w"); fprintf(fp, "\n------------------------------------------------------------------------------------------------------\n"); ind = uts_paramsToStr(strBuf, ind); ind = impl_paramsToStr(strBuf, ind); //showParametersStr(strBuf); fprintf(fp, "%s\n", strBuf); fprintf(fp, "\nTotal nodes = %d\n", totalNodes); fprintf(fp, "Max depth = %d\n\n", maxHeight); fprintf(fp, "Tseng ImbMeasure(overall)\n max:\t\t%lf \n avg:\t\t%lf \n devMaxAvg:\t %lf\n normDevMaxAvg: %lf\t\t\n\n", imb_max/totalNodes, imb_avg/totalNodes, imb_devmaxavg/totalNodes, imb_normdevmaxavg/totalNodes); switch (unbType){ case 0: tmpstr = "(min imb weighted by size)"; break; case 1: tmpstr = "(min imb not weighted by size)"; break; case 2: tmpstr = "(max imb not weighted by size)"; break; default: tmpstr = "(?unknown measure)"; break; } fprintf(fp, "ImbMeasure:\t%s\n Overall:\t %lf\n Max:\t\t%lf\n Min:\t\t%lf\n\n", tmpstr, treeImb, minImb, maxImb); showHist(fp); fprintf(fp, "\n------------------------------------------------------------------------------------------------------\n\n\n"); fclose(fp); } #endif } /* PThreads main() function: * Pthreads is quite a bit different because of how global data has to be stored * using setspecific() and getspecific(). So, many functions are not safe to call * in the single-threaded context. */ #ifdef __PTHREADS__ int pthread_main(int argc, char *argv[]) { Node root; double t1, t2; int i, err; void *rval; struct pthread_args *args; pthread_t *thread_ids; uts_parseParams(argc, argv); uts_printParams(); cb_init(); /* allocate stealstacks */ for (i = 0; i < GET_NUM_THREADS; i++) { stealStack[i] = ALLOC (sizeof(StealStack)); ss_init(stealStack[i], MAXSTACKDEPTH); } /* initialize root node and push on thread 0 stack */ uts_initRoot(&root, type); ss_push(stealStack[0], &root); thread_ids = malloc(sizeof(pthread_t)*GET_NUM_THREADS); args = malloc(sizeof(struct pthread_args)*GET_NUM_THREADS); pthread_key_create(&pthread_thread_num, NULL); /* start timing */ t1 = uts_wctime(); for (i = 0; i < GET_NUM_THREADS; i++) { ss_initState(stealStack[i]); args[i].ss = stealStack[i]; args[i].id = i; err = pthread_create(&thread_ids[i], NULL, pthread_spawn_search, (void*)&args[i]); if (err != 0) { printf("FATAL: Error spawning thread %d\n", err); impl_abort(1); } } for (i = 0; i < GET_NUM_THREADS; i++) { pthread_join(thread_ids[i], &rval); } /* stop timing */ t2 = uts_wctime(); showStats(t2-t1); return 0; } #endif /* __PTHREADS__ */ /* Main() function for: Sequential, OpenMP, UPC, and Shmem * * Notes on execution model: * - under openMP, global vars are all shared * - under UPC, global vars are private unless explicitly shared * - UPC is SPMD starting with main, OpenMP goes SPMD after * parsing parameters */ int main(int argc, char *argv[]) { Node root; #ifdef __PTHREADS__ return pthread_main(argc, argv); #endif #ifdef _SHMEM shmem_init(); // start_pes(0); #endif /* determine benchmark parameters (all PEs) */ uts_parseParams(argc, argv); #ifdef UTS_STAT if (stats) initHist(); #endif /* cancellable barrier initialization (single threaded under OMP) */ cb_init(); /********** SPMD Parallel Region **********/ #pragma omp parallel { double t1, t2, et; StealStack * ss; /* show parameter settings */ if (GET_THREAD_NUM == 0) { uts_printParams(); } /* initialize stealstacks */ #ifdef _SHMEM { /* Shared allocation is a collective operation in Shmem. These * need to be done all at once and in the same order on each PE. * * Note: Only our own stealstack will contain valid data as UTS runs. * For stats, we'll need to gather everyone else's stealstacks */ int i; stealStack[0] = (SHARED StealStack *) ALLOC (sizeof(StealStack)); memset(stealStack[0],0,sizeof(StealStack)); ss = (StealStack *) stealStack[0]; ss_init(ss, MAXSTACKDEPTH); for (i = 1; i < GET_NUM_THREADS; i++) { stealStack[i] = (SHARED StealStack *) ALLOC (sizeof(StealStack)); ss = (StealStack *) stealStack[i]; ss->stack_g=ss->stack=stealStack[0]->stack; ss_init(ss, MAXSTACKDEPTH); } ss = stealStack[GET_THREAD_NUM]; } #else stealStack[GET_THREAD_NUM] = (SHARED StealStack *) ALLOC (sizeof(StealStack)); ss = (StealStack *) stealStack[GET_THREAD_NUM]; ss_init(ss, MAXSTACKDEPTH); #endif /* _SHMEM */ /* initialize root node and push on thread 0 stack */ if (GET_THREAD_NUM == 0) { initRootNode(&root, type); ss_push(ss, &root); } // line up for the start #pragma omp barrier BARRIER /* time parallel search */ ss_initState(ss); t1 = uts_wctime(); parTreeSearch(ss); t2 = uts_wctime(); et = t2 - t1; #ifdef TRACE startTime[GET_THREAD_NUM] = t1; ss->md->sessionRecords[SS_IDLE][ss->entries[SS_IDLE] - 1].endTime = t2; #endif #pragma omp barrier BARRIER /* display results */ if (GET_THREAD_NUM == 0) { showStats(et); } } /********** End Parallel Region **********/ #ifdef _SHMEM shmem_finalize(); #endif return 0; }
taskdep_taskwait_untied_scheduling.c
// RUN: %libomp-compile && env KMP_ABT_NUM_ESS=4 %libomp-run // REQUIRES: abt #include "omp_testsuite.h" #include "bolt_scheduling_util.h" #include <stdio.h> #include <stdlib.h> #include <string.h> int calc_seq(int n) { int i, j, *buffer = (int *)malloc(sizeof(int) * n * n); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i == 0 && j == 0) { buffer[i * n + j] = 1; } else if (i == 0) { buffer[i * n + j] = buffer[i * n + (j - 1)]; } else if (j == 0) { buffer[i * n + j] = buffer[(i - 1) * n + j]; } else { buffer[i * n + j] = buffer[(i - 1) * n + j] + buffer[i * n + (j - 1)]; } } } int ret = buffer[(n - 1) * n + (n - 1)]; free(buffer); return ret; } int test_taskdep_taskwait_untied_scheduilng() { int n = 6; int seq_val, task_val; timeout_barrier_t barrier; timeout_barrier_init(&barrier); #pragma omp parallel shared(task_val) firstprivate(n) num_threads(4) { #pragma omp master { // 6 ( = n) barrier_waits in diagonal tasks and 2 barrier_waits in threads check_num_ess(4); int i, j; int *A_buf = (int *)malloc(sizeof(int) * n * n); int **A = (int **)malloc(sizeof(int *) * n); for(i = 0; i < n; i++) { A[i] = A_buf + (i * n); for(j = 0; j < n; j++) { // Assign random values. A[i][j] = i * n + j; } } // A[i][j] is the root task. for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { if (i == 0 && j == 0) { #pragma omp task depend(out:A[i][j]) firstprivate(A, i, j) untied { if (i + j == n - 1) { timeout_barrier_wait(&barrier, 4); } A[i][j] = 1; } } else if (i == 0) { #pragma omp task depend(in:A[i][j - 1]) depend(out:A[i][j]) \ firstprivate(A, i, j) untied { if (i + j == n - 1) { timeout_barrier_wait(&barrier, 4); } A[i][j] = A[i][j - 1]; } } else if (j == 0) { #pragma omp task depend(in:A[i - 1][j]) depend(out:A[i][j]) \ firstprivate(A, i, j) untied { if (i + j == n - 1) { timeout_barrier_wait(&barrier, 4); } A[i][j] = A[i - 1][j]; } } else { #pragma omp task depend(in:A[i - 1][j], A[i][j - 1]) \ depend(out:A[i][j]) untied { if (i + j == n - 1) { timeout_barrier_wait(&barrier, 4); } A[i][j] = A[i - 1][j] + A[i][j - 1]; } } } } #pragma omp taskwait task_val = A[n - 1][n - 1]; free(A); free(A_buf); } if (omp_get_thread_num() >= 2) { // The master thread needs to wait for tasks, so non-master threads should // run it. timeout_barrier_wait(&barrier, 4); } } seq_val = calc_seq(n); if(seq_val != task_val) { printf("Failed: route(%d) = %d (ANS = %d)\n", n, task_val, seq_val); return 0; } return 1; } int main() { int i, num_failed = 0; for (i = 0; i < REPETITIONS; i++) { if (!test_taskdep_taskwait_untied_scheduilng()) { num_failed++; } } return num_failed; }
17_primes-par3.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char **argv) { // quantos numeros primos entre 1 e N ? unsigned long n = 99999; unsigned long aux = 2; unsigned long primes = 0; #pragma omp parallel for firstprivate(aux) reduction(+:primes) schedule(guided) for (unsigned long i = 2; i < n; i++) { while (aux < i) { if (i % aux == 0) break; aux++; } if (aux == i) primes++; aux = 2; } printf("%lu primos entre 1 e %lu\n",primes,n); return 0; }
trmv_x_csr_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t trmv_x_csr_u_hi_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0;i < m; ++i) { ALPHA_Number tmp = x[i]; for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col <= i) { continue; } else { alpha_madde(tmp, A->values[ai], x[col]); } } alpha_mule(tmp, alpha); alpha_mule(y[i], beta); alpha_adde(y[i], tmp); } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return trmv_x_csr_u_hi_omp(alpha, A, x, beta, y); }
GB_iso_check_template.c
//------------------------------------------------------------------------------ // GB_iso_check_template: check if all entries in a matrix are identical //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ { //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; //-------------------------------------------------------------------------- // check all entries to see if they are equal to the first entry //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t pstart, pend ; GB_PARTITION (pstart, pend, anz, tid, ntasks) ; bool my_iso ; GB_ATOMIC_READ my_iso = iso ; if (my_iso) { // GB_ATYPE a = Ax [0] ; GB_GET_FIRST_VALUE (GB_ATYPE, a, Ax) ; for (int64_t p = pstart ; my_iso && p < pend ; p++) { // my_iso = my_iso && (a == Ax [p]) GB_COMPARE_WITH_FIRST_VALUE (my_iso, a, Ax, p) ; } if (!my_iso) { // tell the other tasks to exit early GB_ATOMIC_WRITE iso = false ; } } } done = true ; } #undef GB_ATYPE
residual_based_pseudo_static_displacement_scheme.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ \. // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_RESIDUAL_PSEUDO_STATIC_DISPLACEMENT_SCHEME ) #define KRATOS_RESIDUAL_PSEUDO_STATIC_DISPLACEMENT_SCHEME /* System includes */ /* External includes */ /* Project includes */ #include "solving_strategies/schemes/residual_based_bossak_displacement_scheme.hpp" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class ResidualBasedPseudoStaticDisplacementScheme * @ingroup KratosCore * @brief This is a pseudo-static scheme * @details For pseudo–static strategy: calculate the constant matrices D = Beta * M, "set" M = 0 after initializing the damping matrix * @note Based on Riccardo Rossi PhD Thesis: Light weight Structures: Structural Analysis and Coupling Issues * @author Vicente Mataix Ferrandiz */ template<class TSparseSpace, class TDenseSpace > class ResidualBasedPseudoStaticDisplacementScheme : public ResidualBasedBossakDisplacementScheme<TSparseSpace,TDenseSpace> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedPseudoStaticDisplacementScheme ); typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef typename BaseType::TDataType TDataType; typedef typename BaseType::DofsArrayType DofsArrayType; typedef typename Element::DofsVectorType DofsVectorType; typedef typename BaseType::TSystemMatrixType TSystemMatrixType; typedef typename BaseType::TSystemVectorType TSystemVectorType; typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef typename BaseType::Pointer BaseTypePointer; typedef ResidualBasedBossakDisplacementScheme<TSparseSpace,TDenseSpace> DerivedBaseType; typedef typename BaseType::LocalSystemComponents LocalSystemComponentsType; static constexpr double ZeroTolerance = std::numeric_limits<double>::epsilon(); ///@} ///@name Life Cycle ///@{ /** * @brief Constructor. The pseudo static scheme (parameters) * @param ThisParameters Parameters with the Rayleigh variable */ explicit ResidualBasedPseudoStaticDisplacementScheme(Parameters ThisParameters) :DerivedBaseType(0.0) { // Validate default parameters Parameters default_parameters = Parameters(R"( { "rayleigh_beta_variable" : "RAYLEIGH_BETA" })" ); ThisParameters.ValidateAndAssignDefaults(default_parameters); mRayleighBeta = KratosComponents<Variable<double>>::Get(ThisParameters["rayleigh_beta_variable"].GetString()); } /** * @brief Default constructor. The pseudo static scheme */ explicit ResidualBasedPseudoStaticDisplacementScheme(const Variable<double> RayleighBetaVariable) :DerivedBaseType(0.0), mRayleighBeta(RayleighBetaVariable) { } /** Copy Constructor. */ explicit ResidualBasedPseudoStaticDisplacementScheme(ResidualBasedPseudoStaticDisplacementScheme& rOther) :DerivedBaseType(rOther), mRayleighBeta(rOther.mRayleighBeta) { } /** * Clone */ BaseTypePointer Clone() override { return BaseTypePointer( new ResidualBasedPseudoStaticDisplacementScheme(*this) ); } /** Destructor. */ ~ResidualBasedPseudoStaticDisplacementScheme () override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Performing the prediction of the solution * @details It predicts the solution for the current step x = xold + vold * Dt * @param rModelPart The model of the problem to solve * @param rDofSet set of all primary variables * @param A LHS matrix * @param Dx Incremental update of primary variables * @param b RHS Vector */ void Predict( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& A, TSystemVectorType& Dx, TSystemVectorType& b ) override { KRATOS_TRY; const double delta_time = rModelPart.GetProcessInfo()[DELTA_TIME]; // Updating time derivatives (nodally for efficiency) const int num_nodes = static_cast<int>(rModelPart.NumberOfNodes()); array_1d<double, 3> zero_array(3, 0.0); array_1d<double, 3> delta_displacement; #pragma omp parallel for private(zero_array, delta_displacement) for(int i = 0; i < num_nodes; ++i) { auto it_node = rModelPart.Nodes().begin() + i; //Predicting: NewDisplacement = previous_displacement + previous_velocity * delta_time; //ATTENTION::: the prediction is performed only on free nodes const array_1d<double, 3>& previous_velocity = (it_node)->FastGetSolutionStepValue(VELOCITY, 1); const array_1d<double, 3>& previous_displacement = (it_node)->FastGetSolutionStepValue(DISPLACEMENT, 1); array_1d<double, 3>& current_acceleration = (it_node)->FastGetSolutionStepValue(ACCELERATION); array_1d<double, 3>& current_velocity = (it_node)->FastGetSolutionStepValue(VELOCITY); array_1d<double, 3>& current_displacement = (it_node)->FastGetSolutionStepValue(DISPLACEMENT); if (it_node -> IsFixed(DISPLACEMENT_X) == false) current_displacement[0] = previous_displacement[0] + delta_time * previous_velocity[0]; if (it_node -> IsFixed(DISPLACEMENT_Y) == false) current_displacement[1] = previous_displacement[1] + delta_time * previous_velocity[1]; // For 3D cases if (it_node -> HasDofFor(DISPLACEMENT_Z)) { if (it_node -> IsFixed(DISPLACEMENT_Z) == false) current_displacement[2] = previous_displacement[2] + delta_time * previous_velocity[2]; } // Updating time derivatives ::: Please note that displacements and its time derivatives can not be consistently fixed separately noalias(delta_displacement) = current_displacement - previous_displacement; current_velocity = previous_velocity; current_acceleration = zero_array; } KRATOS_CATCH( "" ); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "ResidualBasedPseudoStaticDisplacementScheme"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << Info(); } /// Print object's data. void PrintData(std::ostream& rOStream) const override { rOStream << Info(); } ///@} ///@name Friends ///@{ protected: ///@} ///@name Static Member Variables ///@{ ///@} ///@name Protected Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief It adds the dynamic LHS contribution of the elements D*c1 + K * @param rLHSContribution The dynamic contribution for the LHS * @param rD The damping matrix * @param rM The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToLHS( LocalSystemMatrixType& rLHSContribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, ProcessInfo& rCurrentProcessInfo ) override { // Adding damping contribution if (rD.size1() != 0 && TDenseSpace::TwoNorm(rD) > ZeroTolerance) // if D matrix declared noalias(rLHSContribution) += rD * DerivedBaseType::mNewmark.c1; else if (rM.size1() != 0) { const double beta = rCurrentProcessInfo[mRayleighBeta]; noalias(rLHSContribution) += rM * beta * DerivedBaseType::mNewmark.c1; } } /** * @brief It adds the dynamic RHS contribution of the elements b - D*v * @param pElement The element to compute * @param RHS_Contribution The dynamic contribution for the RHS * @param D The damping matrix * @param M The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToRHS( Element::Pointer pElement, LocalSystemVectorType& rRHSContribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, ProcessInfo& rCurrentProcessInfo ) override { const std::size_t this_thread = OpenMPUtils::ThisThread(); // Adding damping contribution if (rD.size1() != 0 && TDenseSpace::TwoNorm(rD) > ZeroTolerance) { pElement->GetFirstDerivativesVector(DerivedBaseType::mVector.v[this_thread], 0); noalias(rRHSContribution) -= prod(rD, DerivedBaseType::mVector.v[this_thread]); } else if (rM.size1() != 0) { const double beta = rCurrentProcessInfo[mRayleighBeta]; pElement->GetFirstDerivativesVector(DerivedBaseType::mVector.v[this_thread], 0); noalias(rRHSContribution) -= beta * prod(rM, DerivedBaseType::mVector.v[this_thread]); } } /** * @brief It adds the dynamic RHS contribution of the condition b - M*a - D*v * @param pCondition The condition to compute * @param rRHSContribution The dynamic contribution for the RHS * @param rD The damping matrix * @param rM The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToRHS( Condition::Pointer pCondition, LocalSystemVectorType& rRHSContribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, ProcessInfo& rCurrentProcessInfo ) override { const std::size_t this_thread = OpenMPUtils::ThisThread(); // Adding damping contribution // Damping contribution if (rD.size1() != 0 && TDenseSpace::TwoNorm(rD) > ZeroTolerance) { pCondition->GetFirstDerivativesVector(DerivedBaseType::mVector.v[this_thread], 0); noalias(rRHSContribution) -= prod(rD, DerivedBaseType::mVector.v[this_thread]); } else if (rM.size1() != 0) { const double beta = rCurrentProcessInfo[mRayleighBeta]; pCondition->GetFirstDerivativesVector(DerivedBaseType::mVector.v[this_thread], 0); noalias(rRHSContribution) -= beta * prod(rM, DerivedBaseType::mVector.v[this_thread]); } } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@{ private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ const Variable<double> mRayleighBeta; /// The Rayleigh Beta variable ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class ResidualBasedPseudoStaticDisplacementScheme */ } /* namespace Kratos.*/ #endif /* KRATOS_RESIDUAL_PSEUDO_STATIC_DISPLACEMENT_SCHEME E defined */
integrate.c
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> /* Include Ian Bush's timing routines */ #include<timer.h> /* Include OpenMP library routines */ #include<omp.h> /* The constant M_PI isn't included in the C89 standard, so we define it here - checking first to see if it has already been defined (in case the code is compiled with a different C standard */ #ifndef M_PI # define M_PI 3.1415926535897931 #endif /* We define these named constants to make it easier to state whether we want timing info printed from the integrate() function.*/ #define PRINT_TIMES 1 #define NO_PRINT_TIMES 0 /* Calculate the first function given on the specification sheet */ double f1(double x) { double res; res = 5*pow(x, 3) + 4 * pow(x, 2) + 3*x + 2; return res; } /* Calculate the second function given on the specification sheet */ double f2(double x) { double res; res = sin(x); return res; } /* Calculate the third function given on the specification sheet */ double f3(double x) { double res; if (x <= 0) { res = x; } else { res = sin(x); } return res; } /* This function does the actual integration *fn A pointer to a function to intergrate a The lower limit for integration b The upper limit for integration n The number of trapezia to use for integration t The number of threads to use (given as an argument so that tests can easily be carried out) print_times Takes a #define'd constant of either PRINT_TIMES or NO_PRINT_TIMES to specify whether timing information should be printed or not */ double integrate( double (*fn)(double), double a, double b, int n, int t, int print_times) { /* Declare variables (All are initialised to zero as C variables will otherwise be initialised to whatever happens to be in that memory location) */ double tstart = 0; /* The starting time */ double tend = 0; /* The ending time */ double h = 0; /* The x-step value */ double curr_x = 0; /* The current x value used in the loop */ double sum = 0; /* Used to hold the sum as we go from i = a to b in steps of h */ int i; /* The integer loop variable */ /* Record the start time */ tstart = timer(); /* Calculate h (the distance between each x value) given n (the number of bits to split the input range into*/ h = (b - a) / (double) n; /* Start a parallel region using the number of threads set by the parameter t The region will only be run in parallel if n is greater than 1300 The loop variable and curr_x variable are private to each thread, all others are shared */ #pragma omp parallel num_threads(t), default(none), private(i, curr_x), shared(h, a, b, fn, n, sum) if(n>1300) /* Go from a to b in steps of h and stop when we get to b We do this using a standard integer loop, and then calculating what x value we are at inside the loop. This means that the loop variable is an int, which is more efficient. */ /* Parallelize this loop - splitting the iterations between threads Each thread will calculate its own sum, at the end add all of these sub-sums together and store it in the variable sum. Split the iterations equally between the threads, and do all of the splitting at the beginning. */ #pragma omp for reduction(+:sum) schedule(static) for (i = 0; i < n; i++) { curr_x = a + i * h; /* Calculate the equation given on the Coursework 1 instruction sheet */ sum += h * ( ( (*fn)(curr_x) + (*fn)(curr_x - h) ) / 2); } /* Record the end time */ tend = timer(); /* Print the value of n (number of steps), t (number of threads), and the time taken in CSV format ready to be redirected to a CSV file from the command line */ if (print_times == PRINT_TIMES) { printf("%d, %d, %f\n", n, t, tend-tstart); } /* Return the final calculated value of the integral */ return sum; } /* Integrate a function using the adaptive scheme discussed in the report *fn A pointer to a function to intergrate a The lower limit for integration b The upper limit for integration start_n The number of trapezia to use for the first integration epsilon The accuracy required for the final result n_factor The factor to change n by each iteration (new_n = n * n_factor) t The number of threads to use (given as an argument so that tests can easily be carried out) */ double adaptive_integrate(double (*fn)(double), double a, double b, int start_n, double epsilon, int n_factor, int t) { double prev_res = 0; /* The previous result, initialised to zero */ double curr_res = 0; /* The current result, initialised to zero */ double diff = 10000; /* The difference - initialised to a large number */ int n = start_n; /* The current n value to use - initialised to the user-specified start value */ double tstart = 0; /* The starting time */ double tend = 0; /* The ending time */ /* Record the start time */ tstart = timer(); /* While the difference between the last two integrations is larger than the user-specified accuracy (epsilon) */ while (diff > epsilon) { /* Record the current result */ prev_res = curr_res; /* Run the integration (telling it not to print any timing information */ curr_res = integrate((*fn), a, b, n, t, NO_PRINT_TIMES); printf("Integrating with n = %d\n\tResult = %f\n", n, curr_res); /* Compute the next n value */ n = n * n_factor; /* Get the absolute difference between the previous two integrations */ diff = fabs(prev_res - curr_res); printf("\tDifference between previous results = %f\n", diff); } printf("Difference is less than epsilon. Stopping.\n"); printf("Final result = %f\n", curr_res); /* Record the end time */ tend = timer(); printf("Time taken = %f seconds\n", tend-tstart); return curr_res; } /* Test the adaptive integration scheme */ void run_adaptive_test(void) { adaptive_integrate((double (*)(double))f1, -1, 3, 10, 0.0001, 10, 8); } /* Integrate all of the test functions and display the results */ void run_all(void) { printf("Using n = 1000\n"); printf("Integral of f1 = %f\n", integrate((double (*)(double))f1, -1, 3, 10000, 8, NO_PRINT_TIMES)); printf("Integral of f2 = %f\n", integrate((double (*)(double))f2, 0, 2 * M_PI, 10000, 8, NO_PRINT_TIMES)); printf("Integral of f3 = %f\n", integrate((double (*)(double))f3, -1 * M_PI, M_PI, 10000, 8, NO_PRINT_TIMES)); } /* Run the test to calculate what value of n should be used in the omp parallel if statement */ void run_n_test(void) { double res; int i; for (i = 0; i <= 50000; i+=100) { res = integrate((double (*)(double))f3, -1 * M_PI, M_PI, i, 1, PRINT_TIMES); res = integrate((double (*)(double))f3, -1 * M_PI, M_PI, i, 8, PRINT_TIMES); } } /* Run a test to produce the data used for the scaling graphs */ void run_scaling_test(void) { int n = 100000; /* Set n to a large number */ int i; for (i = 1; i <= 8; i++) { integrate((double (*)(double))f1, -1, 3, n, i, PRINT_TIMES); integrate((double (*)(double))f2, 0, 2 * M_PI, n, i, PRINT_TIMES); integrate((double (*)(double))f3, -1 * M_PI, M_PI, n, i, PRINT_TIMES); } } /* Run a simple test to calculate the difference between the numerical integration results and analytical results */ void run_unit_test(void) { /* Use a large n to get values as accurate as possible */ int n = 1000000; /* Define the variables for the CALCulated values of the integrals and the ANALytical values (derived from Mathematica) */ double calc_res1, calc_res2, calc_res3 = 0; double anal_res1, anal_res2, anal_res3 = 0; /* For each of the functions, integrate it and store the result and put the analytical result in a variable too */ calc_res1 = integrate((double (*)(double))f1, -1, 3, n, 8, NO_PRINT_TIMES); anal_res1 = 472 / (double) 3; calc_res2 = integrate((double (*)(double))f2, 0, 2 * M_PI, n, 8, NO_PRINT_TIMES); anal_res2 = 0.0; calc_res3 = integrate((double (*)(double))f3, -1 * M_PI, M_PI, n, 8, NO_PRINT_TIMES); anal_res3 = 2 - (pow(M_PI,2) / 2); /* Print the results */ printf("Function 1 difference: %f\n", calc_res1 - anal_res1); printf("Function 2 difference: %f\n", calc_res2 - anal_res2); printf("Function 3 difference: %f\n", calc_res3 - anal_res3); } /* The main function */ int main(int argc, char *argv[]) { /* Define a single int loop variable */ int i; /* If no command-line arguments have been specified then display the help text below */ if (argc == 1) { printf("SESG6028 Integration Coursework by Robin Wilson\n \ ----------------------------------------------- \ \nThe following options are available:\n \ full\t\tRun test of all functions given on coursework sheet\n \ unittest\tRuns a simple test to ensure that the functions are giving the right results\n \ ntest\t\tRun a test to see what value of n should be used as the if threshold\n \ scalingtest\tRun a test to determine the scaling of the code\n \ adaptivetest\tRuns a test of the adaptive integration system\n"); } /* Process command line arguments checking them and running the appropriate function */ for (i = 1; i < argc; i++) /* Skip argv[0] (program name). */ { /* if strcmp returns 0 then the strings are identical */ if (strcmp(argv[i], "full") == 0) { run_all(); } else if (strcmp(argv[i], "ntest") == 0) { run_n_test(); } else if (strcmp(argv[i], "scalingtest") == 0) { run_scaling_test(); } else if (strcmp(argv[i], "unittest") == 0) { run_unit_test(); } else if (strcmp(argv[i], "adaptivetest") == 0) { run_adaptive_test(); } } /* Return success regardless */ return 0; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 24; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
valid.mob7.src.h
#pragma once #include "ukr.h" #include "omp.h" #include "transpose.h" #include "gen_ukr_A6B2gemm_1_512_14_14_512_3_3.h" #include "gen_ukr_A4B2gemm_1_512_14_14_512_3_3.h" void testrun(float* A ,float*B, float*C, float*oriB ){ int tid = omp_get_thread_num(); int Nx = 14; int Ny = 14; int Nh = 3; long long Astrides[6] = {0,1,2,3,4,5}; int b1 = 0; for (int fpck = (tid%1)*16; fpck < uNf; fpck+=1*16){ for(int cwh = (tid/1)*8; cwh < uNc*uNw*uNh/8*8; cwh+=8*1){ transpose8x8_avx(oriB+ (fpck+0)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 0, uNc*uNw*uNh, 16); transpose8x8_avx(oriB+ (fpck+8)*uNc*uNw*uNh + cwh, B + fpck*uNc*uNw*uNh + cwh* 16 + 8, uNc*uNw*uNh, 16); } } #pragma omp barrier// begin push button generated block for(int c5=0;c5<512+0;c5+=512) { for(int xy5=0;xy5<196+0;xy5+=196) { for(int f5=0;f5<512+0;f5+=512) { for(int c4=c5;c4<min(512, 512+c5);c4+=512) { for(int f4=f5;f4<min(512, 512+f5);f4+=512) { for(int xy4=xy5;xy4<min(196, 196+xy5);xy4+=196) { for(int c3=c4;c3<min(512, 512+c4);c3+=Tc1) { for(int f3=f4;f3<min(512, 512+f4);f3+=Tf2) { for(int xy3=xy4;xy3<min(196, 196+xy4);xy3+=Txy3) { for(int xy2=xy3;xy2<min(196, Txy3+xy3);xy2+=6) { for(int f2=f3;f2<min(512, Tf2+f3);f2+=16) { for(int c2=c3;c2<min(512, Tc1+c3);c2+=Tc1) { for(int c1=c2;c1<min(512, Tc1+c2);c1+=Tc1) { for(int xy1=xy2;xy1<min(196, 6+xy2);xy1+=6) { for(int f1=f2;f1<min(512, 16+f2);f1+=16) { int ctile=min(Tc1, 512-c1); int x1=xy1/14; int y1=xy1%14/1; int c1_1=c1/1; int c1_2=c1%1/1; int kf1_1=f1/16; int kf1_2=f1%16/1; int of1_1=f1/1; int of1_2=f1%1/1; int offsetA=0+b1*131072+c1_1*256+1*x1*16+1*y1*1+c1_2*1; int offsetB=0+kf1_1*73728+c1*144+0*48+0*16+kf1_2*1; int offsetC=0+b1*100352+of1_1*196+x1*14+y1*1+of1_2*1; if(14-y1>=6){ cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } else if(14*14-xy1>=6){ for(int sti=14-y1;sti<6;sti+=1) { Astrides[sti]+=2; } cnn_ukr_float_scatter_6x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); for(int sti=14-y1;sti<6;sti+=1) { Astrides[sti]-=2; } } else{ cnn_ukr_float_scatter_4x2v_cxycgemm(A+offsetA, B+offsetB, C+offsetC, ctile, Astrides); } } } } } } } } } } } } } } } } // end push button generated block }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/DarwinSDKInfo.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Tracks expected type during expression parsing, for use in code completion. /// The type is tied to a particular token, all functions that update or consume /// the type take a start location of the token they are looking at as a /// parameter. This avoids updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Handles e.g. BaseType{ .D = Tok... void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. /// /// The callback should also emit signature help as a side-effect, but only /// if the completion point has been reached. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); /// Get the expected type associated with this location, if any. /// /// If the location is a function argument, determining the expected type /// involves considering all function overloads and the arguments so far. /// In this case, signature help for these function overloads will be reported /// as a side-effect (only if the completion point has been reached). QualType get(SourceLocation Tok) const { if (!Enabled || Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: bool Enabled; /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 32; static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The namespace where coroutine components are defined. In standard, /// they are defined in std namespace. And in the previous implementation, /// they are defined in std::experimental namespace. NamespaceDecl *CoroTraitsNamespaceCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// In addition of being constant evaluated, the current expression /// occurs in an immediate function context - either a consteval function /// or a consteval if function. ImmediateFunctionContext, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; // A context can be nested in both a discarded statement context and // an immediate function context, so they need to be tracked independently. bool InDiscardedStatement; bool InImmediateFunctionContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), InDiscardedStatement(false), InImmediateFunctionContext(false) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated || Context == ExpressionEvaluationContext::ImmediateFunctionContext; } bool isImmediateFunctionContext() const { return Context == ExpressionEvaluationContext::ImmediateFunctionContext || (Context == ExpressionEvaluationContext::DiscardedStatement && InImmediateFunctionContext); } bool isDiscardedStatementContext() const { return Context == ExpressionEvaluationContext::DiscardedStatement || (Context == ExpressionEvaluationContext::ImmediateFunctionContext && InDiscardedStatement); } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl *, 2> Pair; public: SpecialMemberOverloadResult() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. const TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; class GlobalMethodPool { public: using Lists = std::pair<ObjCMethodList, ObjCMethodList>; using iterator = llvm::DenseMap<Selector, Lists>::iterator; iterator begin() { return Methods.begin(); } iterator end() { return Methods.end(); } iterator find(Selector Sel) { return Methods.find(Sel); } std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) { return Methods.insert(Val); } int count(Selector Sel) const { return Methods.count(Sel); } bool empty() const { return Methods.empty(); } private: llvm::DenseMap<Selector, Lists> Methods; }; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; /// Increment when we find a reference; decrement when we find an ignored /// assignment. Ultimately the value is 0 if every reference is an ignored /// assignment. llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; private: Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; bool WarnedDarwinSDKInfoMissing = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); /// This virtual key function only exists to limit the emission of debug info /// describing the Sema class. GCC and Clang only emit debug info for a class /// with a vtable when the vtable is emitted. Sema is final and not /// polymorphic, but the debug info size savings are so significant that it is /// worth adding a vtable just to take advantage of this optimization. virtual void anchor(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, StringRef Platform); DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(); ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether deferrable diagnostics should be deferred. bool DeferDiags = false; /// RAII class to control scope of DeferDiags. class DeferDiagsRAII { Sema &S; bool SavedDeferDiags = false; public: DeferDiagsRAII(Sema &S, bool DeferDiags) : S(S), SavedDeferDiags(S.DeferDiags) { S.DeferDiags = DeferDiags; } ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } }; /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void setFunctionHasMustTail(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// Retrieve the current function, if any, that should be analyzed for /// potential availability violations. sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } /// Helper function to judge if we are in module purview. /// Return false if we are not in a module. bool isCurrentModulePurview() const { return getCurrentModule() ? getCurrentModule()->isModulePurview() : false; } /// Enter the scope of the global module. Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit); /// Leave the scope of the global module. void PopGlobalModuleFragment(); VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); // Returns the underlying type of a decltype with the given expression. QualType getDecltypeForExpr(Expr *E); QualType BuildTypeofExprType(Expr *E); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); void warnOnReservedIdentifier(const NamedDecl *D); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const BindingDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, /// Merge availability attributes for an implementation of /// an optional protocol requirement. AMK_OptionalProtocolImplementation }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. CCEK_Noexcept ///< Condition in a noexcept(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the /// correct number of arguments were passed, etc. Returns true if the /// attribute has been diagnosed. bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); llvm::Error isValidSectionSpecifier(StringRef Str); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, bool &HasDefault, bool &HasCommas, SmallVectorImpl<StringRef> &Strings); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Process the attributes before creating an attributed statement. Returns /// the semantic attributes that have been processed. void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesWithRange &InAttrs, SmallVectorImpl<const Attr *> &OutAttrs); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); struct NamedReturnInfo { const VarDecl *Candidate; enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; Status S; bool isMoveEligible() const { return S != None; }; bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } }; enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; NamedReturnInfo getNamedReturnInfo( Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves = false); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, bool AllowRecovery = false); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// If VD is set but not otherwise used, diagnose, for a parameter or a /// variable. void DiagnoseUnusedButSetDecl(const VarDecl *VD); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false, ArrayRef<const Expr *> StopAt = None); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the statements's reachability /// analysis. /// /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until /// the function body is parsed, and then do a basic reachability analysis to /// determine if the statement is reachable. If it is unreachable, the /// diagnostic will not be emitted. bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, const PartialDiagnostic &PD); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI); ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; } CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void FilterUsingLookup(Scope *S, LookupResult &lookup); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc, const LookupResult *R = nullptr, const UsingDecl *UD = nullptr); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists); NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr *> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); // Checks that the vector type should be initialized from a scalar // by splatting the value rather than populating a single element. // This is the case for AltiVecVector types as well as with // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); // Checks if the -faltivec-src-compat=gcc option is specified. // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are // treated the same way as they are when trying to initialize // these vectors on gcc (an error is emitted). bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); // Complete an enum decl, maybe without a scope spec. bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS = nullptr); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); // Substitute auto in TypeWithAuto for a Dependent auto type QualType SubstAutoTypeDependent(QualType TypeWithAuto); // Substitute auto in TypeWithAuto for a Dependent auto type TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } bool isImmediateFunctionContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isImmediateFunctionContext(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); /// Lookup 'coroutine_traits' in std namespace and std::experimental /// namespace. The namespace found is recorded in Namespace. ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc, NamespaceDecl *&Namespace); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; struct DeclareTargetContextInfo { struct MapInfo { OMPDeclareTargetDeclAttr::MapTypeTy MT; SourceLocation Loc; }; /// Explicitly listed variables and functions in a 'to' or 'link' clause. llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; /// The 'device_type' as parsed from the clause. OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; /// The directive kind, `begin declare target` or `declare target`. OpenMPDirectiveKind Kind; /// The directive with indirect clause. Optional<Expr *> Indirect; /// The directive location. SourceLocation Loc; DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc) {} }; /// Number of nested '#pragma omp declare target' directives. SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true, bool SuppressExprDiags = false); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Analyzes and checks a loop nest for use by a loop transformation. /// /// \param Kind The loop transformation directive kind. /// \param NumLoops How many nested loops the directive is expecting. /// \param AStmt Associated statement of the transformation directive. /// \param LoopHelpers [out] The loop analysis result. /// \param Body [out] The body code nested in \p NumLoops loop. /// \param OriginalInits [out] Collection of statements and declarations that /// must have been executed/declared before entering the /// loop. /// /// \return Whether there was any error. bool checkTransformableLoopNest( OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, Stmt *&Body, SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> &OriginalInits); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); /// Called on well-formed '\#pragma omp metadirective' after parsing /// of the associated statement. StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<std::string> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Called at the end of target region i.e. '#pragma omp end declare target'. const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); /// Called once a target context is completed, that can be when a /// '#pragma omp end declare target' was encountered or when a /// '#pragma omp declare target' without declaration-definition-seq was /// encountered. void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, DeclareTargetContextInfo &DTCI); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to /// an OpenMP loop directive. StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); /// Process a canonical OpenMP loop nest that can either be a canonical /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an /// OpenMP loop transformation construct. StmtResult ActOnOpenMPLoopnest(Stmt *AStmt); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '#pragma omp tile' after parsing of its clauses and /// the associated statement. StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '#pragma omp unroll' after parsing of its clauses /// and the associated statement. StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp interop'. StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp dispatch' after parsing of the // /associated statement. StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp masked' after parsing of the // /associated statement. StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp loop' after parsing of the /// associated statement. StmtResult ActOnOpenMPGenericLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \param NumAppendArgs The number of omp_interop_t arguments to account for /// in checking. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. /// \param AdjustArgsNothing The list of 'nothing' arguments. /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments. /// \param AppendArgs The list of 'append_args' arguments. /// \param AdjustArgsLoc The Location of an 'adjust_args' clause. /// \param AppendArgsLoc The Location of an 'append_args' clause. /// \param SR The SourceRange of the 'declare variant' directive. void ActOnOpenMPDeclareVariantDirective( FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef<Expr *> AdjustArgsNothing, ArrayRef<Expr *> AdjustArgsNeedDevicePtr, ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'align' clause. OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'sizes' clause. OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'full' clauses. OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-form 'partial' clauses. OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'when' clause. OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'compare' clause. OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'init' clause. OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'use' clause. OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'novariants' clause. OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'nocontext' clause. OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'filter' clause. OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause *ActOnOpenMPMapClause( ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, bool NoDiagnose = false, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// Called on a well-formed 'bind' clause. OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_PRValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. In the success case, /// the statement is rewritten to remove implicit nodes from the return /// value. bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); private: /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. bool checkMustTailAttr(const Stmt *St, const Attr &MTA); public: /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); bool areVectorTypesSameSize(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckMatrixCast - Check type constraints for matrix casts. // We allow casting between matrixes of the same dimensions i.e. when they // have the same number of rows and column. Returns true if the cast is // invalid. bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; QualType PreferredConditionType(ConditionKind K) const { return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy; } ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK = false); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD = nullptr); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, FunctionDecl *FD = nullptr) { return targetDiag(Loc, PD.getDiagID(), FD) << PD; } /// Check if the type is allowed to be used for the current target. void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D = nullptr); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); enum CUDAVariableTarget { CVT_Device, /// Emitted on device side with a shadow variable on host side CVT_Host, /// Emitted on host side only CVT_Both, /// Emitted on both sides with different addresses CVT_Unified, /// Emitted as a unified address, e.g. managed variables }; /// Determines whether the given variable is emitted on host or device side. CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); enum class AttributeCompletion { Attribute, Scope, None, }; void CodeCompleteAttribute( AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion = AttributeCompletion::Attribute, const IdentifierInfo *Scope = nullptr); /// Determines the preferred type of the current function argument, by /// examining the signatures of all possible overloads. /// Returns null if unknown or ambiguous, or if code completion is off. /// /// If the code completion point has been reached, also reports the function /// signatures that were considered. /// /// FIXME: rename to GuessCallArgumentType to reduce confusion. QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc, bool Braced); QualType ProduceCtorInitMemberSignatureHelp( Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, bool Braced); QualType ProduceTemplateArgumentSignatureHelp( TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinArithmeticFence(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); bool SemaBuiltinElementwiseMath(CallExpr *TheCall); bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); void deepTypeCheckForSYCLDevice(SourceLocation UsedAt, llvm::DenseSet<QualType> Visited, ValueDecl *DeclToCheck); }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
attribute.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % AAA TTTTT TTTTT RRRR IIIII BBBB U U TTTTT EEEEE % % A A T T R R I B B U U T E % % AAAAA T T RRRR I BBBB U U T EEE % % A A T T R R I B B U U T E % % A A T T R R IIIII BBBB UUU T EEEEE % % % % % % MagickCore Get / Set Image Attributes % % % % Software Design % % Cristy % % October 2002 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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 declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/draw.h" #include "magick/draw-private.h" #include "magick/effect.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/histogram.h" #include "magick/identify.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/magick.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/segment.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e B o u n d i n g B o x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageBoundingBox() returns the bounding box of an image canvas. % % The format of the GetImageBoundingBox method is: % % RectangleInfo GetImageBoundingBox(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o bounds: Method GetImageBoundingBox returns the bounding box of an % image canvas. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ typedef struct _EdgeInfo { double left, right, top, bottom; } EdgeInfo; static double GetEdgeBackgroundFactor(const Image *image, const CacheView *image_view,const GravityType gravity,const size_t width, const size_t height,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { CacheView *edge_view; const char *artifact; double factor; Image *edge_image; MagickPixelPacket background, pixel; RectangleInfo edge_geometry; register const PixelPacket *p; ssize_t y; /* Determine the percent of image background for this edge. */ switch (gravity) { case NorthWestGravity: case NorthGravity: default: { p=GetCacheViewVirtualPixels(image_view,0,0,1,1,exception); break; } case NorthEastGravity: case EastGravity: { p=GetCacheViewVirtualPixels(image_view,(ssize_t) image->columns-1,0,1,1, exception); break; } case SouthEastGravity: case SouthGravity: { p=GetCacheViewVirtualPixels(image_view,(ssize_t) image->columns-1, (ssize_t) image->rows-1,1,1,exception); break; } case SouthWestGravity: case WestGravity: { p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-1,1,1, exception); break; } } GetMagickPixelPacket(image,&background); SetMagickPixelPacket(image,p,(IndexPacket *) NULL,&background); artifact=GetImageArtifact(image,"trim:background-color"); if (artifact != (const char *) NULL) (void) QueryMagickColor(artifact,&background,exception); edge_geometry.width=width; edge_geometry.height=height; edge_geometry.x=x_offset; edge_geometry.y=y_offset; GravityAdjustGeometry(image->columns,image->rows,gravity,&edge_geometry); edge_image=CropImage(image,&edge_geometry,exception); if (edge_image == (Image *) NULL) return(0.0); factor=0.0; GetMagickPixelPacket(edge_image,&pixel); edge_view=AcquireVirtualCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) edge_image->columns; x++) { SetMagickPixelPacket(edge_image,p,(IndexPacket *) NULL,&pixel); if (IsMagickColorSimilar(&pixel,&background) == MagickFalse) factor++; p++; } } factor/=((double) edge_image->columns*edge_image->rows); edge_view=DestroyCacheView(edge_view); edge_image=DestroyImage(edge_image); return(factor); } static inline double GetMinEdgeBackgroundFactor(const EdgeInfo *edge) { double factor; factor=MagickMin(MagickMin(MagickMin(edge->left,edge->right),edge->top), edge->bottom); return(factor); } static RectangleInfo GetEdgeBoundingBox(const Image *image, ExceptionInfo *exception) { CacheView *edge_view; const char *artifact; double background_factor, percent_background; EdgeInfo edge, vertex; Image *edge_image; RectangleInfo bounds; /* Get the image bounding box. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); SetGeometry(image,&bounds); edge_image=CloneImage(image,0,0,MagickTrue,exception); if (edge_image == (Image *) NULL) return(bounds); (void) ParseAbsoluteGeometry("0x0+0+0",&edge_image->page); memset(&vertex,0,sizeof(vertex)); edge_view=AcquireVirtualCacheView(edge_image,exception); edge.left=GetEdgeBackgroundFactor(edge_image,edge_view,WestGravity, 1,0,0,0,exception); edge.right=GetEdgeBackgroundFactor(edge_image,edge_view,EastGravity, 1,0,0,0,exception); edge.top=GetEdgeBackgroundFactor(edge_image,edge_view,NorthGravity, 0,1,0,0,exception); edge.bottom=GetEdgeBackgroundFactor(edge_image,edge_view,SouthGravity, 0,1,0,0,exception); percent_background=1.0; artifact=GetImageArtifact(edge_image,"trim:percent-background"); if (artifact != (const char *) NULL) percent_background=StringToDouble(artifact,(char **) NULL)/100.0; percent_background=MagickMin(MagickMax(1.0-percent_background,MagickEpsilon), 1.0); background_factor=GetMinEdgeBackgroundFactor(&edge); for ( ; background_factor < percent_background; background_factor=GetMinEdgeBackgroundFactor(&edge)) { if ((bounds.width == 0) || (bounds.height == 0)) break; if (fabs(edge.left-background_factor) < MagickEpsilon) { /* Trim left edge. */ vertex.left++; bounds.width--; edge.left=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,1,bounds.height,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); edge.top=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); edge.bottom=GetEdgeBackgroundFactor(edge_image,edge_view, SouthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.bottom,exception); continue; } if (fabs(edge.right-background_factor) < MagickEpsilon) { /* Trim right edge. */ vertex.right++; bounds.width--; edge.right=GetEdgeBackgroundFactor(edge_image,edge_view, NorthEastGravity,1,bounds.height,(ssize_t) vertex.right,(ssize_t) vertex.top,exception); edge.top=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); edge.bottom=GetEdgeBackgroundFactor(edge_image,edge_view, SouthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.bottom,exception); continue; } if (fabs(edge.top-background_factor) < MagickEpsilon) { /* Trim top edge. */ vertex.top++; bounds.height--; edge.left=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,1,bounds.height,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); edge.right=GetEdgeBackgroundFactor(edge_image,edge_view, NorthEastGravity,1,bounds.height,(ssize_t) vertex.right,(ssize_t) vertex.top,exception); edge.top=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); continue; } if (fabs(edge.bottom-background_factor) < MagickEpsilon) { /* Trim bottom edge. */ vertex.bottom++; bounds.height--; edge.left=GetEdgeBackgroundFactor(edge_image,edge_view, NorthWestGravity,1,bounds.height,(ssize_t) vertex.left,(ssize_t) vertex.top,exception); edge.right=GetEdgeBackgroundFactor(edge_image,edge_view, NorthEastGravity,1,bounds.height,(ssize_t) vertex.right,(ssize_t) vertex.top,exception); edge.bottom=GetEdgeBackgroundFactor(edge_image,edge_view, SouthWestGravity,bounds.width,1,(ssize_t) vertex.left,(ssize_t) vertex.bottom,exception); continue; } } edge_view=DestroyCacheView(edge_view); edge_image=DestroyImage(edge_image); bounds.x=(ssize_t) vertex.left; bounds.y=(ssize_t) vertex.top; if ((bounds.width == 0) || (bounds.height == 0)) (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); return(bounds); } MagickExport RectangleInfo GetImageBoundingBox(const Image *image, ExceptionInfo *exception) { CacheView *image_view; const char *artifact; MagickBooleanType status; MagickPixelPacket target[3], zero; RectangleInfo bounds; register const PixelPacket *p; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); artifact=GetImageArtifact(image,"trim:percent-background"); if (artifact != (const char *) NULL) return(GetEdgeBoundingBox(image,exception)); bounds.width=0; bounds.height=0; bounds.x=(ssize_t) image->columns; bounds.y=(ssize_t) image->rows; GetMagickPixelPacket(image,&target[0]); image_view=AcquireVirtualCacheView(image,exception); p=GetCacheViewVirtualPixels(image_view,0,0,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); return(bounds); } SetMagickPixelPacket(image,p,GetCacheViewVirtualIndexQueue(image_view), &target[0]); GetMagickPixelPacket(image,&target[1]); p=GetCacheViewVirtualPixels(image_view,(ssize_t) image->columns-1,0,1,1, exception); if (p != (const PixelPacket *) NULL) SetMagickPixelPacket(image,p,GetCacheViewVirtualIndexQueue(image_view), &target[1]); GetMagickPixelPacket(image,&target[2]); p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-1,1,1, exception); if (p != (const PixelPacket *) NULL) SetMagickPixelPacket(image,p,GetCacheViewVirtualIndexQueue(image_view), &target[2]); status=MagickTrue; GetMagickPixelPacket(image,&zero); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickPixelPacket pixel; RectangleInfo bounding_box; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_GetImageBoundingBox) #endif bounding_box=bounds; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((x < bounding_box.x) && (IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse)) bounding_box.x=x; if ((x > (ssize_t) bounding_box.width) && (IsMagickColorSimilar(&pixel,&target[1]) == MagickFalse)) bounding_box.width=(size_t) x; if ((y < bounding_box.y) && (IsMagickColorSimilar(&pixel,&target[0]) == MagickFalse)) bounding_box.y=y; if ((y > (ssize_t) bounding_box.height) && (IsMagickColorSimilar(&pixel,&target[2]) == MagickFalse)) bounding_box.height=(size_t) y; p++; } #if defined(MAGICKCORE_OPENMP_SUPPORT) # pragma omp critical (MagickCore_GetImageBoundingBox) #endif { if (bounding_box.x < bounds.x) bounds.x=bounding_box.x; if (bounding_box.y < bounds.y) bounds.y=bounding_box.y; if (bounding_box.width > bounds.width) bounds.width=bounding_box.width; if (bounding_box.height > bounds.height) bounds.height=bounding_box.height; } } image_view=DestroyCacheView(image_view); if ((bounds.width == 0) || (bounds.height == 0)) (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); else { bounds.width-=(bounds.x-1); bounds.height-=(bounds.y-1); } return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelDepth() returns the depth of a particular image channel. % % The format of the GetImageChannelDepth method is: % % size_t GetImageDepth(const Image *image,ExceptionInfo *exception) % size_t GetImageChannelDepth(const Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport size_t GetImageDepth(const Image *image,ExceptionInfo *exception) { return(GetImageChannelDepth(image,CompositeChannels,exception)); } MagickExport size_t GetImageChannelDepth(const Image *image, const ChannelType channel,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t *current_depth, depth, number_threads; ssize_t y; /* Compute image depth. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); number_threads=(size_t) GetMagickResourceLimit(ThreadResource); current_depth=(size_t *) AcquireQuantumMemory(number_threads, sizeof(*current_depth)); if (current_depth == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); status=MagickTrue; for (i=0; i < (ssize_t) number_threads; i++) current_depth[i]=1; if ((image->storage_class == PseudoClass) && (image->matte == MagickFalse)) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->colors,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { const int id = GetOpenMPThreadId(); while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH) { MagickBooleanType atDepth; QuantumAny range; atDepth=MagickTrue; range=GetQuantumRange(current_depth[id]); if ((channel & RedChannel) != 0) if (IsPixelAtDepth(image->colormap[i].red,range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse) && ((channel & GreenChannel) != 0)) if (IsPixelAtDepth(image->colormap[i].green,range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse) && ((channel & BlueChannel) != 0)) if (IsPixelAtDepth(image->colormap[i].blue,range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse)) break; current_depth[id]++; } } depth=current_depth[0]; for (i=1; i < (ssize_t) number_threads; i++) if (depth < current_depth[i]) depth=current_depth[i]; current_depth=(size_t *) RelinquishMagickMemory(current_depth); return(depth); } image_view=AcquireVirtualCacheView(image,exception); #if !defined(MAGICKCORE_HDRI_SUPPORT) DisableMSCWarning(4127) if (1UL*QuantumRange <= MaxMap) RestoreMSCWarning { size_t *depth_map; /* Scale pixels to desired (optimized with depth map). */ depth_map=(size_t *) AcquireQuantumMemory(MaxMap+1,sizeof(*depth_map)); if (depth_map == (size_t *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); for (i=0; i <= (ssize_t) MaxMap; i++) { unsigned int depth; for (depth=1; depth < MAGICKCORE_QUANTUM_DEPTH; depth++) { Quantum pixel; QuantumAny range; range=GetQuantumRange(depth); pixel=(Quantum) i; if (pixel == ScaleAnyToQuantum(ScaleQuantumToAny(pixel,range),range)) break; } depth_map[i]=depth; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) continue; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { Quantum pixel; if ((channel & RedChannel) != 0) { pixel=GetPixelRed(p); if (depth_map[ScaleQuantumToMap(pixel)] > current_depth[id]) current_depth[id]=depth_map[ScaleQuantumToMap(pixel)]; } if ((channel & GreenChannel) != 0) { pixel=GetPixelGreen(p); if (depth_map[ScaleQuantumToMap(pixel)] > current_depth[id]) current_depth[id]=depth_map[ScaleQuantumToMap(pixel)]; } if ((channel & BlueChannel) != 0) { pixel=GetPixelBlue(p); if (depth_map[ScaleQuantumToMap(pixel)] > current_depth[id]) current_depth[id]=depth_map[ScaleQuantumToMap(pixel)]; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { pixel=GetPixelOpacity(p); if (depth_map[ScaleQuantumToMap(pixel)] > current_depth[id]) current_depth[id]=depth_map[ScaleQuantumToMap(pixel)]; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { pixel=GetPixelIndex(indexes+x); if (depth_map[ScaleQuantumToMap(pixel)] > current_depth[id]) current_depth[id]=depth_map[ScaleQuantumToMap(pixel)]; } p++; } if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH) status=MagickFalse; } image_view=DestroyCacheView(image_view); depth=current_depth[0]; for (i=1; i < (ssize_t) number_threads; i++) if (depth < current_depth[i]) depth=current_depth[i]; depth_map=(size_t *) RelinquishMagickMemory(depth_map); current_depth=(size_t *) RelinquishMagickMemory(current_depth); return(depth); } #endif #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) continue; indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { while (current_depth[id] < MAGICKCORE_QUANTUM_DEPTH) { MagickBooleanType atDepth; QuantumAny range; atDepth=MagickTrue; range=GetQuantumRange(current_depth[id]); if ((atDepth != MagickFalse) && ((channel & RedChannel) != 0)) if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse) && ((channel & GreenChannel) != 0)) if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse) && ((channel & BlueChannel) != 0)) if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse) && ((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) if (IsPixelAtDepth(GetPixelOpacity(p),range) == MagickFalse) atDepth=MagickTrue; if ((atDepth != MagickFalse) && ((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) atDepth=MagickFalse; if ((atDepth != MagickFalse)) break; current_depth[id]++; } p++; } if (current_depth[id] == MAGICKCORE_QUANTUM_DEPTH) status=MagickFalse; } image_view=DestroyCacheView(image_view); depth=current_depth[0]; for (i=1; i < (ssize_t) number_threads; i++) if (depth < current_depth[i]) depth=current_depth[i]; current_depth=(size_t *) RelinquishMagickMemory(current_depth); return(depth); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantumDepth() returns the depth of the image rounded to a legal % quantum depth: 8, 16, or 32. % % The format of the GetImageQuantumDepth method is: % % size_t GetImageQuantumDepth(const Image *image, % const MagickBooleanType constrain) % % A description of each parameter follows: % % o image: the image. % % o constrain: A value other than MagickFalse, constrains the depth to % a maximum of MAGICKCORE_QUANTUM_DEPTH. % */ MagickExport size_t GetImageQuantumDepth(const Image *image, const MagickBooleanType constrain) { size_t depth; depth=image->depth; if (depth <= 8) depth=8; else if (depth <= 16) depth=16; else if (depth <= 32) depth=32; else if (depth <= 64) depth=64; if (constrain != MagickFalse) depth=(size_t) MagickMin((double) depth,(double) MAGICKCORE_QUANTUM_DEPTH); return(depth); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageType() returns the potential type of image: % % Bilevel Grayscale GrayscaleMatte % Palette PaletteMatte TrueColor % TrueColorMatte ColorSeparation ColorSeparationMatte % % To ensure the image type matches its potential, use SetImageType(): % % (void) SetImageType(image,GetImageType(image)); % % The format of the GetImageType method is: % % ImageType GetImageType(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageType GetImageType(const Image *image,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->colorspace == CMYKColorspace) { if (image->matte == MagickFalse) return(ColorSeparationType); return(ColorSeparationMatteType); } if (IsMonochromeImage(image,exception) != MagickFalse) return(BilevelType); if (IsGrayImage(image,exception) != MagickFalse) { if (image->matte != MagickFalse) return(GrayscaleMatteType); return(GrayscaleType); } if (IsPaletteImage(image,exception) != MagickFalse) { if (image->matte != MagickFalse) return(PaletteMatteType); return(PaletteType); } if (image->matte != MagickFalse) return(TrueColorMatteType); return(TrueColorType); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I d e n t i f y I m a g e G r a y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % either 0 or QuantumRange. Otherwise undefined is returned. % % The format of the IdentifyImageGray method is: % % ImageType IdentifyImageGray(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageType IdentifyImageGray(const Image *image, ExceptionInfo *exception) { CacheView *image_view; ImageType type; register const PixelPacket *p; register ssize_t x; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->type == BilevelType) || (image->type == GrayscaleType) || (image->type == GrayscaleMatteType)) return(image->type); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(UndefinedType); type=BilevelType; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(p) == MagickFalse) { type=UndefinedType; break; } if ((type == BilevelType) && (IsPixelMonochrome(p) == MagickFalse)) type=GrayscaleType; p++; } if (type == UndefinedType) break; } image_view=DestroyCacheView(image_view); if ((type == GrayscaleType) && (image->matte != MagickFalse)) type=GrayscaleMatteType; return(type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I d e n t i f y I m a g e M o n o c h r o m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IdentifyImageMonochrome() returns MagickTrue if all the pixels in the image % have the same red, green, and blue intensities and the intensity is either % 0 or QuantumRange. % % The format of the IdentifyImageMonochrome method is: % % MagickBooleanType IdentifyImageMonochrome(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IdentifyImageMonochrome(const Image *image, ExceptionInfo *exception) { CacheView *image_view; ImageType type; register ssize_t x; register const PixelPacket *p; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->type == BilevelType) return(MagickTrue); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) return(MagickFalse); type=BilevelType; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelMonochrome(p) == MagickFalse) { type=UndefinedType; break; } p++; } if (type == UndefinedType) break; } image_view=DestroyCacheView(image_view); if (type == BilevelType) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I d e n t i f y I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IdentifyImageType() returns the potential type of image: % % Bilevel Grayscale GrayscaleMatte % Palette PaletteMatte TrueColor % TrueColorMatte ColorSeparation ColorSeparationMatte % % To ensure the image type matches its potential, use SetImageType(): % % (void) SetImageType(image,IdentifyImageType(image,exception),exception); % % The format of the IdentifyImageType method is: % % ImageType IdentifyImageType(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ImageType IdentifyImageType(const Image *image, ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->colorspace == CMYKColorspace) { if (image->matte == MagickFalse) return(ColorSeparationType); return(ColorSeparationMatteType); } if (IdentifyImageMonochrome(image,exception) != MagickFalse) return(BilevelType); if (IdentifyImageGray(image,exception) != UndefinedType) { if (image->matte != MagickFalse) return(GrayscaleMatteType); return(GrayscaleType); } if (IdentifyPaletteImage(image,exception) != MagickFalse) { if (image->matte != MagickFalse) return(PaletteMatteType); return(PaletteType); } if (image->matte != MagickFalse) return(TrueColorMatteType); return(TrueColorType); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s G r a y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGrayImage() returns MagickTrue if the type of the image is grayscale or % bi-level. % % The format of the IsGrayImage method is: % % MagickBooleanType IsGrayImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsGrayImage(const Image *image, ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); magick_unreferenced(exception); if ((image->type == BilevelType) || (image->type == GrayscaleType) || (image->type == GrayscaleMatteType)) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s M o n o c h r o m e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsMonochromeImage() returns MagickTrue if type of the image is bi-level. % % The format of the IsMonochromeImage method is: % % MagickBooleanType IsMonochromeImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsMonochromeImage(const Image *image, ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); magick_unreferenced(exception); if (image->type == BilevelType) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsOpaqueImage() returns MagickTrue if none of the pixels in the image have % an opacity value other than opaque (0). % % The format of the IsOpaqueImage method is: % % MagickBooleanType IsOpaqueImage(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType IsOpaqueImage(const Image *image, ExceptionInfo *exception) { CacheView *image_view; register const PixelPacket *p; register ssize_t x; ssize_t y; /* Determine if image is opaque. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->matte == MagickFalse) return(MagickTrue); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelOpacity(p) != OpaqueOpacity) break; p++; } if (x < (ssize_t) image->columns) break; } image_view=DestroyCacheView(image_view); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C h a n n e l D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageChannelDepth() sets the depth of the image. % % The format of the SetImageChannelDepth method is: % % MagickBooleanType SetImageDepth(Image *image,const size_t depth) % MagickBooleanType SetImageChannelDepth(Image *image, % const ChannelType channel,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o depth: the image depth. % */ MagickExport MagickBooleanType SetImageDepth(Image *image, const size_t depth) { return(SetImageChannelDepth(image,CompositeChannels,depth)); } MagickExport MagickBooleanType SetImageChannelDepth(Image *image, const ChannelType channel,const size_t depth) { CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; QuantumAny range; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (depth >= MAGICKCORE_QUANTUM_DEPTH) { image->depth=depth; return(MagickTrue); } range=GetQuantumRange(depth); if (image->storage_class == PseudoClass) { register ssize_t i; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { if ((channel & RedChannel) != 0) image->colormap[i].red=ScaleAnyToQuantum(ScaleQuantumToAny( ClampPixel((MagickRealType) image->colormap[i].red),range),range); if ((channel & GreenChannel) != 0) image->colormap[i].green=ScaleAnyToQuantum(ScaleQuantumToAny( ClampPixel((MagickRealType) image->colormap[i].green),range),range); if ((channel & BlueChannel) != 0) image->colormap[i].blue=ScaleAnyToQuantum(ScaleQuantumToAny( ClampPixel((MagickRealType) image->colormap[i].blue),range),range); if ((channel & OpacityChannel) != 0) image->colormap[i].opacity=ScaleAnyToQuantum(ScaleQuantumToAny( ClampPixel((MagickRealType) image->colormap[i].opacity),range), range); } } status=MagickTrue; exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if !defined(MAGICKCORE_HDRI_SUPPORT) DisableMSCWarning(4127) if (1UL*QuantumRange <= MaxMap) RestoreMSCWarning { Quantum *depth_map; register ssize_t i; /* Scale pixels to desired (optimized with depth map). */ depth_map=(Quantum *) AcquireQuantumMemory(MaxMap+1,sizeof(*depth_map)); if (depth_map == (Quantum *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); for (i=0; i <= (ssize_t) MaxMap; i++) depth_map[i]=ScaleAnyToQuantum(ScaleQuantumToAny((Quantum) i,range), range); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,depth_map[ScaleQuantumToMap(GetPixelRed(q))]); if ((channel & GreenChannel) != 0) SetPixelGreen(q,depth_map[ScaleQuantumToMap(GetPixelGreen(q))]); if ((channel & BlueChannel) != 0) SetPixelBlue(q,depth_map[ScaleQuantumToMap(GetPixelBlue(q))]); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,depth_map[ScaleQuantumToMap(GetPixelOpacity(q))]); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; continue; } } image_view=DestroyCacheView(image_view); depth_map=(Quantum *) RelinquishMagickMemory(depth_map); if (status != MagickFalse) image->depth=depth; return(status); } #endif /* Scale pixels to desired depth. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ScaleAnyToQuantum(ScaleQuantumToAny(ClampPixel( (MagickRealType) GetPixelRed(q)),range),range)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ScaleAnyToQuantum(ScaleQuantumToAny(ClampPixel( (MagickRealType) GetPixelGreen(q)),range),range)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ScaleAnyToQuantum(ScaleQuantumToAny(ClampPixel( (MagickRealType) GetPixelBlue(q)),range),range)); if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) SetPixelOpacity(q,ScaleAnyToQuantum(ScaleQuantumToAny(ClampPixel( (MagickRealType) GetPixelOpacity(q)),range),range)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) { status=MagickFalse; continue; } } image_view=DestroyCacheView(image_view); if (status != MagickFalse) image->depth=depth; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageType() sets the type of image. Choose from these types: % % BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, % PaletteMatteType, TrueColorType, TrueColorMatteType, % ColorSeparationType, ColorSeparationMatteType, OptimizeType % % The format of the SetImageType method is: % % MagickBooleanType SetImageType(Image *image,const ImageType type) % % A description of each parameter follows: % % o image: the image. % % o type: Image type. % */ MagickExport MagickBooleanType SetImageType(Image *image,const ImageType type) { const char *artifact; ImageInfo *image_info; MagickBooleanType status; QuantizeInfo *quantize_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); status=MagickTrue; image_info=AcquireImageInfo(); image_info->dither=image->dither; artifact=GetImageArtifact(image,"dither"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"dither",artifact); switch (type) { case BilevelType: { status=TransformImageColorspace(image,GRAYColorspace); (void) NormalizeImage(image); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=2; quantize_info->colorspace=GRAYColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); image->matte=MagickFalse; break; } case GrayscaleType: { status=TransformImageColorspace(image,GRAYColorspace); image->matte=MagickFalse; break; } case GrayscaleMatteType: { status=TransformImageColorspace(image,GRAYColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case PaletteType: { status=TransformImageColorspace(image,sRGBColorspace); if ((image->storage_class == DirectClass) || (image->colors > 256)) { quantize_info=AcquireQuantizeInfo(image_info); quantize_info->number_colors=256; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); } image->matte=MagickFalse; break; } case PaletteBilevelMatteType: { status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); (void) BilevelImageChannel(image,AlphaChannel,(double) QuantumRange/2.0); quantize_info=AcquireQuantizeInfo(image_info); status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case PaletteMatteType: { status=TransformImageColorspace(image,sRGBColorspace); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); quantize_info=AcquireQuantizeInfo(image_info); quantize_info->colorspace=TransparentColorspace; status=QuantizeImage(quantize_info,image); quantize_info=DestroyQuantizeInfo(quantize_info); break; } case TrueColorType: { status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case TrueColorMatteType: { status=TransformImageColorspace(image,sRGBColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case ColorSeparationType: { status=TransformImageColorspace(image,CMYKColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); image->matte=MagickFalse; break; } case ColorSeparationMatteType: { status=TransformImageColorspace(image,CMYKColorspace); if (image->storage_class != DirectClass) status=SetImageStorageClass(image,DirectClass); if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); break; } case OptimizeType: case UndefinedType: break; } image_info=DestroyImageInfo(image_info); if (status == MagickFalse) return(MagickFalse); image->type=type; return(MagickTrue); }
heated_plate_openmp.c
# include <stdlib.h> # include <stdio.h> # include <math.h> # include <omp.h> int main ( int argc, char *argv[] ); /******************************************************************************/ /* Michael: when I use CIVL-C input qualifiers the OMP2CIVL transformer breaks $input int M=5; // originally 500 $input int N=5; // originally 500 $input double EPSILON=0.1; // originally 0.001 */ #define M 5 #define N 5 #define EPSILON 0.1 int main ( int argc, char *argv[] ) /******************************************************************************/ /* Purpose: MAIN is the main program for HEATED_PLATE_OPENMP. Discussion: This code solves the steady state heat equation on a rectangular region. The sequential version of this program needs approximately 18/epsilon iterations to complete. The physical region, and the boundary conditions, are suggested by this diagram; W = 0 +------------------+ | | W = 100 | | W = 100 | | +------------------+ W = 100 The region is covered with a grid of M by N nodes, and an N by N array W is used to record the temperature. The correspondence between array indices and locations in the region is suggested by giving the indices of the four corners: I = 0 [0][0]-------------[0][N-1] | | J = 0 | | J = N-1 | | [M-1][0]-----------[M-1][N-1] I = M-1 The steady state solution to the discrete heat equation satisfies the following condition at an interior grid point: W[Central] = (1/4) * ( W[North] + W[South] + W[East] + W[West] ) where "Central" is the index of the grid point, "North" is the index of its immediate neighbor to the "north", and so on. Given an approximate solution of the steady state heat equation, a "better" solution is given by replacing each interior point by the average of its 4 neighbors - in other words, by using the condition as an ASSIGNMENT statement: W[Central] <= (1/4) * ( W[North] + W[South] + W[East] + W[West] ) If this process is repeated often enough, the difference between successive estimates of the solution will go to zero. This program carries out such an iteration, using a tolerance specified by the user, and writes the final estimate of the solution to a file that can be used for graphic processing. Licensing: This code is distributed under the GNU LGPL license. Modified: 18 October 2011 Author: Original C version by Michael Quinn. This C version by John Burkardt. Reference: Michael Quinn, Parallel Programming in C with MPI and OpenMP, McGraw-Hill, 2004, ISBN13: 978-0071232654, LC: QA76.73.C15.Q55. Local parameters: Local, double DIFF, the norm of the change in the solution from one iteration to the next. Local, double MEAN, the average of the boundary values, used to initialize the values of the solution in the interior. Local, double U[M][N], the solution at the previous iteration. Local, double W[M][N], the solution computed at the latest iteration. */ { double diff; double epsilon = EPSILON; int i; int iterations; int iterations_print; int j; double mean; double my_diff; double u[M][N]; double w[M][N]; double wtime; printf ( "\n" ); printf ( "HEATED_PLATE_OPENMP\n" ); printf ( " C/OpenMP version\n" ); printf ( " A program to solve for the steady state temperature distribution\n" ); printf ( " over a rectangular plate.\n" ); printf ( "\n" ); printf ( " Spatial grid of %d by %d points.\n", M, N ); printf ( " The iteration will be repeated until the change is <= %e\n", epsilon ); printf ( " Number of processors available = %d\n", omp_get_num_procs ( ) ); printf ( " Number of threads = %d\n", omp_get_max_threads ( ) ); /* Set the boundary values, which don't change. */ mean = 0.0; #pragma omp parallel shared ( w ) private ( i, j ) { #pragma omp for for ( i = 1; i < M - 1; i++ ) { w[i][0] = 100.0; } #pragma omp for for ( i = 1; i < M - 1; i++ ) { w[i][N-1] = 100.0; } #pragma omp for for ( j = 0; j < N; j++ ) { w[M-1][j] = 100.0; } #pragma omp for for ( j = 0; j < N; j++ ) { w[0][j] = 0.0; } /* Average the boundary values, to come up with a reasonable initial value for the interior. */ #pragma omp for reduction ( + : mean ) for ( i = 1; i < M - 1; i++ ) { mean = mean + w[i][0] + w[i][N-1]; } #pragma omp for reduction ( + : mean ) for ( j = 0; j < N; j++ ) { mean = mean + w[M-1][j] + w[0][j]; } } /* OpenMP note: You cannot normalize MEAN inside the parallel region. It only gets its correct value once you leave the parallel region. So we interrupt the parallel region, set MEAN, and go back in. */ mean = mean / ( double ) ( 2 * M + 2 * N - 4 ); printf ( "\n" ); printf ( " MEAN = %f\n", mean ); /* Initialize the interior solution to the mean value. */ #pragma omp parallel shared ( mean, w ) private ( i, j ) { #pragma omp for for ( i = 1; i < M - 1; i++ ) { for ( j = 1; j < N - 1; j++ ) { w[i][j] = mean; } } } /* iterate until the new solution W differs from the old solution U by no more than EPSILON. */ iterations = 0; iterations_print = 1; printf ( "\n" ); printf ( " Iteration Change\n" ); printf ( "\n" ); wtime = omp_get_wtime ( ); diff = epsilon; while ( epsilon <= diff ) { # pragma omp parallel shared ( u, w ) private ( i, j ) { /* Save the old solution in U. */ # pragma omp for for ( i = 0; i < M; i++ ) { for ( j = 0; j < N; j++ ) { u[i][j] = w[i][j]; } } /* Determine the new estimate of the solution at the interior points. The new solution W is the average of north, south, east and west neighbors. */ # pragma omp for for ( i = 1; i < M - 1; i++ ) { for ( j = 1; j < N - 1; j++ ) { w[i][j] = ( u[i-1][j] + u[i+1][j] + u[i][j-1] + u[i][j+1] ) / 4.0; } } } /* C and C++ cannot compute a maximum as a reduction operation. Therefore, we define a private variable MY_DIFF for each thread. Once they have all computed their values, we use a CRITICAL section to update DIFF. */ diff = 0.0; # pragma omp parallel shared ( diff, u, w ) private ( i, j, my_diff ) { my_diff = 0.0; # pragma omp for for ( i = 1; i < M - 1; i++ ) { for ( j = 1; j < N - 1; j++ ) { if ( my_diff < fabs ( w[i][j] - u[i][j] ) ) { my_diff = fabs ( w[i][j] - u[i][j] ); } } } # pragma omp critical { if ( diff < my_diff ) { diff = my_diff; } } } iterations++; if ( iterations == iterations_print ) { printf ( " %8d %f\n", iterations, diff ); iterations_print = 2 * iterations_print; } } wtime = omp_get_wtime ( ) - wtime; printf ( "\n" ); printf ( " %8d %f\n", iterations, diff ); printf ( "\n" ); printf ( " Error tolerance achieved.\n" ); printf ( " Wallclock time = %f\n", wtime ); /* Terminate. */ printf ( "\n" ); printf ( "HEATED_PLATE_OPENMP:\n" ); printf ( " Normal end of execution.\n" ); return 0; # undef M # undef N }
cpu_ctx.h
#ifndef MOBULA_INCLUDE_CONTEXT_CPU_CTX_H_ #define MOBULA_INCLUDE_CONTEXT_CPU_CTX_H_ #define MOBULA_KERNEL void #define MOBULA_DEVICE #include <algorithm> #include <cmath> #include <cstring> #include <mutex> #include <thread> #include "../ctypes.h" #include "./common.h" namespace mobula { #if USING_CBLAS #include <cblas.h> inline void blas_gemm(const int axis, const bool tA, const bool tB, const int M, const int N, const int K, const float alpha, const float *A, const int lda, const float *B, const int ldb, const float beta, float *C, const int ldc) { cblas_sgemm(axis == 0 ? CblasRowMajor : CblasColMajor, tA ? CblasTrans : CblasNoTrans, tB ? CblasTrans : CblasNoTrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } #endif using std::abs; using std::max; using std::min; #if USING_OPENMP inline MOBULA_DEVICE float atomic_add(const float val, float *address) { #pragma omp atomic update *address += val; return *address; } #elif HOST_NUM_THREADS > 1 // Naive CPU constexpr int NUM_MOBULA_ATOMIC_ADD_MUTEXES = HOST_NUM_THREADS * 8; static std::mutex MOBULA_ATOMIC_ADD_MUTEXES[NUM_MOBULA_ATOMIC_ADD_MUTEXES]; inline MOBULA_DEVICE float atomic_add(const float val, float *address) { uintptr_t id = (reinterpret_cast<uintptr_t>(address) / sizeof(float)) % NUM_MOBULA_ATOMIC_ADD_MUTEXES; std::lock_guard<std::mutex> lock(MOBULA_ATOMIC_ADD_MUTEXES[id]); *address += val; return *address; } #else // no lock for single thread mode inline MOBULA_DEVICE float atomic_add(const float val, float *address) { *address += val; return *address; } #endif template <typename T> T *new_array(size_t size) { return new T[size]; } template <typename T> void del_array(T *p) { delete[] p; } template <typename T> T *MemcpyHostToDev(T *dst, const T *src, size_t size) { if (dst == src) return dst; return static_cast<T *>(memcpy(dst, src, size)); } template <typename T> T *MemcpyDevToHost(T *dst, const T *src, size_t size) { if (dst == src) return dst; return static_cast<T *>(memcpy(dst, src, size)); } template <typename T> T *MemcpyDevToDev(T *dst, const T *src, size_t size) { if (dst == src) return dst; return static_cast<T *>(memcpy(dst, src, size)); } } // namespace mobula #define KERNEL_RUN_BEGIN(device_id) \ { \ UNUSED(device_id) #define KERNEL_RUN_END() } #define KERNEL_RUN_STREAM(a, strm) KERNEL_RUN(a) #if USING_OPENMP #include "./openmp_ctx.h" #else #include "./naive_ctx.h" #endif #endif // MOBULA_INCLUDE_CONTEXT_CPU_CTX_H_
Graph.h
/* * Graph.h * * Created on: 01.06.2014 * Author: Christian Staudt (christian.staudt@kit.edu), Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com) */ #ifndef GRAPH_H_ #define GRAPH_H_ #include <algorithm> #include <vector> #include <stack> #include <queue> #include <utility> #include <stdexcept> #include <functional> #include "../Globals.h" #include "Coordinates.h" #include "../viz/Point.h" #include "../auxiliary/Random.h" #include "../auxiliary/FunctionTraits.h" #include "../auxiliary/Log.h" namespace NetworKit { /** * @ingroup graph * A graph (with optional weights) and parallel iterator methods. */ class Graph final { friend class ParallelPartitionCoarsening; friend class GraphBuilder; private: // graph attributes count id; //!< unique graph id, starts at 0 std::string name; //!< name of the graph, initially G#ID // scalars count n; //!< current number of nodes count m; //!< current number of edges count storedNumberOfSelfLoops; //!< current number of self loops, edges which have the same origin and target node z; //!< current upper bound of node ids, z will be the id of the next node edgeid omega; //!< current upper bound of edge ids, will be the id of the next edge count t; //!< current time step bool weighted; //!< true if the graph is weighted, false otherwise bool directed; //!< true if the graph is directed, false otherwise bool edgesIndexed; //!< true if edge ids have been assigned // per node data std::vector<bool> exists; //!< exists[v] is true if node v has not been removed from the graph Coordinates<float> coordinates; //!< coordinates of nodes (if present) std::vector<count> inDeg; //!< only used for directed graphs, number of edges incoming per node std::vector<count> outDeg; //!< degree of every node, zero if node was removed. For directed graphs only outgoing edges count std::vector< std::vector<node> > inEdges; //!< only used for directed graphs, inEdges[v] contains all nodes u that have an edge (u, v) std::vector< std::vector<node> > outEdges; //!< (outgoing) edges, for each edge (u, v) v is saved in outEdges[u] and for undirected also u in outEdges[v] std::vector< std::vector<edgeweight> > inEdgeWeights; //!< only used for directed graphs, same schema as inEdges std::vector< std::vector<edgeweight> > outEdgeWeights; //!< same schema (and same order!) as outEdges std::vector< std::vector<edgeid> > inEdgeIds; //!< only used for directed graphs, same schema as inEdges std::vector< std::vector<edgeid> > outEdgeIds; //!< same schema (and same order!) as outEdges /** * Returns the next unique graph id. */ count getNextGraphId(); /** * Returns the index of node u in the array of incoming edges of node v. (for directed graphs inEdges is searched, while for indirected outEdges is searched, which gives the same result as indexInOutEdgeArray). */ index indexInInEdgeArray(node v, node u) const; /** * Returns the index of node v in the array of outgoing edges of node u. */ index indexInOutEdgeArray(node u, node v) const; /** * Returns the edge weight of the outgoing edge of index i in the outgoing edges of node u * @param u The node * @param i The index * @return The weight of the outgoing edge or defaultEdgeWeight if the graph is unweighted */ template<bool hasWeights> inline edgeweight getOutEdgeWeight(node u, index i) const; /** * Returns the edge weight of the incoming edge of index i in the incoming edges of node u * * @param u The node * @param i The index in the incoming edge array * @return The weight of the incoming edge */ template<bool hasWeights> inline edgeweight getInEdgeWeight(node u, index i) const; /** * Returns the edge id of the edge of index i in the outgoing edges of node u * * @param u The node * @param i The index in the outgoing edges * @return The edge id */ template<bool graphHasEdgeIds> inline edgeid getOutEdgeId(node u, index i) const; /** * Returns the edge id of the edge of index i in the incoming edges of node u * * @param u The node * @param i The index in the incoming edges of u * @return The edge id */ template<bool graphHasEdgeIds> inline edgeid getInEdgeId(node u, index i) const; /** * @brief Returns if the edge (u, v) shall be used in the iteration of all edgesIndexed * * @param u The source node of the edge * @param v The target node of the edge * @return If the node shall be used, i.e. if v is not none and in the undirected case if u >= v */ template<bool graphIsDirected> inline bool useEdgeInIteration(node u, node v) const; /** * @brief Implementation of the for loop for outgoing edges of u * * Note: If all (valid) outgoing edges shall be considered, graphIsDirected needs to be set to true * * @param u The node * @param handle The handle that shall be executed for each edge * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forOutEdgesOfImpl(node u, L handle) const; /** * @brief Implementation of the for loop for incoming edges of u * * For undirected graphs, this is the same as forOutEdgesOfImpl but u and v are changed in the handle * * @param u The node * @param handle The handle that shall be executed for each edge * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forInEdgesOfImpl(node u, L handle) const; /** * @brief Implementation of the for loop for all edges, @see forEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void forEdgeImpl(L handle) const; /** * @brief Parallel implementation of the for loop for all edges, @see parallelForEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void parallelForEdgesImpl(L handle) const; /** * @brief Summation variant of the parallel for loop for all edges, @see parallelSumForEdges * * @param handle The handle that shall be executed for all edges * @return void */ template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline double parallelSumForEdgesImpl(L handle) const; /* * In the following definition, Aux::FunctionTraits is used in order to only execute lambda functions * with the appropriate parameters. The decltype-return type is used for determining the return type of * the lambda (needed for summation) but also determines if the lambda accepts the correct number of parameters. * Otherwise the return type declaration fails and the function is excluded from overload resoluation. * Then there are multiple possible lambdas with three (third parameter id or weight) and two (second parameter * can be second node id or edge weight for neighbor iterators). This is checked using Aux::FunctionTraits and * std::enable_if. std::enable_if only defines the type member when the given bool is true, this bool comes from * std::is_same which compares two types. The function traits give either the parameter type or if it is out of bounds * they define type as void. */ /** * Triggers a static assert error when no other method is chosen. Because of the use of "..." as arguments, the priority * of this method is lower than the priority of the other methods. This method avoids ugly and unreadable template substitution * error messages from the other declarations. */ template<class F, void* = (void*)0> typename Aux::FunctionTraits<F>::result_type edgeLambda(F&f, ...) const { // the strange condition is used in order to delay the eveluation of the static assert to the moment when this function is actually used static_assert(! std::is_same<F, F>::value, "Your lambda does not support the required parameters or the parameters have the wrong type."); return std::declval<typename Aux::FunctionTraits<F>::result_type>(); // use the correct return type (this won't compile) } /** * Calls the given function f if its fourth argument is of the type edgeid and third of type edgeweight * Note that the decltype check is not enough as edgeweight can be casted to node and we want to assure that . */ template < class F, typename std::enable_if < (Aux::FunctionTraits<F>::arity >= 3) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<2>::type>::value && std::is_same<edgeid, typename Aux::FunctionTraits<F>::template arg<3>::type>::value >::type * = (void*)0 > auto edgeLambda(F &f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, v, ew, id)) { return f(u, v, ew, id); } /** * Calls the given function f if its third argument is of the type edgeid, discards the edge weight * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 2) && std::is_same<edgeid, typename Aux::FunctionTraits<F>::template arg<2>::type>::value && std::is_same<node, typename Aux::FunctionTraits<F>::template arg<1>::type>::value /* prevent f(v, weight, eid) */ >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, v, id)) { return f(u, v, id); } /** * Calls the given function f if its third argument is of type edgeweight, discards the edge id * Note that the decltype check is not enough as node can be casted to edgeweight. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 2) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<2>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, v, ew)) { return f(u, v, ew); } /** * Calls the given function f if it has only two arguments and the second argument is of type node, * discards edge weight and id * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 1) && std::is_same<node, typename Aux::FunctionTraits<F>::template arg<1>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, v)) { return f(u, v); } /** * Calls the given function f if it has only two arguments and the second argument is of type edgeweight, * discards the first node and the edge id * Note that the decltype check is not enough as edgeweight can be casted to node. */ template<class F, typename std::enable_if< (Aux::FunctionTraits<F>::arity >= 1) && std::is_same<edgeweight, typename Aux::FunctionTraits<F>::template arg<1>::type>::value >::type* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(u, ew)) { return f(v, ew); } /** * Calls the given function f if it has only one argument, discards the first * node id, the edge weight and the edge id */ template<class F, void* = (void*)0> auto edgeLambda(F&f, node u, node v, edgeweight ew, edgeid id) const -> decltype(f(v)) { return f(v); } /** * Calls the given BFS handle with distance parameter */ template <class F> auto callBFSHandle(F &f, node u, count dist) const -> decltype(f(u, dist)) { return f(u, dist); } /** * Calls the given BFS handle without distance parameter */ template <class F> auto callBFSHandle(F &f, node u, count dist) const -> decltype(f(u)) { return f(u); } public: /** * Create a graph of @a n nodes. The graph has assignable edge weights if @a weighted is set to <code>true</code>. * If @a weighted is set to <code>false</code> each edge has edge weight 1.0 and any other weight assignment will * be ignored. * @param n Number of nodes. * @param weighted If set to <code>true</code>, the graph has edge weights. * @param directed If set to @c true, the graph will be directed. */ Graph(count n = 0, bool weighted = false, bool directed = false); Graph(const Graph& G, bool weighted, bool directed); /** * Create a graph as copy of @a other. * @param other The graph to copy. */ Graph(const Graph& other) = default; /** Default move constructor */ Graph(Graph&& other) = default; /** Default destructor */ ~Graph() = default; /** Default move assignment operator */ Graph& operator=(Graph&& other) = default; /** Default copy assignment operator */ Graph& operator=(const Graph& other) = default; /** EDGE IDS **/ /** * Initially assign integer edge identifiers. * * @param force Force re-indexing of edges even if they have already been indexed */ void indexEdges(bool force = false); /** * Checks if edges have been indexed * * @return bool if edges have been indexed */ bool hasEdgeIds() const { return edgesIndexed; } /** * Get the id of the given edge. */ edgeid edgeId(node u, node v) const; /** * Get an upper bound for the edge ids in the graph. * @return An upper bound for the edge ids. */ index upperEdgeIdBound() const { return omega; } /** GRAPH INFORMATION **/ /** * Get the ID of this graph. The ID is a unique unsigned integer given to * every graph on construction. */ count getId() const { return id; } /** * Return the type of the graph. * Graph: not weighted, undirected * WeightedGraph: weighted, undirected * DirectedGraph: not weighted, directed * WeightedDirectedGraph: weighted, directed */ std::string typ() const; /** * Try to save some memory by shrinking internal data structures of the graph. Only run this * once you finished editing the graph. Otherwise it will cause unnecessary reallocation of * memory. */ void shrinkToFit(); /** * Compacts the adjacency arrays by re-using no longer neede slots from deleted edges. */ void compactEdges(); /** * Sorts the adjacency arrays by node id. While the running time is linear this * temporarily duplicates the memory. */ void sortEdges(); /** * Set name of graph to @a name. * @param name The name. */ void setName(std::string name) { this->name = name; } /* * Returns the name of the graph. * @return The name of the graph. */ std::string getName() const { return name; } /** * Returns a string representation of the graph. * @return A string representation. */ std::string toString() const; /* COPYING */ /* * Copies all nodes to a new graph * @return graph with the same nodes. */ Graph copyNodes() const; /* NODE MODIFIERS */ /** * Add a new node to the graph and return it. * @return The new node. */ node addNode(); /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Add a new node to the graph with coordinates @a x and @y and return it. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] node addNode(float x, float y); /** * Remove an isolated node @a v from the graph. * * @param u Node. * @note Although it would be convenient to remove all incident edges at the same time, * this causes complications for dynamic applications. Therefore, removeNode is an * atomic event. All incident edges need to be removed first and an exception is thrown * otherwise. */ void removeNode(node v); /** * Check if node @a v exists in the graph. * * @param v Node. * @return @c true if @a v exists, @c false otherwise. */ bool hasNode(node v) const { return (v < z) && this->exists[v]; } /** * Restores a previously deleted node @a v with its previous id in the graph. * * @param v Node. * */ void restoreNode(node v); /** NODE PROPERTIES **/ /** * Returns the number of outgoing neighbors of @a v. * * @param v Node. * @return The number of outgoing neighbors. */ count degree(node v) const { return outDeg[v]; } /** * Get the number of incoming neighbors of @a v. * * @param v Node. * @return The number of incoming neighbors. * @note If the graph is not directed, the outgoing degree is returned. */ count degreeIn(node v) const { return directed ? inDeg[v] : outDeg[v]; } /** * Get the number of outgoing neighbors of @a v. * * @param v Node. * @return The number of outgoing neighbors. */ count degreeOut(node v) const { return outDeg[v]; } /** * Check whether @a v is isolated, i.e. degree is 0. * @param v Node. * @return @c true if the node is isolated (= degree is 0) */ bool isIsolated(node v) const { return outDeg[v] == 0 && (!directed || inDeg[v] == 0); } /** * Returns the weighted degree of @a v. * * @param v Node. * @return Weighted degree of @a v. * @note For directed graphs this is the sum of weights of all outgoing edges of @a v. */ edgeweight weightedDegree(node v) const; /** * Returns the volume of the @a v, which is the weighted degree with self-loops counted twice. * * @param v Node. * @return The volume of the @a v. */ edgeweight volume(node v) const; /** * Returns a random node of the graph. * @return A random node. */ node randomNode() const; /** * Returns a random neighbor of @a u and @c none if degree is zero. * * @param u Node. * @return A random neighbor of @a u. */ node randomNeighbor(node u) const; /* EDGE MODIFIERS */ /** * Insert an edge between the nodes @a u and @a v. If the graph is weighted you can optionally * set a weight for this edge. The default weight is 1.0. * Note: Multi-edges are not supported and will NOT be handled consistently by the graph data * structure. * @param u Endpoint of edge. * @param v Endpoint of edge. * @param weight Optional edge weight. */ void addEdge(node u, node v, edgeweight ew = defaultEdgeWeight); /** * Removes the undirected edge {@a u,@a v}. * @param u Endpoint of edge. * @param v Endpoint of edge. */ void removeEdge(node u, node v); /** * Removes all self-loops in the graph. */ void removeSelfLoops(); /** * Changes the edges {@a s1, @a t1} into {@a s1, @a t2} and the edge {@a s2, @a t2} into {@a s2, @a t1}. * * If there are edge weights or edge ids, they are preserved. Note that no check is performed if the swap is actually possible, i.e. does not generate duplicate edges. * * @param s1 The first source * @param t1 The first target * @param s2 The second source * @param t2 The second target */ void swapEdge(NetworKit::node s1, NetworKit::node t1, NetworKit::node s2, NetworKit::node t2); /** * Checks if undirected edge {@a u,@a v} exists in the graph. * @param u Endpoint of edge. * @param v Endpoint of edge. * @return <code>true</code> if the edge exists, <code>false</code> otherwise. */ bool hasEdge(node u, node v) const; /** * Returns a random edge. By default a random node u is chosen and then some random neighbor v. So the probability of choosing (u, v) highly * depends on the degree of u. * Setting uniformDistribution to true, will give you a real uniform distributed edge, but will be very slow. So only use uniformDistribution * for single calls outside of any loops. */ std::pair<node, node> randomEdge(bool uniformDistribution = false) const; /** * Returns a vector with nr random edges. The edges are chosen uniform random. */ std::vector< std::pair<node, node> > randomEdges(count nr) const; /* GLOBAL PROPERTIES */ /** * Returns <code>true</code> if this graph supports edge weights other than 1.0. * @return <code>true</code> if this graph supports edge weights other than 1.0. */ bool isWeighted() const { return weighted; } /** * Return @c true if this graph supports directed edges. * @return @c true if this graph supports directed edges. */ bool isDirected() const { return directed; } /** * Return <code>true</code> if graph contains no nodes. * @return <code>true</code> if graph contains no nodes. */ bool isEmpty() const { return n == 0; } /** * Return the number of nodes in the graph. * @return The number of nodes. */ count numberOfNodes() const { return n; } /** * Return the number of edges in the graph. * @return The number of edges. */ count numberOfEdges() const { return m; } /** * @return a pair (n, m) where n is the number of nodes and m is the number of edges */ std::pair<count, count> const size() { return {n, m}; }; /** * @return the density of the graph */ double density() const { count n = numberOfNodes(); count m = numberOfEdges(); count loops = numberOfSelfLoops(); m -= loops; double d; if (isDirected()) { d = m / (double) (n * (n-1)); } else { d = (2 * m) / (double) (n * (n-1)); } return d; } /** * Return the number of loops {v,v} in the graph. * @return The number of loops. * @note This involves calculation, so store result if needed multiple times. */ count numberOfSelfLoops() const; /** * Get an upper bound for the node ids in the graph. * @return An upper bound for the node ids. */ index upperNodeIdBound() const { return z; } /** * Check for invalid graph states, such as multi-edges. * @return False if the graph is in invalid state. */ bool checkConsistency() const; /* DYNAMICS */ /** * Trigger a time step - increments counter. */ void timeStep() { t++; } /** * Get time step counter. * @return Time step counter. */ count time() { return t; } /* COORDINATES */ /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Sets the coordinate of @a v to @a value. * * @param v Node. * @param value The coordinate of @a v. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] void setCoordinate(node v, Point<float> value) { coordinates.setCoordinate(v, value); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get the coordinate of @a v. * @param v Node. * @return The coordinate of @a v. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] Point<float>& getCoordinate(node v) { return coordinates.getCoordinate(v); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get minimum coordinate of all coordinates with respect to dimension @a dim. * @param dim The dimension to search for minimum. * @return The minimum coordinate in dimension @a dim. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] float minCoordinate(count dim) { return coordinates.minCoordinate(dim); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Get maximum coordinate of all coordinates with respect to dimension @a dim. * @param dim The dimension to search for maximum. * @return The maximum coordinate in dimension @a dim. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] float maxCoordinate(count dim) { return coordinates.maxCoordinate(dim); } /** * DEPRECATED: Coordinates should be handled outside the Graph class * like general node attributes. * * Initializes the coordinates for the nodes in graph. * @note This has to be called once and before you set coordinates. Call this method again if new nodes have * been added. */ // TODO: remove method // [[deprecated("Deprecated: Node coordinates should be stored externally like any other node attribute")]] void initCoordinates() { coordinates.init(z); } /* EDGE ATTRIBUTES */ /** * Return edge weight of edge {@a u,@a v}. Returns 0 if edge does not exist. * BEWARE: Running time is \Theta(deg(u))! * * @param u Endpoint of edge. * @param v Endpoint of edge. * @return Edge weight of edge {@a u,@a v} or 0 if edge does not exist. */ edgeweight weight(node u, node v) const; /** * Set the weight of an edge. If the edge does not exist, * it will be inserted. * * @param[in] u endpoint of edge * @param[in] v endpoint of edge * @param[in] weight edge weight */ void setWeight(node u, node v, edgeweight ew); /** * Increase the weight of an edge. If the edge does not exist, * it will be inserted. * * @param[in] u endpoint of edge * @param[in] v endpoint of edge * @param[in] weight edge weight */ void increaseWeight(node u, node v, edgeweight ew); /* SUMS */ /** * Returns the sum of all edge weights. * @return The sum of all edge weights. */ edgeweight totalEdgeWeight() const; /* Collections */ /** * Get list of all nodes. * @return List of all nodes. */ std::vector<node> nodes() const; /** * Get list of edges as node pairs. * @return List of edges as node pairs. */ std::vector<std::pair<node, node> > edges() const; /** * Get list of neighbors of @a u. * * @param u Node. * @return List of neighbors of @a u. */ std::vector<node> neighbors(node u) const; /* Derivative Graphs */ /** * Return an undirected version of this graph. * * @return undirected graph. */ Graph toUndirected() const; /** * Return the transpose of this graph. The graph must be directed. * * @return transpose of the graph. */ Graph transpose() const; /* NODE ITERATORS */ /** * Iterate over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void forNodes(L handle) const; /** * Iterate randomly over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void parallelForNodes(L handle) const; /** Iterate over all nodes of the graph and call @a handle (lambda closure) as long as @a condition remains true. * This allows for breaking from a node loop. * * @param condition Returning <code>false</code> breaks the loop. * @param handle Takes parameter <code>(node)</code>. */ template<typename C, typename L> void forNodesWhile(C condition, L handle) const; /** * Iterate randomly over all nodes of the graph and call @a handle (lambda closure). * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void forNodesInRandomOrder(L handle) const; /** * Iterate in parallel over all nodes of the graph and call handler (lambda closure). * Using schedule(guided) to remedy load-imbalances due to e.g. unequal degree distribution. * * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void balancedParallelForNodes(L handle) const; /** * Iterate over all undirected pairs of nodes and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>. */ template<typename L> void forNodePairs(L handle) const; /** * Iterate over all undirected pairs of nodes in parallel and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>. */ template<typename L> void parallelForNodePairs(L handle) const; /* EDGE ITERATORS */ /** * Iterate over all edges of the const graph and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code>, <code>(node, node, edgweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code>. */ template<typename L> void forEdges(L handle) const; /** * Iterate in parallel over all edges of the const graph and call @a handle (lambda closure). * * @param handle Takes parameters <code>(node, node)</code> or <code>(node, node, edgweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code>. */ template<typename L> void parallelForEdges(L handle) const; /* NEIGHBORHOOD ITERATORS */ /** * Iterate over all neighbors of a node and call @a handle (lamdba closure). * * @param u Node. * @param handle Takes parameter <code>(node)</code> or <code>(node, edgeweight)</code> which is a neighbor of @a u. * @note For directed graphs only outgoing edges from @a u are considered. * A node is its own neighbor if there is a self-loop. * */ template<typename L> void forNeighborsOf(node u, L handle) const; /** * Iterate over all incident edges of a node and call @a handle (lamdba closure). * * @param u Node. * @param handle Takes parameters <code>(node, node)</code>, <code>(node, node, edgeweight)</code>, <code>(node, node, edgeid)</code> or <code>(node, node, edgeweight, edgeid)</code> where the first node is @a u and the second is a neighbor of @a u. * @note For undirected graphs all edges incident to @a u are also outgoing edges. */ template<typename L> void forEdgesOf(node u, L handle) const; /** * Iterate over all neighbors of a node and call handler (lamdba closure). * For directed graphs only incoming edges from u are considered. */ template<typename L> void forInNeighborsOf(node u, L handle) const; /** * Iterate over all incoming edges of a node and call handler (lamdba closure). * @note For undirected graphs all edges incident to u are also incoming edges. * * Handle takes parameters (u, v) or (u, v, w) where w is the edge weight. */ template<typename L> void forInEdgesOf(node u, L handle) const; /* REDUCTION ITERATORS */ /** * Iterate in parallel over all nodes and sum (reduce +) the values returned by the handler */ template<typename L> double parallelSumForNodes(L handle) const; /** * Iterate in parallel over all edges and sum (reduce +) the values returned by the handler */ template<typename L> double parallelSumForEdges(L handle) const; /* GRAPH SEARCHES */ /** * Iterate over nodes in breadth-first search order starting from r until connected component * of r has been visited. * * @param r Node. * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void BFSfrom(node r, L handle) const; template<typename L> void BFSfrom(const std::vector<node> &startNodes, L handle) const; template<typename L> void BFSEdgesFrom(node r, L handle) const; /** * Iterate over nodes in depth-first search order starting from r until connected component * of r has been visited. * * @param r Node. * @param handle Takes parameter <code>(node)</code>. */ template<typename L> void DFSfrom(node r, L handle) const; template<typename L> void DFSEdgesFrom(node r, L handle) const; }; /* NODE ITERATORS */ template<typename L> void Graph::forNodes(L handle) const { for (node v = 0; v < z; ++v) { if (exists[v]) { handle(v); } } } template<typename L> void Graph::parallelForNodes(L handle) const { #pragma omp parallel for for (node v = 0; v < z; ++v) { if (exists[v]) { handle(v); } } } template<typename C, typename L> void Graph::forNodesWhile(C condition, L handle) const { for (node v = 0; v < z; ++v) { if (exists[v]) { if (!condition()) { break; } handle(v); } } } template<typename L> void Graph::forNodesInRandomOrder(L handle) const { std::vector<node> randVec = nodes(); std::shuffle(randVec.begin(), randVec.end(), Aux::Random::getURNG()); for (node v : randVec) { handle(v); } } template<typename L> void Graph::balancedParallelForNodes(L handle) const { #pragma omp parallel for schedule(guided) // TODO: define min block size (and test it!) for (node v = 0; v < z; ++v) { if (exists[v]) { handle(v); } } } template<typename L> void Graph::forNodePairs(L handle) const { for (node u = 0; u < z; ++u) { if (exists[u]) { for (node v = u + 1; v < z; ++v) { if (exists[v]) { handle(u, v); } } } } } template<typename L> void Graph::parallelForNodePairs(L handle) const { #pragma omp parallel for schedule(guided) for (node u = 0; u < z; ++u) { if (exists[u]) { for (node v = u + 1; v < z; ++v) { if (exists[v]) { handle(u, v); } } } } } /* EDGE ITERATORS */ /* HELPERS */ template<bool hasWeights> // implementation for weighted == true inline edgeweight Graph::getOutEdgeWeight(node u, index i) const { return outEdgeWeights[u][i]; } template<> // implementation for weighted == false inline edgeweight Graph::getOutEdgeWeight<false>(node, index) const { return defaultEdgeWeight; } template<bool hasWeights> // implementation for weighted == true inline edgeweight Graph::getInEdgeWeight(node u, index i) const { return inEdgeWeights[u][i]; } template<> // implementation for weighted == false inline edgeweight Graph::getInEdgeWeight<false>(node, index) const { return defaultEdgeWeight; } template<bool graphHasEdgeIds> // implementation for hasEdgeIds == true inline edgeid Graph::getOutEdgeId(node u, index i) const { return outEdgeIds[u][i]; } template<> // implementation for hasEdgeIds == false inline edgeid Graph::getOutEdgeId<false>(node, index) const { return 0; } template<bool graphHasEdgeIds> // implementation for hasEdgeIds == true inline edgeid Graph::getInEdgeId(node u, index i) const { return inEdgeIds[u][i]; } template<> // implementation for hasEdgeIds == false inline edgeid Graph::getInEdgeId<false>(node, index) const { return 0; } template<bool graphIsDirected> // implementation for graphIsDirected == true inline bool Graph::useEdgeInIteration(node u, node v) const { return v != none; } template<> // implementation for graphIsDirected == false inline bool Graph::useEdgeInIteration<false>(node u, node v) const { return u >= v; } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forOutEdgesOfImpl(node u, L handle) const { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; if (useEdgeInIteration<graphIsDirected>(u, v)) { edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forInEdgesOfImpl(node u, L handle) const { if (graphIsDirected) { for (index i = 0; i < inEdges[u].size(); i++) { node v = inEdges[u][i]; if (useEdgeInIteration<true>(u, v)) { edgeLambda<L>(handle, u, v, getInEdgeWeight<hasWeights>(u, i), getInEdgeId<graphHasEdgeIds>(u, i)); } } } else { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; if (useEdgeInIteration<true>(u, v)) { edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::forEdgeImpl(L handle) const { for (node u = 0; u < z; ++u) { forOutEdgesOfImpl<graphIsDirected, hasWeights, graphHasEdgeIds, L>(u, handle); } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline void Graph::parallelForEdgesImpl(L handle) const { #pragma omp parallel for schedule(guided) for (node u = 0; u < z; ++u) { forOutEdgesOfImpl<graphIsDirected, hasWeights, graphHasEdgeIds, L>(u, handle); } } template<bool graphIsDirected, bool hasWeights, bool graphHasEdgeIds, typename L> inline double Graph::parallelSumForEdgesImpl(L handle) const { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for (node u = 0; u < z; ++u) { for (index i = 0; i < outEdges[u].size(); ++i) { node v = outEdges[u][i]; // undirected, do not iterate over edges twice // {u, v} instead of (u, v); if v == none, u > v is not fulfilled if (useEdgeInIteration<graphIsDirected>(u, v)) { sum += edgeLambda<L>(handle, u, v, getOutEdgeWeight<hasWeights>(u, i), getOutEdgeId<graphHasEdgeIds>(u, i)); } } } return sum; } template<typename L> void Graph::forEdges(L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edgeIds forEdgeImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edgeIds forEdgeImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edgeIds forEdgeImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edgeIds forEdgeImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edgeIds forEdgeImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edgeIds forEdgeImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edgeIds forEdgeImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edgeIds forEdgeImpl<true, true, true, L>(handle); break; } } template<typename L> void Graph::parallelForEdges(L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edgeIds parallelForEdgesImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edgeIds parallelForEdgesImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edgeIds parallelForEdgesImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edgeIds parallelForEdgesImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edgeIds parallelForEdgesImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edgeIds parallelForEdgesImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edgeIds parallelForEdgesImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edgeIds parallelForEdgesImpl<true, true, true, L>(handle); break; } } /* NEIGHBORHOOD ITERATORS */ template<typename L> void Graph::forNeighborsOf(node u, L handle) const { forEdgesOf(u, handle); } template<typename L> void Graph::forEdgesOf(node u, L handle) const { switch (weighted + 2 * edgesIndexed) { case 0: //not weighted, no edge ids forOutEdgesOfImpl<true, false, false, L>(u, handle); break; case 1: //weighted, no edge ids forOutEdgesOfImpl<true, true, false, L>(u, handle); break; case 2: //not weighted, with edge ids forOutEdgesOfImpl<true, false, true, L>(u, handle); break; case 3: //weighted, with edge ids forOutEdgesOfImpl<true, true, true, L>(u, handle); break; } } template<typename L> void Graph::forInNeighborsOf(node u, L handle) const { forInEdgesOf(u, handle); } template<typename L> void Graph::forInEdgesOf(node u, L handle) const { switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: //unweighted, undirected, no edge ids forInEdgesOfImpl<false, false, false, L>(u, handle); break; case 1: //weighted, undirected, no edge ids forInEdgesOfImpl<false, true, false, L>(u, handle); break; case 2: //unweighted, directed, no edge ids forInEdgesOfImpl<true, false, false, L>(u, handle); break; case 3: //weighted, directed, no edge ids forInEdgesOfImpl<true, true, false, L>(u, handle); break; case 4: //unweighted, undirected, with edge ids forInEdgesOfImpl<false, false, true, L>(u, handle); break; case 5: //weighted, undirected, with edge ids forInEdgesOfImpl<false, true, true, L>(u, handle); break; case 6: //unweighted, directed, with edge ids forInEdgesOfImpl<true, false, true, L>(u, handle); break; case 7: //weighted, directed, with edge ids forInEdgesOfImpl<true, true, true, L>(u, handle); break; } } /* REDUCTION ITERATORS */ template<typename L> double Graph::parallelSumForNodes(L handle) const { double sum = 0.0; #pragma omp parallel for reduction(+:sum) for (node v = 0; v < z; ++v) { if (exists[v]) { sum += handle(v); } } return sum; } template<typename L> double Graph::parallelSumForEdges(L handle) const { double sum = 0.0; switch (weighted + 2 * directed + 4 * edgesIndexed) { case 0: // unweighted, undirected, no edge ids sum = parallelSumForEdgesImpl<false, false, false, L>(handle); break; case 1: // weighted, undirected, no edge ids sum = parallelSumForEdgesImpl<false, true, false, L>(handle); break; case 2: // unweighted, directed, no edge ids sum = parallelSumForEdgesImpl<true, false, false, L>(handle); break; case 3: // weighted, directed, no edge ids sum = parallelSumForEdgesImpl<true, true, false, L>(handle); break; case 4: // unweighted, undirected, with edge ids sum = parallelSumForEdgesImpl<false, false, true, L>(handle); break; case 5: // weighted, undirected, with edge ids sum = parallelSumForEdgesImpl<false, true, true, L>(handle); break; case 6: // unweighted, directed, with edge ids sum = parallelSumForEdgesImpl<true, false, true, L>(handle); break; case 7: // weighted, directed, with edge ids sum = parallelSumForEdgesImpl<true, true, true, L>(handle); break; } return sum; } /* GRAPH SEARCHES */ template<typename L> void Graph::BFSfrom(node r, L handle) const { std::vector<node> startNodes(1, r); BFSfrom(startNodes, handle); } template<typename L> void Graph::BFSfrom(const std::vector<node> &startNodes, L handle) const { std::vector<bool> marked(z); std::queue<node> q, qNext; count dist = 0; // enqueue start nodes for (node u : startNodes) { q.push(u); marked[u] = true; } do { node u = q.front(); q.pop(); // apply function callBFSHandle(handle, u, dist); forNeighborsOf(u, [&](node v) { if (!marked[v]) { qNext.push(v); marked[v] = true; } }); if (q.empty() && !qNext.empty()) { q.swap(qNext); ++dist; } } while (!q.empty()); } template<typename L> void Graph::BFSEdgesFrom(node r, L handle) const { std::vector<bool> marked(z); std::queue<node> q; q.push(r); // enqueue root marked[r] = true; do { node u = q.front(); q.pop(); // apply function forNeighborsOf(u, [&](node, node v, edgeweight w, edgeid eid) { if (!marked[v]) { handle(u, v, w, eid); q.push(v); marked[v] = true; } }); } while (!q.empty()); } template<typename L> void Graph::DFSfrom(node r, L handle) const { std::vector<bool> marked(z); std::stack<node> s; s.push(r); // enqueue root marked[r] = true; do { node u = s.top(); s.pop(); // apply function handle(u); forNeighborsOf(u, [&](node v) { if (!marked[v]) { s.push(v); marked[v] = true; } }); } while (!s.empty()); } template<typename L> void Graph::DFSEdgesFrom(node r, L handle) const { std::vector<bool> marked(z); std::stack<node> s; s.push(r); // enqueue root marked[r] = true; do { node u = s.top(); s.pop(); // apply function forNeighborsOf(u, [&](node v) { if (!marked[v]) { handle(u, v); s.push(v); marked[v] = true; } }); } while (!s.empty()); } } /* namespace NetworKit */ #endif /* GRAPH_H_ */
erodr.c
#include <time.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include "vector.h" #include "io.h" #include "image.h" #include "params.h" #include "util.h" /* * Particle type. */ typedef struct particle { vec2 pos; vec2 dir; double vel; double sediment; double water; } particle; /* * gradient & height tuple. */ typedef struct hg_tuple { vec2 gradient; double height; } hg_tuple; /* * Bilinearly interpolate double value at (x, y) in map. */ double bil_interpolate_map_double(const image *map, vec2 pos) { double *map_buffer = (double *) map->buffer; double u, v, ul, ur, ll, lr, ipl_l, ipl_r; int x_i = (int)pos.x; int y_i = (int)pos.y; u = pos.x - x_i; v = pos.y - y_i; ul = map_buffer[y_i*map->width + x_i]; ur = map_buffer[y_i*map->width + x_i + 1]; ll = map_buffer[(y_i + 1)*map->width + x_i]; lr = map_buffer[(y_i + 1)*map->width + x_i + 1]; ipl_l = (1 - v) * ul + v * ll; ipl_r = (1 - v) * ur + v * lr; return (1 - u) * ipl_l + u * ipl_r; } /* * Deposits sediment at position `pos` in heighmap `hmap`. * Deposition only affect immediate neighbouring gridpoints * to `pos`. */ void deposit(image *hmap, vec2 pos, double amount) { double *hmap_buffer = (double *) hmap->buffer; int x_i = (int)pos.x; int y_i = (int)pos.y; double u = pos.x - x_i; double v = pos.y - y_i; hmap_buffer[y_i*hmap->width + x_i] += amount * (1 - u) * (1 - v); hmap_buffer[y_i*hmap->width + x_i + 1] += amount * u * (1 - v); hmap_buffer[(y_i + 1)*hmap->width + x_i] += amount * (1 - u) * v; hmap_buffer[(y_i + 1)*hmap->width + x_i + 1] += amount * u * v; } /* * Erodes heighmap `hmap` at position `pos` by amount `amount`. * Erosion is distributed over an area defined through p_radius. */ void erode(image *hmap, vec2 pos, double amount, int radius) { double *hmap_buffer = (double *) hmap->buffer; if(radius < 1){ deposit(hmap, pos, -amount); return; } int x0 = (int)pos.x - radius; int y0 = (int)pos.y - radius; int x_start = max(0, x0); int y_start = max(0, y0); int x_end = min(hmap->width, x0+2*radius+1); int y_end = min(hmap->height, y0+2*radius+1); // construct erosion/deposition kernel. double kernel[2*radius + 1][2*radius + 1]; double kernel_sum = 0; for(int y = y_start; y < y_end; y++) { for(int x = x_start; x < x_end; x++) { double d_x = x - pos.x; double d_y = y - pos.y; double distance = sqrt(d_x*d_x + d_y*d_y); double w = fmax(0, radius - distance); kernel_sum += w; kernel[y-y0][x-x0] = w; } } // normalize weights and apply changes on heighmap. for(int y = y_start; y < y_end; y++) { for(int x = x_start; x < x_end; x++) { kernel[y-y0][x-x0] /= kernel_sum; hmap_buffer[y*hmap->width + x] -= amount * kernel[y-y0][x-x0]; } } } /* * Returns gradient at (int x, int y) on heightmap `hmap`. */ vec2 gradient_at(image *hmap, int x, int y) { double *hmap_buffer = (double *) hmap->buffer; int idx = y * hmap->width + x; //int right = y * hmap->width + min(x, hmap->width - 2); //int below = min(y, hmap->height - 2) * hmap->width + x; int right = idx + ((x > hmap->width - 2) ? 0 : 1); int below = idx + ((y > hmap->height - 2) ? 0 : hmap->width); vec2 g; g.x = hmap_buffer[right] - hmap_buffer[idx]; g.y = hmap_buffer[below] - hmap_buffer[idx]; return g; } /* * Returns interpolated gradient and height at (double x, double y) on * heightmap `hmap`. */ hg_tuple height_gradient_at(image *hmap, vec2 pos) { hg_tuple ret; vec2 ul, ur, ll, lr, ipl_l, ipl_r; int x_i = (int)pos.x; int y_i = (int)pos.y; double u = pos.x - x_i; double v = pos.y - y_i; ul = gradient_at(hmap, x_i, y_i); ur = gradient_at(hmap, x_i + 1, y_i); ll = gradient_at(hmap, x_i, y_i + 1); lr = gradient_at(hmap, x_i + 1, y_i + 1); ipl_l = add(scalar_mul(1 - v, ul), scalar_mul(v, ll)); ipl_r = add(scalar_mul(1 - v, ur), scalar_mul(v, lr)); ret.gradient = add(scalar_mul(1 - u, ipl_l), scalar_mul(u, ipl_r)); ret.height = bil_interpolate_map_double(hmap, pos); return ret; } /* * Runs hydraulic erosion simulation. */ void simulate_particles(image *hmap, sim_params *params) { srand(time(NULL)); // simulate each particle #pragma omp parallel for for(int i = 0; i < params->n; i++) { if(!((i+1) % 10000)) printf("Particles simulated: %d\n", i+1); // spawn particle. particle p; double denom = (RAND_MAX / ((double)hmap->width - 1.0)); p.pos = (vec2){(double)rand() / denom, (double)rand() / denom}; p.dir = (vec2){0, 0}; p.vel = 0; p.sediment = 0; p.water = 1; for(int j = 0; j < params->ttl; j++) { // interpolate gradient g and height h_old at p's position. vec2 pos_old = p.pos; hg_tuple hg = height_gradient_at(hmap, pos_old); vec2 g = hg.gradient; double h_old = hg.height; // calculate new dir vector p.dir = sub( scalar_mul(params->p_enertia, p.dir), scalar_mul(1 - params->p_enertia, g) ); normalize(&p.dir); // calculate new pos p.pos = add(p.pos, p.dir); // check bounds vec2 pos_new = p.pos; if(pos_new.x > (hmap->width-1) || pos_new.x < 0 || pos_new.y > (hmap->height-1) || pos_new.y < 0) break; // new height double h_new = bil_interpolate_map_double(hmap, pos_new); double h_diff = h_new - h_old; // sediment capacity double c = fmax(-h_diff, params->p_min_slope) * p.vel * p.water * params->p_capacity; // decide whether to erode or deposit depending on particle properties if(h_diff > 0 || p.sediment > c) { double to_deposit = (h_diff > 0) ? fmin(p.sediment, h_diff) : (p.sediment - c) * params->p_deposition; p.sediment -= to_deposit; deposit(hmap, pos_old, to_deposit); } else { double to_erode = fmin((c - p.sediment) * params->p_erosion, -h_diff); p.sediment += to_erode; erode(hmap, pos_old, to_erode, params->p_radius); } // update `vel` and `water` p.vel = sqrt(p.vel*p.vel + h_diff*params->p_gravity); p.water *= (1 - params->p_evaporation); } } } /* * Main. */ int main(int argc, char *argv[]) { sim_params params = DEFAULT_PARAM; image img; // parse args. char filepath[FILEPATH_MAXLEN]; char outputfilepath[FILEPATH_MAXLEN]; strcpy(outputfilepath, OUTPUTFILEPATH_DEFAULT); bool ascii_out = false; if(parse_args(argc, argv, filepath, outputfilepath, &params, &ascii_out)) exit_with_info(1); // load pgm heightmap. if(load_pgm(filepath, &img)) exit_with_info(1); // simulate hydraulic erosion simulate_particles(&img, &params); // Save results save_pgm(outputfilepath, &img, ascii_out); // free memory release_image(&img); }
c-parser.c
/* Parser for C and Objective-C. Copyright (C) 1987, 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc. Parser actions based on the old Bison parser; structure somewhat influenced by and fragments based on the C++ parser. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* TODO: Make sure all relevant comments, and all relevant code from all actions, brought over from old parser. Verify exact correspondence of syntax accepted. Add testcases covering every input symbol in every state in old and new parsers. Include full syntax for GNU C, including erroneous cases accepted with error messages, in syntax productions in comments. Make more diagnostics in the front end generally take an explicit location rather than implicitly using input_location. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "tree.h" #include "rtl.h" #include "langhooks.h" #include "input.h" #include "cpplib.h" #include "timevar.h" #include "c-pragma.h" #include "c-tree.h" #include "flags.h" #include "output.h" #include "toplev.h" #include "ggc.h" #include "c-common.h" #include "vec.h" #include "target.h" #include "cgraph.h" /* Miscellaneous data and functions needed for the parser. */ int yydebug; /* Objective-C specific parser/lexer information. */ static int objc_pq_context = 0; /* The following flag is needed to contextualize Objective-C lexical analysis. In some cases (e.g., 'int NSObject;'), it is undesirable to bind an identifier to an Objective-C class, even if a class with that name exists. */ static int objc_need_raw_identifier = 0; #define OBJC_NEED_RAW_IDENTIFIER(VAL) \ do { \ if (c_dialect_objc ()) \ objc_need_raw_identifier = VAL; \ } while (0) /* The reserved keyword table. */ struct resword { const char *word; ENUM_BITFIELD(rid) rid : 16; unsigned int disable : 16; }; /* Disable mask. Keywords are disabled if (reswords[i].disable & mask) is _true_. */ #define D_C89 0x01 /* not in C89 */ #define D_EXT 0x02 /* GCC extension */ #define D_EXT89 0x04 /* GCC extension incorporated in C99 */ #define D_OBJC 0x08 /* Objective C only */ static const struct resword reswords[] = { { "_Bool", RID_BOOL, 0 }, { "_Complex", RID_COMPLEX, 0 }, { "_Decimal32", RID_DFLOAT32, D_EXT }, { "_Decimal64", RID_DFLOAT64, D_EXT }, { "_Decimal128", RID_DFLOAT128, D_EXT }, { "__FUNCTION__", RID_FUNCTION_NAME, 0 }, { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 }, { "__alignof", RID_ALIGNOF, 0 }, { "__alignof__", RID_ALIGNOF, 0 }, { "__asm", RID_ASM, 0 }, { "__asm__", RID_ASM, 0 }, { "__attribute", RID_ATTRIBUTE, 0 }, { "__attribute__", RID_ATTRIBUTE, 0 }, { "__builtin_choose_expr", RID_CHOOSE_EXPR, 0 }, { "__builtin_offsetof", RID_OFFSETOF, 0 }, { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, 0 }, { "__builtin_va_arg", RID_VA_ARG, 0 }, { "__complex", RID_COMPLEX, 0 }, { "__complex__", RID_COMPLEX, 0 }, { "__const", RID_CONST, 0 }, { "__const__", RID_CONST, 0 }, { "__extension__", RID_EXTENSION, 0 }, { "__func__", RID_C99_FUNCTION_NAME, 0 }, { "__imag", RID_IMAGPART, 0 }, { "__imag__", RID_IMAGPART, 0 }, { "__inline", RID_INLINE, 0 }, { "__inline__", RID_INLINE, 0 }, { "__label__", RID_LABEL, 0 }, { "__real", RID_REALPART, 0 }, { "__real__", RID_REALPART, 0 }, { "__restrict", RID_RESTRICT, 0 }, { "__restrict__", RID_RESTRICT, 0 }, { "__signed", RID_SIGNED, 0 }, { "__signed__", RID_SIGNED, 0 }, { "__thread", RID_THREAD, 0 }, { "__typeof", RID_TYPEOF, 0 }, { "__typeof__", RID_TYPEOF, 0 }, { "__volatile", RID_VOLATILE, 0 }, { "__volatile__", RID_VOLATILE, 0 }, { "asm", RID_ASM, D_EXT }, { "auto", RID_AUTO, 0 }, { "break", RID_BREAK, 0 }, { "case", RID_CASE, 0 }, { "char", RID_CHAR, 0 }, { "const", RID_CONST, 0 }, { "continue", RID_CONTINUE, 0 }, { "default", RID_DEFAULT, 0 }, { "do", RID_DO, 0 }, { "double", RID_DOUBLE, 0 }, { "else", RID_ELSE, 0 }, { "enum", RID_ENUM, 0 }, { "extern", RID_EXTERN, 0 }, { "float", RID_FLOAT, 0 }, { "for", RID_FOR, 0 }, { "goto", RID_GOTO, 0 }, { "if", RID_IF, 0 }, { "inline", RID_INLINE, D_EXT89 }, { "int", RID_INT, 0 }, { "long", RID_LONG, 0 }, { "register", RID_REGISTER, 0 }, { "restrict", RID_RESTRICT, D_C89 }, { "return", RID_RETURN, 0 }, { "short", RID_SHORT, 0 }, { "signed", RID_SIGNED, 0 }, { "sizeof", RID_SIZEOF, 0 }, { "static", RID_STATIC, 0 }, { "struct", RID_STRUCT, 0 }, { "switch", RID_SWITCH, 0 }, { "typedef", RID_TYPEDEF, 0 }, { "typeof", RID_TYPEOF, D_EXT }, { "union", RID_UNION, 0 }, { "unsigned", RID_UNSIGNED, 0 }, { "void", RID_VOID, 0 }, { "volatile", RID_VOLATILE, 0 }, { "while", RID_WHILE, 0 }, /* These Objective-C keywords are recognized only immediately after an '@'. */ { "class", RID_AT_CLASS, D_OBJC }, { "compatibility_alias", RID_AT_ALIAS, D_OBJC }, { "defs", RID_AT_DEFS, D_OBJC }, { "encode", RID_AT_ENCODE, D_OBJC }, { "end", RID_AT_END, D_OBJC }, { "implementation", RID_AT_IMPLEMENTATION, D_OBJC }, { "interface", RID_AT_INTERFACE, D_OBJC }, { "private", RID_AT_PRIVATE, D_OBJC }, { "protected", RID_AT_PROTECTED, D_OBJC }, { "protocol", RID_AT_PROTOCOL, D_OBJC }, { "public", RID_AT_PUBLIC, D_OBJC }, { "selector", RID_AT_SELECTOR, D_OBJC }, { "throw", RID_AT_THROW, D_OBJC }, { "try", RID_AT_TRY, D_OBJC }, { "catch", RID_AT_CATCH, D_OBJC }, { "finally", RID_AT_FINALLY, D_OBJC }, { "synchronized", RID_AT_SYNCHRONIZED, D_OBJC }, /* These are recognized only in protocol-qualifier context (see above) */ { "bycopy", RID_BYCOPY, D_OBJC }, { "byref", RID_BYREF, D_OBJC }, { "in", RID_IN, D_OBJC }, { "inout", RID_INOUT, D_OBJC }, { "oneway", RID_ONEWAY, D_OBJC }, { "out", RID_OUT, D_OBJC }, }; #define N_reswords (sizeof reswords / sizeof (struct resword)) /* All OpenMP clauses. OpenMP 2.5. */ typedef enum pragma_omp_clause { PRAGMA_OMP_CLAUSE_NONE = 0, PRAGMA_OMP_CLAUSE_COLLAPSE, PRAGMA_OMP_CLAUSE_COPYIN, PRAGMA_OMP_CLAUSE_COPYPRIVATE, PRAGMA_OMP_CLAUSE_DEFAULT, PRAGMA_OMP_CLAUSE_FIRSTPRIVATE, PRAGMA_OMP_CLAUSE_IF, PRAGMA_OMP_CLAUSE_LASTPRIVATE, PRAGMA_OMP_CLAUSE_NOWAIT, PRAGMA_OMP_CLAUSE_NUM_THREADS, PRAGMA_OMP_CLAUSE_ORDERED, PRAGMA_OMP_CLAUSE_PRIVATE, PRAGMA_OMP_CLAUSE_REDUCTION, PRAGMA_OMP_CLAUSE_SCHEDULE, PRAGMA_OMP_CLAUSE_SHARED, PRAGMA_OMP_CLAUSE_UNTIED } pragma_omp_clause; /* Initialization routine for this file. */ void c_parse_init (void) { /* The only initialization required is of the reserved word identifiers. */ unsigned int i; tree id; int mask = (flag_isoc99 ? 0 : D_C89) | (flag_no_asm ? (flag_isoc99 ? D_EXT : D_EXT|D_EXT89) : 0); if (!c_dialect_objc ()) mask |= D_OBJC; ridpointers = GGC_CNEWVEC (tree, (int) RID_MAX); for (i = 0; i < N_reswords; i++) { /* If a keyword is disabled, do not enter it into the table and so create a canonical spelling that isn't a keyword. */ if (reswords[i].disable & mask) continue; id = get_identifier (reswords[i].word); C_RID_CODE (id) = reswords[i].rid; C_IS_RESERVED_WORD (id) = 1; ridpointers [(int) reswords[i].rid] = id; } } /* The C lexer intermediates between the lexer in cpplib and c-lex.c and the C parser. Unlike the C++ lexer, the parser structure stores the lexer information instead of using a separate structure. Identifiers are separated into ordinary identifiers, type names, keywords and some other Objective-C types of identifiers, and some look-ahead is maintained. ??? It might be a good idea to lex the whole file up front (as for C++). It would then be possible to share more of the C and C++ lexer code, if desired. */ /* The following local token type is used. */ /* A keyword. */ #define CPP_KEYWORD ((enum cpp_ttype) (N_TTYPES + 1)) /* More information about the type of a CPP_NAME token. */ typedef enum c_id_kind { /* An ordinary identifier. */ C_ID_ID, /* An identifier declared as a typedef name. */ C_ID_TYPENAME, /* An identifier declared as an Objective-C class name. */ C_ID_CLASSNAME, /* Not an identifier. */ C_ID_NONE } c_id_kind; /* A single C token after string literal concatenation and conversion of preprocessing tokens to tokens. */ typedef struct c_token GTY (()) { /* The kind of token. */ ENUM_BITFIELD (cpp_ttype) type : 8; /* If this token is a CPP_NAME, this value indicates whether also declared as some kind of type. Otherwise, it is C_ID_NONE. */ ENUM_BITFIELD (c_id_kind) id_kind : 8; /* If this token is a keyword, this value indicates which keyword. Otherwise, this value is RID_MAX. */ ENUM_BITFIELD (rid) keyword : 8; /* If this token is a CPP_PRAGMA, this indicates the pragma that was seen. Otherwise it is PRAGMA_NONE. */ ENUM_BITFIELD (pragma_kind) pragma_kind : 7; /* True if this token is from a system header. */ BOOL_BITFIELD in_system_header : 1; /* The value associated with this token, if any. */ tree value; /* The location at which this token was found. */ location_t location; } c_token; /* A parser structure recording information about the state and context of parsing. Includes lexer information with up to two tokens of look-ahead; more are not needed for C. */ typedef struct c_parser GTY(()) { /* The look-ahead tokens. */ c_token tokens[2]; /* How many look-ahead tokens are available (0, 1 or 2). */ short tokens_avail; /* True if a syntax error is being recovered from; false otherwise. c_parser_error sets this flag. It should clear this flag when enough tokens have been consumed to recover from the error. */ BOOL_BITFIELD error : 1; /* True if we're processing a pragma, and shouldn't automatically consume CPP_PRAGMA_EOL. */ BOOL_BITFIELD in_pragma : 1; } c_parser; /* The actual parser and external interface. ??? Does this need to be garbage-collected? */ static GTY (()) c_parser *the_parser; /* Read in and lex a single token, storing it in *TOKEN. */ static void c_lex_one_token (c_token *token) { timevar_push (TV_LEX); token->type = c_lex_with_flags (&token->value, &token->location, NULL); token->id_kind = C_ID_NONE; token->keyword = RID_MAX; token->pragma_kind = PRAGMA_NONE; token->in_system_header = in_system_header; switch (token->type) { case CPP_NAME: { tree decl; int objc_force_identifier = objc_need_raw_identifier; OBJC_NEED_RAW_IDENTIFIER (0); if (C_IS_RESERVED_WORD (token->value)) { enum rid rid_code = C_RID_CODE (token->value); if (c_dialect_objc ()) { if (!OBJC_IS_AT_KEYWORD (rid_code) && (!OBJC_IS_PQ_KEYWORD (rid_code) || objc_pq_context)) { /* Return the canonical spelling for this keyword. */ token->value = ridpointers[(int) rid_code]; token->type = CPP_KEYWORD; token->keyword = rid_code; break; } } else { /* Return the canonical spelling for this keyword. */ token->value = ridpointers[(int) rid_code]; token->type = CPP_KEYWORD; token->keyword = rid_code; break; } } decl = lookup_name (token->value); if (decl) { if (TREE_CODE (decl) == TYPE_DECL) { token->id_kind = C_ID_TYPENAME; break; } } else if (c_dialect_objc ()) { tree objc_interface_decl = objc_is_class_name (token->value); /* Objective-C class names are in the same namespace as variables and typedefs, and hence are shadowed by local declarations. */ if (objc_interface_decl && (global_bindings_p () || (!objc_force_identifier && !decl))) { token->value = objc_interface_decl; token->id_kind = C_ID_CLASSNAME; break; } } token->id_kind = C_ID_ID; } break; case CPP_AT_NAME: /* This only happens in Objective-C; it must be a keyword. */ token->type = CPP_KEYWORD; token->keyword = C_RID_CODE (token->value); break; case CPP_COLON: case CPP_COMMA: case CPP_CLOSE_PAREN: case CPP_SEMICOLON: /* These tokens may affect the interpretation of any identifiers following, if doing Objective-C. */ OBJC_NEED_RAW_IDENTIFIER (0); break; case CPP_PRAGMA: /* We smuggled the cpp_token->u.pragma value in an INTEGER_CST. */ token->pragma_kind = TREE_INT_CST_LOW (token->value); token->value = NULL; break; default: break; } timevar_pop (TV_LEX); } /* Return a pointer to the next token from PARSER, reading it in if necessary. */ static inline c_token * c_parser_peek_token (c_parser *parser) { if (parser->tokens_avail == 0) { c_lex_one_token (&parser->tokens[0]); parser->tokens_avail = 1; } return &parser->tokens[0]; } /* Return true if the next token from PARSER has the indicated TYPE. */ static inline bool c_parser_next_token_is (c_parser *parser, enum cpp_ttype type) { return c_parser_peek_token (parser)->type == type; } /* Return true if the next token from PARSER does not have the indicated TYPE. */ static inline bool c_parser_next_token_is_not (c_parser *parser, enum cpp_ttype type) { return !c_parser_next_token_is (parser, type); } /* Return true if the next token from PARSER is the indicated KEYWORD. */ static inline bool c_parser_next_token_is_keyword (c_parser *parser, enum rid keyword) { c_token *token; /* Peek at the next token. */ token = c_parser_peek_token (parser); /* Check to see if it is the indicated keyword. */ return token->keyword == keyword; } /* Return true if TOKEN can start a type name, false otherwise. */ static bool c_token_starts_typename (c_token *token) { switch (token->type) { case CPP_NAME: switch (token->id_kind) { case C_ID_ID: return false; case C_ID_TYPENAME: return true; case C_ID_CLASSNAME: gcc_assert (c_dialect_objc ()); return true; default: gcc_unreachable (); } case CPP_KEYWORD: switch (token->keyword) { case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: case RID_BOOL: case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_TYPEOF: case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: case RID_ATTRIBUTE: return true; default: return false; } case CPP_LESS: if (c_dialect_objc ()) return true; return false; default: return false; } } /* Return true if the next token from PARSER can start a type name, false otherwise. */ static inline bool c_parser_next_token_starts_typename (c_parser *parser) { c_token *token = c_parser_peek_token (parser); return c_token_starts_typename (token); } /* Return true if TOKEN can start declaration specifiers, false otherwise. */ static bool c_token_starts_declspecs (c_token *token) { switch (token->type) { case CPP_NAME: switch (token->id_kind) { case C_ID_ID: return false; case C_ID_TYPENAME: return true; case C_ID_CLASSNAME: gcc_assert (c_dialect_objc ()); return true; default: gcc_unreachable (); } case CPP_KEYWORD: switch (token->keyword) { case RID_STATIC: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_INLINE: case RID_AUTO: case RID_THREAD: case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: case RID_BOOL: case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_TYPEOF: case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: case RID_ATTRIBUTE: return true; default: return false; } case CPP_LESS: if (c_dialect_objc ()) return true; return false; default: return false; } } /* Return true if the next token from PARSER can start declaration specifiers, false otherwise. */ static inline bool c_parser_next_token_starts_declspecs (c_parser *parser) { c_token *token = c_parser_peek_token (parser); return c_token_starts_declspecs (token); } /* Return a pointer to the next-but-one token from PARSER, reading it in if necessary. The next token is already read in. */ static c_token * c_parser_peek_2nd_token (c_parser *parser) { if (parser->tokens_avail >= 2) return &parser->tokens[1]; gcc_assert (parser->tokens_avail == 1); gcc_assert (parser->tokens[0].type != CPP_EOF); gcc_assert (parser->tokens[0].type != CPP_PRAGMA_EOL); c_lex_one_token (&parser->tokens[1]); parser->tokens_avail = 2; return &parser->tokens[1]; } /* Consume the next token from PARSER. */ static void c_parser_consume_token (c_parser *parser) { gcc_assert (parser->tokens_avail >= 1); gcc_assert (parser->tokens[0].type != CPP_EOF); gcc_assert (!parser->in_pragma || parser->tokens[0].type != CPP_PRAGMA_EOL); gcc_assert (parser->error || parser->tokens[0].type != CPP_PRAGMA); if (parser->tokens_avail == 2) parser->tokens[0] = parser->tokens[1]; parser->tokens_avail--; } /* Expect the current token to be a #pragma. Consume it and remember that we've begun parsing a pragma. */ static void c_parser_consume_pragma (c_parser *parser) { gcc_assert (!parser->in_pragma); gcc_assert (parser->tokens_avail >= 1); gcc_assert (parser->tokens[0].type == CPP_PRAGMA); if (parser->tokens_avail == 2) parser->tokens[0] = parser->tokens[1]; parser->tokens_avail--; parser->in_pragma = true; } /* Update the globals input_location and in_system_header from TOKEN. */ static inline void c_parser_set_source_position_from_token (c_token *token) { if (token->type != CPP_EOF) { input_location = token->location; in_system_header = token->in_system_header; } } /* Issue a diagnostic of the form FILE:LINE: MESSAGE before TOKEN where TOKEN is the next token in the input stream of PARSER. MESSAGE (specified by the caller) is usually of the form "expected OTHER-TOKEN". Do not issue a diagnostic if still recovering from an error. ??? This is taken from the C++ parser, but building up messages in this way is not i18n-friendly and some other approach should be used. */ static void c_parser_error (c_parser *parser, const char *gmsgid) { c_token *token = c_parser_peek_token (parser); if (parser->error) return; parser->error = true; if (!gmsgid) return; /* This diagnostic makes more sense if it is tagged to the line of the token we just peeked at. */ c_parser_set_source_position_from_token (token); c_parse_error (gmsgid, /* Because c_parse_error does not understand CPP_KEYWORD, keywords are treated like identifiers. */ (token->type == CPP_KEYWORD ? CPP_NAME : token->type), token->value); } /* If the next token is of the indicated TYPE, consume it. Otherwise, issue the error MSGID. If MSGID is NULL then a message has already been produced and no message will be produced this time. Returns true if found, false otherwise. */ static bool c_parser_require (c_parser *parser, enum cpp_ttype type, const char *msgid) { if (c_parser_next_token_is (parser, type)) { c_parser_consume_token (parser); return true; } else { c_parser_error (parser, msgid); return false; } } /* If the next token is the indicated keyword, consume it. Otherwise, issue the error MSGID. Returns true if found, false otherwise. */ static bool c_parser_require_keyword (c_parser *parser, enum rid keyword, const char *msgid) { if (c_parser_next_token_is_keyword (parser, keyword)) { c_parser_consume_token (parser); return true; } else { c_parser_error (parser, msgid); return false; } } /* Like c_parser_require, except that tokens will be skipped until the desired token is found. An error message is still produced if the next token is not as expected. If MSGID is NULL then a message has already been produced and no message will be produced this time. */ static void c_parser_skip_until_found (c_parser *parser, enum cpp_ttype type, const char *msgid) { unsigned nesting_depth = 0; if (c_parser_require (parser, type, msgid)) return; /* Skip tokens until the desired token is found. */ while (true) { /* Peek at the next token. */ c_token *token = c_parser_peek_token (parser); /* If we've reached the token we want, consume it and stop. */ if (token->type == type && !nesting_depth) { c_parser_consume_token (parser); break; } /* If we've run out of tokens, stop. */ if (token->type == CPP_EOF) return; if (token->type == CPP_PRAGMA_EOL && parser->in_pragma) return; if (token->type == CPP_OPEN_BRACE || token->type == CPP_OPEN_PAREN || token->type == CPP_OPEN_SQUARE) ++nesting_depth; else if (token->type == CPP_CLOSE_BRACE || token->type == CPP_CLOSE_PAREN || token->type == CPP_CLOSE_SQUARE) { if (nesting_depth-- == 0) break; } /* Consume this token. */ c_parser_consume_token (parser); } parser->error = false; } /* Skip tokens until the end of a parameter is found, but do not consume the comma, semicolon or closing delimiter. */ static void c_parser_skip_to_end_of_parameter (c_parser *parser) { unsigned nesting_depth = 0; while (true) { c_token *token = c_parser_peek_token (parser); if ((token->type == CPP_COMMA || token->type == CPP_SEMICOLON) && !nesting_depth) break; /* If we've run out of tokens, stop. */ if (token->type == CPP_EOF) return; if (token->type == CPP_PRAGMA_EOL && parser->in_pragma) return; if (token->type == CPP_OPEN_BRACE || token->type == CPP_OPEN_PAREN || token->type == CPP_OPEN_SQUARE) ++nesting_depth; else if (token->type == CPP_CLOSE_BRACE || token->type == CPP_CLOSE_PAREN || token->type == CPP_CLOSE_SQUARE) { if (nesting_depth-- == 0) break; } /* Consume this token. */ c_parser_consume_token (parser); } parser->error = false; } /* Expect to be at the end of the pragma directive and consume an end of line marker. */ static void c_parser_skip_to_pragma_eol (c_parser *parser) { gcc_assert (parser->in_pragma); parser->in_pragma = false; if (!c_parser_require (parser, CPP_PRAGMA_EOL, "expected end of line")) while (true) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_EOF) break; if (token->type == CPP_PRAGMA_EOL) { c_parser_consume_token (parser); break; } c_parser_consume_token (parser); } parser->error = false; } /* Skip tokens until we have consumed an entire block, or until we have consumed a non-nested ';'. */ static void c_parser_skip_to_end_of_block_or_statement (c_parser *parser) { unsigned nesting_depth = 0; bool save_error = parser->error; while (true) { c_token *token; /* Peek at the next token. */ token = c_parser_peek_token (parser); switch (token->type) { case CPP_EOF: return; case CPP_PRAGMA_EOL: if (parser->in_pragma) return; break; case CPP_SEMICOLON: /* If the next token is a ';', we have reached the end of the statement. */ if (!nesting_depth) { /* Consume the ';'. */ c_parser_consume_token (parser); goto finished; } break; case CPP_CLOSE_BRACE: /* If the next token is a non-nested '}', then we have reached the end of the current block. */ if (nesting_depth == 0 || --nesting_depth == 0) { c_parser_consume_token (parser); goto finished; } break; case CPP_OPEN_BRACE: /* If it the next token is a '{', then we are entering a new block. Consume the entire block. */ ++nesting_depth; break; case CPP_PRAGMA: /* If we see a pragma, consume the whole thing at once. We have some safeguards against consuming pragmas willy-nilly. Normally, we'd expect to be here with parser->error set, which disables these safeguards. But it's possible to get here for secondary error recovery, after parser->error has been cleared. */ c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); parser->error = save_error; continue; default: break; } c_parser_consume_token (parser); } finished: parser->error = false; } /* Save the warning flags which are controlled by __extension__. */ static inline int disable_extension_diagnostics (void) { int ret = (pedantic | (warn_pointer_arith << 1) | (warn_traditional << 2) | (flag_iso << 3)); pedantic = 0; warn_pointer_arith = 0; warn_traditional = 0; flag_iso = 0; return ret; } /* Restore the warning flags which are controlled by __extension__. FLAGS is the return value from disable_extension_diagnostics. */ static inline void restore_extension_diagnostics (int flags) { pedantic = flags & 1; warn_pointer_arith = (flags >> 1) & 1; warn_traditional = (flags >> 2) & 1; flag_iso = (flags >> 3) & 1; } /* Possibly kinds of declarator to parse. */ typedef enum c_dtr_syn { /* A normal declarator with an identifier. */ C_DTR_NORMAL, /* An abstract declarator (maybe empty). */ C_DTR_ABSTRACT, /* A parameter declarator: may be either, but after a type name does not redeclare a typedef name as an identifier if it can alternatively be interpreted as a typedef name; see DR#009, applied in C90 TC1, omitted from C99 and reapplied in C99 TC2 following DR#249. For example, given a typedef T, "int T" and "int *T" are valid parameter declarations redeclaring T, while "int (T)" and "int * (T)" and "int (T[])" and "int (T (int))" are abstract declarators rather than involving redundant parentheses; the same applies with attributes inside the parentheses before "T". */ C_DTR_PARM } c_dtr_syn; static void c_parser_external_declaration (c_parser *); static void c_parser_asm_definition (c_parser *); static void c_parser_declaration_or_fndef (c_parser *, bool, bool, bool, bool); static void c_parser_declspecs (c_parser *, struct c_declspecs *, bool, bool, bool); static struct c_typespec c_parser_enum_specifier (c_parser *); static struct c_typespec c_parser_struct_or_union_specifier (c_parser *); static tree c_parser_struct_declaration (c_parser *); static struct c_typespec c_parser_typeof_specifier (c_parser *); static struct c_declarator *c_parser_declarator (c_parser *, bool, c_dtr_syn, bool *); static struct c_declarator *c_parser_direct_declarator (c_parser *, bool, c_dtr_syn, bool *); static struct c_declarator *c_parser_direct_declarator_inner (c_parser *, bool, struct c_declarator *); static struct c_arg_info *c_parser_parms_declarator (c_parser *, bool, tree); static struct c_arg_info *c_parser_parms_list_declarator (c_parser *, tree); static struct c_parm *c_parser_parameter_declaration (c_parser *, tree); static tree c_parser_simple_asm_expr (c_parser *); static tree c_parser_attributes (c_parser *); static struct c_type_name *c_parser_type_name (c_parser *); static struct c_expr c_parser_initializer (c_parser *); static struct c_expr c_parser_braced_init (c_parser *, tree, bool); static void c_parser_initelt (c_parser *); static void c_parser_initval (c_parser *, struct c_expr *); static tree c_parser_compound_statement (c_parser *); static void c_parser_compound_statement_nostart (c_parser *); static void c_parser_label (c_parser *); static void c_parser_statement (c_parser *); static void c_parser_statement_after_labels (c_parser *); static void c_parser_if_statement (c_parser *); static void c_parser_switch_statement (c_parser *); static void c_parser_while_statement (c_parser *); static void c_parser_do_statement (c_parser *); static void c_parser_for_statement (c_parser *); static tree c_parser_asm_statement (c_parser *); static tree c_parser_asm_operands (c_parser *, bool); static tree c_parser_asm_clobbers (c_parser *); static struct c_expr c_parser_expr_no_commas (c_parser *, struct c_expr *); static struct c_expr c_parser_conditional_expression (c_parser *, struct c_expr *); static struct c_expr c_parser_binary_expression (c_parser *, struct c_expr *); static struct c_expr c_parser_cast_expression (c_parser *, struct c_expr *); static struct c_expr c_parser_unary_expression (c_parser *); static struct c_expr c_parser_sizeof_expression (c_parser *); static struct c_expr c_parser_alignof_expression (c_parser *); static struct c_expr c_parser_postfix_expression (c_parser *); static struct c_expr c_parser_postfix_expression_after_paren_type (c_parser *, struct c_type_name *); static struct c_expr c_parser_postfix_expression_after_primary (c_parser *, struct c_expr); static struct c_expr c_parser_expression (c_parser *); static struct c_expr c_parser_expression_conv (c_parser *); static tree c_parser_expr_list (c_parser *, bool); static void c_parser_omp_construct (c_parser *); static void c_parser_omp_threadprivate (c_parser *); static void c_parser_omp_barrier (c_parser *); static void c_parser_omp_flush (c_parser *); static void c_parser_omp_taskwait (c_parser *); enum pragma_context { pragma_external, pragma_stmt, pragma_compound }; static bool c_parser_pragma (c_parser *, enum pragma_context); /* These Objective-C parser functions are only ever called when compiling Objective-C. */ static void c_parser_objc_class_definition (c_parser *); static void c_parser_objc_class_instance_variables (c_parser *); static void c_parser_objc_class_declaration (c_parser *); static void c_parser_objc_alias_declaration (c_parser *); static void c_parser_objc_protocol_definition (c_parser *); static enum tree_code c_parser_objc_method_type (c_parser *); static void c_parser_objc_method_definition (c_parser *); static void c_parser_objc_methodprotolist (c_parser *); static void c_parser_objc_methodproto (c_parser *); static tree c_parser_objc_method_decl (c_parser *); static tree c_parser_objc_type_name (c_parser *); static tree c_parser_objc_protocol_refs (c_parser *); static void c_parser_objc_try_catch_statement (c_parser *); static void c_parser_objc_synchronized_statement (c_parser *); static tree c_parser_objc_selector (c_parser *); static tree c_parser_objc_selector_arg (c_parser *); static tree c_parser_objc_receiver (c_parser *); static tree c_parser_objc_message_args (c_parser *); static tree c_parser_objc_keywordexpr (c_parser *); /* Parse a translation unit (C90 6.7, C99 6.9). translation-unit: external-declarations external-declarations: external-declaration external-declarations external-declaration GNU extensions: translation-unit: empty */ static void c_parser_translation_unit (c_parser *parser) { if (c_parser_next_token_is (parser, CPP_EOF)) { if (pedantic) pedwarn ("ISO C forbids an empty source file"); } else { void *obstack_position = obstack_alloc (&parser_obstack, 0); do { ggc_collect (); c_parser_external_declaration (parser); obstack_free (&parser_obstack, obstack_position); } while (c_parser_next_token_is_not (parser, CPP_EOF)); } } /* Parse an external declaration (C90 6.7, C99 6.9). external-declaration: function-definition declaration GNU extensions: external-declaration: asm-definition ; __extension__ external-declaration Objective-C: external-declaration: objc-class-definition objc-class-declaration objc-alias-declaration objc-protocol-definition objc-method-definition @end */ static void c_parser_external_declaration (c_parser *parser) { int ext; switch (c_parser_peek_token (parser)->type) { case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_EXTENSION: ext = disable_extension_diagnostics (); c_parser_consume_token (parser); c_parser_external_declaration (parser); restore_extension_diagnostics (ext); break; case RID_ASM: c_parser_asm_definition (parser); break; case RID_AT_INTERFACE: case RID_AT_IMPLEMENTATION: gcc_assert (c_dialect_objc ()); c_parser_objc_class_definition (parser); break; case RID_AT_CLASS: gcc_assert (c_dialect_objc ()); c_parser_objc_class_declaration (parser); break; case RID_AT_ALIAS: gcc_assert (c_dialect_objc ()); c_parser_objc_alias_declaration (parser); break; case RID_AT_PROTOCOL: gcc_assert (c_dialect_objc ()); c_parser_objc_protocol_definition (parser); break; case RID_AT_END: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); objc_finish_implementation (); break; default: goto decl_or_fndef; } break; case CPP_SEMICOLON: if (pedantic) pedwarn ("ISO C does not allow extra %<;%> outside of a function"); c_parser_consume_token (parser); break; case CPP_PRAGMA: c_parser_pragma (parser, pragma_external); break; case CPP_PLUS: case CPP_MINUS: if (c_dialect_objc ()) { c_parser_objc_method_definition (parser); break; } /* Else fall through, and yield a syntax error trying to parse as a declaration or function definition. */ default: decl_or_fndef: /* A declaration or a function definition. We can only tell which after parsing the declaration specifiers, if any, and the first declarator. */ c_parser_declaration_or_fndef (parser, true, true, false, true); break; } } /* Parse a declaration or function definition (C90 6.5, 6.7.1, C99 6.7, 6.9.1). If FNDEF_OK is true, a function definition is accepted; otherwise (old-style parameter declarations) only other declarations are accepted. If NESTED is true, we are inside a function or parsing old-style parameter declarations; any functions encountered are nested functions and declaration specifiers are required; otherwise we are at top level and functions are normal functions and declaration specifiers may be optional. If EMPTY_OK is true, empty declarations are OK (subject to all other constraints); otherwise (old-style parameter declarations) they are diagnosed. If START_ATTR_OK is true, the declaration specifiers may start with attributes; otherwise they may not. declaration: declaration-specifiers init-declarator-list[opt] ; function-definition: declaration-specifiers[opt] declarator declaration-list[opt] compound-statement declaration-list: declaration declaration-list declaration init-declarator-list: init-declarator init-declarator-list , init-declarator init-declarator: declarator simple-asm-expr[opt] attributes[opt] declarator simple-asm-expr[opt] attributes[opt] = initializer GNU extensions: nested-function-definition: declaration-specifiers declarator declaration-list[opt] compound-statement The simple-asm-expr and attributes are GNU extensions. This function does not handle __extension__; that is handled in its callers. ??? Following the old parser, __extension__ may start external declarations, declarations in functions and declarations at the start of "for" loops, but not old-style parameter declarations. C99 requires declaration specifiers in a function definition; the absence is diagnosed through the diagnosis of implicit int. In GNU C we also allow but diagnose declarations without declaration specifiers, but only at top level (elsewhere they conflict with other syntax). OpenMP: declaration: threadprivate-directive */ static void c_parser_declaration_or_fndef (c_parser *parser, bool fndef_ok, bool empty_ok, bool nested, bool start_attr_ok) { struct c_declspecs *specs; tree prefix_attrs; tree all_prefix_attrs; bool diagnosed_no_specs = false; specs = build_null_declspecs (); c_parser_declspecs (parser, specs, true, true, start_attr_ok); if (parser->error) { c_parser_skip_to_end_of_block_or_statement (parser); return; } if (nested && !specs->declspecs_seen_p) { c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_to_end_of_block_or_statement (parser); return; } finish_declspecs (specs); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { if (empty_ok) shadow_tag (specs); else { shadow_tag_warned (specs, 1); pedwarn ("empty declaration"); } c_parser_consume_token (parser); return; } pending_xref_error (); prefix_attrs = specs->attrs; all_prefix_attrs = prefix_attrs; specs->attrs = NULL_TREE; while (true) { struct c_declarator *declarator; bool dummy = false; tree fnbody; /* Declaring either one or more declarators (in which case we should diagnose if there were no declaration specifiers) or a function definition (in which case the diagnostic for implicit int suffices). */ declarator = c_parser_declarator (parser, specs->type_seen_p, C_DTR_NORMAL, &dummy); if (declarator == NULL) { c_parser_skip_to_end_of_block_or_statement (parser); return; } if (c_parser_next_token_is (parser, CPP_EQ) || c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is_keyword (parser, RID_ASM) || c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { tree asm_name = NULL_TREE; tree postfix_attrs = NULL_TREE; if (!diagnosed_no_specs && !specs->declspecs_seen_p) { diagnosed_no_specs = true; pedwarn ("data definition has no type or storage class"); } /* Having seen a data definition, there cannot now be a function definition. */ fndef_ok = false; if (c_parser_next_token_is_keyword (parser, RID_ASM)) asm_name = c_parser_simple_asm_expr (parser); if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) postfix_attrs = c_parser_attributes (parser); if (c_parser_next_token_is (parser, CPP_EQ)) { tree d; struct c_expr init; c_parser_consume_token (parser); /* The declaration of the variable is in effect while its initializer is parsed. */ d = start_decl (declarator, specs, true, chainon (postfix_attrs, all_prefix_attrs)); if (!d) d = error_mark_node; start_init (d, asm_name, global_bindings_p ()); init = c_parser_initializer (parser); finish_init (); if (d != error_mark_node) { maybe_warn_string_init (TREE_TYPE (d), init); finish_decl (d, init.value, asm_name); } } else { tree d = start_decl (declarator, specs, false, chainon (postfix_attrs, all_prefix_attrs)); if (d) finish_decl (d, NULL_TREE, asm_name); } if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) all_prefix_attrs = chainon (c_parser_attributes (parser), prefix_attrs); else all_prefix_attrs = prefix_attrs; continue; } else if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); return; } else { c_parser_error (parser, "expected %<,%> or %<;%>"); c_parser_skip_to_end_of_block_or_statement (parser); return; } } else if (!fndef_ok) { c_parser_error (parser, "expected %<=%>, %<,%>, %<;%>, " "%<asm%> or %<__attribute__%>"); c_parser_skip_to_end_of_block_or_statement (parser); return; } /* Function definition (nested or otherwise). */ if (nested) { if (pedantic) pedwarn ("ISO C forbids nested functions"); push_function_context (); } if (!start_function (specs, declarator, all_prefix_attrs)) { /* This can appear in many cases looking nothing like a function definition, so we don't give a more specific error suggesting there was one. */ c_parser_error (parser, "expected %<=%>, %<,%>, %<;%>, %<asm%> " "or %<__attribute__%>"); if (nested) pop_function_context (); break; } /* Parse old-style parameter declarations. ??? Attributes are not allowed to start declaration specifiers here because of a syntax conflict between a function declaration with attribute suffix and a function definition with an attribute prefix on first old-style parameter declaration. Following the old parser, they are not accepted on subsequent old-style parameter declarations either. However, there is no ambiguity after the first declaration, nor indeed on the first as long as we don't allow postfix attributes after a declarator with a nonempty identifier list in a definition; and postfix attributes have never been accepted here in function definitions either. */ while (c_parser_next_token_is_not (parser, CPP_EOF) && c_parser_next_token_is_not (parser, CPP_OPEN_BRACE)) c_parser_declaration_or_fndef (parser, false, false, true, false); DECL_SOURCE_LOCATION (current_function_decl) = c_parser_peek_token (parser)->location; store_parm_decls (); fnbody = c_parser_compound_statement (parser); if (nested) { tree decl = current_function_decl; add_stmt (fnbody); finish_function (); pop_function_context (); add_stmt (build_stmt (DECL_EXPR, decl)); } else { add_stmt (fnbody); finish_function (); } break; } } /* Parse an asm-definition (asm() outside a function body). This is a GNU extension. asm-definition: simple-asm-expr ; */ #ifdef KEY extern void gspin_gxx_emits_asm (tree t); extern int flag_spin_file; #endif static void c_parser_asm_definition (c_parser *parser) { tree asm_str = c_parser_simple_asm_expr (parser); if (asm_str) { cgraph_add_asm_node (asm_str); #ifdef KEY if (flag_spin_file) gspin_gxx_emits_asm (asm_str); #endif } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse some declaration specifiers (possibly none) (C90 6.5, C99 6.7), adding them to SPECS (which may already include some). Storage class specifiers are accepted iff SCSPEC_OK; type specifiers are accepted iff TYPESPEC_OK; attributes are accepted at the start iff START_ATTR_OK. declaration-specifiers: storage-class-specifier declaration-specifiers[opt] type-specifier declaration-specifiers[opt] type-qualifier declaration-specifiers[opt] function-specifier declaration-specifiers[opt] Function specifiers (inline) are from C99, and are currently handled as storage class specifiers, as is __thread. C90 6.5.1, C99 6.7.1: storage-class-specifier: typedef extern static auto register C99 6.7.4: function-specifier: inline C90 6.5.2, C99 6.7.2: type-specifier: void char short int long float double signed unsigned _Bool _Complex [_Imaginary removed in C99 TC2] struct-or-union-specifier enum-specifier typedef-name (_Bool and _Complex are new in C99.) C90 6.5.3, C99 6.7.3: type-qualifier: const restrict volatile (restrict is new in C99.) GNU extensions: declaration-specifiers: attributes declaration-specifiers[opt] storage-class-specifier: __thread type-specifier: typeof-specifier _Decimal32 _Decimal64 _Decimal128 Objective-C: type-specifier: class-name objc-protocol-refs[opt] typedef-name objc-protocol-refs objc-protocol-refs */ static void c_parser_declspecs (c_parser *parser, struct c_declspecs *specs, bool scspec_ok, bool typespec_ok, bool start_attr_ok) { bool attrs_ok = start_attr_ok; bool seen_type = specs->type_seen_p; while (c_parser_next_token_is (parser, CPP_NAME) || c_parser_next_token_is (parser, CPP_KEYWORD) || (c_dialect_objc () && c_parser_next_token_is (parser, CPP_LESS))) { struct c_typespec t; tree attrs; if (c_parser_next_token_is (parser, CPP_NAME)) { tree value = c_parser_peek_token (parser)->value; c_id_kind kind = c_parser_peek_token (parser)->id_kind; /* This finishes the specifiers unless a type name is OK, it is declared as a type name and a type name hasn't yet been seen. */ if (!typespec_ok || seen_type || (kind != C_ID_TYPENAME && kind != C_ID_CLASSNAME)) break; c_parser_consume_token (parser); seen_type = true; attrs_ok = true; if (kind == C_ID_TYPENAME && (!c_dialect_objc () || c_parser_next_token_is_not (parser, CPP_LESS))) { t.kind = ctsk_typedef; /* For a typedef name, record the meaning, not the name. In case of 'foo foo, bar;'. */ t.spec = lookup_name (value); } else { tree proto = NULL_TREE; gcc_assert (c_dialect_objc ()); t.kind = ctsk_objc; if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); t.spec = objc_get_protocol_qualified_type (value, proto); } declspecs_add_type (specs, t); continue; } if (c_parser_next_token_is (parser, CPP_LESS)) { /* Make "<SomeProtocol>" equivalent to "id <SomeProtocol>" - nisse@lysator.liu.se. */ tree proto; gcc_assert (c_dialect_objc ()); if (!typespec_ok || seen_type) break; proto = c_parser_objc_protocol_refs (parser); t.kind = ctsk_objc; t.spec = objc_get_protocol_qualified_type (NULL_TREE, proto); declspecs_add_type (specs, t); continue; } gcc_assert (c_parser_next_token_is (parser, CPP_KEYWORD)); switch (c_parser_peek_token (parser)->keyword) { case RID_STATIC: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_INLINE: case RID_AUTO: case RID_THREAD: if (!scspec_ok) goto out; attrs_ok = true; /* TODO: Distinguish between function specifiers (inline) and storage class specifiers, either here or in declspecs_add_scspec. */ declspecs_add_scspec (specs, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); break; case RID_UNSIGNED: case RID_LONG: case RID_SHORT: case RID_SIGNED: case RID_COMPLEX: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: case RID_BOOL: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; OBJC_NEED_RAW_IDENTIFIER (1); t.kind = ctsk_resword; t.spec = c_parser_peek_token (parser)->value; declspecs_add_type (specs, t); c_parser_consume_token (parser); break; case RID_ENUM: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; t = c_parser_enum_specifier (parser); declspecs_add_type (specs, t); break; case RID_STRUCT: case RID_UNION: if (!typespec_ok) goto out; attrs_ok = true; seen_type = true; t = c_parser_struct_or_union_specifier (parser); declspecs_add_type (specs, t); break; case RID_TYPEOF: /* ??? The old parser rejected typeof after other type specifiers, but is a syntax error the best way of handling this? */ if (!typespec_ok || seen_type) goto out; attrs_ok = true; seen_type = true; t = c_parser_typeof_specifier (parser); declspecs_add_type (specs, t); break; case RID_CONST: case RID_VOLATILE: case RID_RESTRICT: attrs_ok = true; declspecs_add_qual (specs, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); break; case RID_ATTRIBUTE: if (!attrs_ok) goto out; attrs = c_parser_attributes (parser); declspecs_add_attrs (specs, attrs); break; default: goto out; } } out: ; } /* Parse an enum specifier (C90 6.5.2.2, C99 6.7.2.2). enum-specifier: enum attributes[opt] identifier[opt] { enumerator-list } attributes[opt] enum attributes[opt] identifier[opt] { enumerator-list , } attributes[opt] enum attributes[opt] identifier The form with trailing comma is new in C99. The forms with attributes are GNU extensions. In GNU C, we accept any expression without commas in the syntax (assignment expressions, not just conditional expressions); assignment expressions will be diagnosed as non-constant. enumerator-list: enumerator enumerator-list , enumerator enumerator: enumeration-constant enumeration-constant = constant-expression */ static struct c_typespec c_parser_enum_specifier (c_parser *parser) { struct c_typespec ret; tree attrs; tree ident = NULL_TREE; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ENUM)); c_parser_consume_token (parser); attrs = c_parser_attributes (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { ident = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { /* Parse an enum definition. */ tree type = start_enum (ident); tree postfix_attrs; /* We chain the enumerators in reverse order, then put them in forward order at the end. */ tree values = NULL_TREE; c_parser_consume_token (parser); while (true) { tree enum_id; tree enum_value; tree enum_decl; bool seen_comma; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); values = error_mark_node; break; } enum_id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_EQ)) { c_parser_consume_token (parser); enum_value = c_parser_expr_no_commas (parser, NULL).value; } else enum_value = NULL_TREE; enum_decl = build_enumerator (enum_id, enum_value); TREE_CHAIN (enum_decl) = values; values = enum_decl; seen_comma = false; if (c_parser_next_token_is (parser, CPP_COMMA)) { seen_comma = true; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { if (seen_comma && pedantic && !flag_isoc99) pedwarn ("comma at end of enumerator list"); c_parser_consume_token (parser); break; } if (!seen_comma) { c_parser_error (parser, "expected %<,%> or %<}%>"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); values = error_mark_node; break; } } postfix_attrs = c_parser_attributes (parser); ret.spec = finish_enum (type, nreverse (values), chainon (attrs, postfix_attrs)); ret.kind = ctsk_tagdef; return ret; } else if (!ident) { c_parser_error (parser, "expected %<{%>"); ret.spec = error_mark_node; ret.kind = ctsk_tagref; return ret; } ret = parser_xref_tag (ENUMERAL_TYPE, ident); /* In ISO C, enumerated types can be referred to only if already defined. */ if (pedantic && !COMPLETE_TYPE_P (ret.spec)) pedwarn ("ISO C forbids forward references to %<enum%> types"); return ret; } /* Parse a struct or union specifier (C90 6.5.2.1, C99 6.7.2.1). struct-or-union-specifier: struct-or-union attributes[opt] identifier[opt] { struct-contents } attributes[opt] struct-or-union attributes[opt] identifier struct-contents: struct-declaration-list struct-declaration-list: struct-declaration ; struct-declaration-list struct-declaration ; GNU extensions: struct-contents: empty struct-declaration struct-declaration-list struct-declaration struct-declaration-list: struct-declaration-list ; ; (Note that in the syntax here, unlike that in ISO C, the semicolons are included here rather than in struct-declaration, in order to describe the syntax with extra semicolons and missing semicolon at end.) Objective-C: struct-declaration-list: @defs ( class-name ) (Note this does not include a trailing semicolon, but can be followed by further declarations, and gets a pedwarn-if-pedantic when followed by a semicolon.) */ static struct c_typespec c_parser_struct_or_union_specifier (c_parser *parser) { struct c_typespec ret; tree attrs; tree ident = NULL_TREE; enum tree_code code; switch (c_parser_peek_token (parser)->keyword) { case RID_STRUCT: code = RECORD_TYPE; break; case RID_UNION: code = UNION_TYPE; break; default: gcc_unreachable (); } c_parser_consume_token (parser); attrs = c_parser_attributes (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { ident = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { /* Parse a struct or union definition. Start the scope of the tag before parsing components. */ tree type = start_struct (code, ident); tree postfix_attrs; /* We chain the components in reverse order, then put them in forward order at the end. Each struct-declaration may declare multiple components (comma-separated), so we must use chainon to join them, although when parsing each struct-declaration we can use TREE_CHAIN directly. The theory behind all this is that there will be more semicolon separated fields than comma separated fields, and so we'll be minimizing the number of node traversals required by chainon. */ tree contents = NULL_TREE; c_parser_consume_token (parser); /* Handle the Objective-C @defs construct, e.g. foo(sizeof(struct{ @defs(ClassName) }));. */ if (c_parser_next_token_is_keyword (parser, RID_AT_DEFS)) { tree name; gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) goto end_at_defs; if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else { c_parser_error (parser, "expected class name"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); goto end_at_defs; } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); contents = nreverse (objc_get_class_ivars (name)); } end_at_defs: /* Parse the struct-declarations and semicolons. Problems with semicolons are diagnosed here; empty structures are diagnosed elsewhere. */ while (true) { tree decls; /* Parse any stray semicolon. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { if (pedantic) pedwarn ("extra semicolon in struct or union specified"); c_parser_consume_token (parser); continue; } /* Stop if at the end of the struct or union contents. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); break; } /* Accept #pragmas at struct scope. */ if (c_parser_next_token_is (parser, CPP_PRAGMA)) { c_parser_pragma (parser, pragma_external); continue; } /* Parse some comma-separated declarations, but not the trailing semicolon if any. */ decls = c_parser_struct_declaration (parser); contents = chainon (decls, contents); /* If no semicolon follows, either we have a parse error or are at the end of the struct or union and should pedwarn. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) pedwarn ("no semicolon at end of struct or union"); else { c_parser_error (parser, "expected %<;%>"); c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); break; } } } postfix_attrs = c_parser_attributes (parser); ret.spec = finish_struct (type, nreverse (contents), chainon (attrs, postfix_attrs)); ret.kind = ctsk_tagdef; return ret; } else if (!ident) { c_parser_error (parser, "expected %<{%>"); ret.spec = error_mark_node; ret.kind = ctsk_tagref; return ret; } ret = parser_xref_tag (code, ident); return ret; } /* Parse a struct-declaration (C90 6.5.2.1, C99 6.7.2.1), *without* the trailing semicolon. struct-declaration: specifier-qualifier-list struct-declarator-list specifier-qualifier-list: type-specifier specifier-qualifier-list[opt] type-qualifier specifier-qualifier-list[opt] attributes specifier-qualifier-list[opt] struct-declarator-list: struct-declarator struct-declarator-list , attributes[opt] struct-declarator struct-declarator: declarator attributes[opt] declarator[opt] : constant-expression attributes[opt] GNU extensions: struct-declaration: __extension__ struct-declaration specifier-qualifier-list Unlike the ISO C syntax, semicolons are handled elsewhere. The use of attributes where shown is a GNU extension. In GNU C, we accept any expression without commas in the syntax (assignment expressions, not just conditional expressions); assignment expressions will be diagnosed as non-constant. */ static tree c_parser_struct_declaration (c_parser *parser) { struct c_declspecs *specs; tree prefix_attrs; tree all_prefix_attrs; tree decls; if (c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { int ext; tree decl; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); decl = c_parser_struct_declaration (parser); restore_extension_diagnostics (ext); return decl; } specs = build_null_declspecs (); c_parser_declspecs (parser, specs, false, true, true); if (parser->error) return NULL_TREE; if (!specs->declspecs_seen_p) { c_parser_error (parser, "expected specifier-qualifier-list"); return NULL_TREE; } finish_declspecs (specs); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { tree ret; if (!specs->type_seen_p) { if (pedantic) pedwarn ("ISO C forbids member declarations with no members"); shadow_tag_warned (specs, pedantic); ret = NULL_TREE; } else { /* Support for unnamed structs or unions as members of structs or unions (which is [a] useful and [b] supports MS P-SDK). */ ret = grokfield (build_id_declarator (NULL_TREE), specs, NULL_TREE); } return ret; } pending_xref_error (); prefix_attrs = specs->attrs; all_prefix_attrs = prefix_attrs; specs->attrs = NULL_TREE; decls = NULL_TREE; while (true) { /* Declaring one or more declarators or un-named bit-fields. */ struct c_declarator *declarator; bool dummy = false; if (c_parser_next_token_is (parser, CPP_COLON)) declarator = build_id_declarator (NULL_TREE); else declarator = c_parser_declarator (parser, specs->type_seen_p, C_DTR_NORMAL, &dummy); if (declarator == NULL) { c_parser_skip_to_end_of_block_or_statement (parser); break; } if (c_parser_next_token_is (parser, CPP_COLON) || c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_CLOSE_BRACE) || c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { tree postfix_attrs = NULL_TREE; tree width = NULL_TREE; tree d; if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); width = c_parser_expr_no_commas (parser, NULL).value; } if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) postfix_attrs = c_parser_attributes (parser); d = grokfield (declarator, specs, width); decl_attributes (&d, chainon (postfix_attrs, all_prefix_attrs), 0); TREE_CHAIN (d) = decls; decls = d; if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) all_prefix_attrs = chainon (c_parser_attributes (parser), prefix_attrs); else all_prefix_attrs = prefix_attrs; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else if (c_parser_next_token_is (parser, CPP_SEMICOLON) || c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { /* Semicolon consumed in caller. */ break; } else { c_parser_error (parser, "expected %<,%>, %<;%> or %<}%>"); break; } } else { c_parser_error (parser, "expected %<:%>, %<,%>, %<;%>, %<}%> or " "%<__attribute__%>"); break; } } return decls; } /* Parse a typeof specifier (a GNU extension). typeof-specifier: typeof ( expression ) typeof ( type-name ) */ static struct c_typespec c_parser_typeof_specifier (c_parser *parser) { struct c_typespec ret; ret.kind = ctsk_typeof; ret.spec = error_mark_node; gcc_assert (c_parser_next_token_is_keyword (parser, RID_TYPEOF)); c_parser_consume_token (parser); skip_evaluation++; in_typeof++; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { skip_evaluation--; in_typeof--; return ret; } if (c_parser_next_token_starts_typename (parser)) { struct c_type_name *type = c_parser_type_name (parser); skip_evaluation--; in_typeof--; if (type != NULL) { ret.spec = groktypename (type); pop_maybe_used (variably_modified_type_p (ret.spec, NULL_TREE)); } } else { bool was_vm; struct c_expr expr = c_parser_expression (parser); skip_evaluation--; in_typeof--; if (TREE_CODE (expr.value) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr.value, 1))) error ("%<typeof%> applied to a bit-field"); ret.spec = TREE_TYPE (expr.value); was_vm = variably_modified_type_p (ret.spec, NULL_TREE); /* This should be returned with the type so that when the type is evaluated, this can be evaluated. For now, we avoid evaluation when the context might. */ if (!skip_evaluation && was_vm) { tree e = expr.value; /* If the expression is not of a type to which we cannot assign a line number, wrap the thing in a no-op NOP_EXPR. */ if (DECL_P (e) || CONSTANT_CLASS_P (e)) e = build1 (NOP_EXPR, void_type_node, e); if (EXPR_P (e)) SET_EXPR_LOCATION (e, input_location); add_stmt (e); } pop_maybe_used (was_vm); } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return ret; } /* Parse a declarator, possibly an abstract declarator (C90 6.5.4, 6.5.5, C99 6.7.5, 6.7.6). If TYPE_SEEN_P then a typedef name may be redeclared; otherwise it may not. KIND indicates which kind of declarator is wanted. Returns a valid declarator except in the case of a syntax error in which case NULL is returned. *SEEN_ID is set to true if an identifier being declared is seen; this is used to diagnose bad forms of abstract array declarators and to determine whether an identifier list is syntactically permitted. declarator: pointer[opt] direct-declarator direct-declarator: identifier ( attributes[opt] declarator ) direct-declarator array-declarator direct-declarator ( parameter-type-list ) direct-declarator ( identifier-list[opt] ) pointer: * type-qualifier-list[opt] * type-qualifier-list[opt] pointer type-qualifier-list: type-qualifier attributes type-qualifier-list type-qualifier type-qualifier-list attributes parameter-type-list: parameter-list parameter-list , ... parameter-list: parameter-declaration parameter-list , parameter-declaration parameter-declaration: declaration-specifiers declarator attributes[opt] declaration-specifiers abstract-declarator[opt] attributes[opt] identifier-list: identifier identifier-list , identifier abstract-declarator: pointer pointer[opt] direct-abstract-declarator direct-abstract-declarator: ( attributes[opt] abstract-declarator ) direct-abstract-declarator[opt] array-declarator direct-abstract-declarator[opt] ( parameter-type-list[opt] ) GNU extensions: direct-declarator: direct-declarator ( parameter-forward-declarations parameter-type-list[opt] ) direct-abstract-declarator: direct-abstract-declarator[opt] ( parameter-forward-declarations parameter-type-list[opt] ) parameter-forward-declarations: parameter-list ; parameter-forward-declarations parameter-list ; The uses of attributes shown above are GNU extensions. Some forms of array declarator are not included in C99 in the syntax for abstract declarators; these are disallowed elsewhere. This may be a defect (DR#289). This function also accepts an omitted abstract declarator as being an abstract declarator, although not part of the formal syntax. */ static struct c_declarator * c_parser_declarator (c_parser *parser, bool type_seen_p, c_dtr_syn kind, bool *seen_id) { /* Parse any initial pointer part. */ if (c_parser_next_token_is (parser, CPP_MULT)) { struct c_declspecs *quals_attrs = build_null_declspecs (); struct c_declarator *inner; c_parser_consume_token (parser); c_parser_declspecs (parser, quals_attrs, false, false, true); inner = c_parser_declarator (parser, type_seen_p, kind, seen_id); if (inner == NULL) return NULL; else return make_pointer_declarator (quals_attrs, inner); } /* Now we have a direct declarator, direct abstract declarator or nothing (which counts as a direct abstract declarator here). */ return c_parser_direct_declarator (parser, type_seen_p, kind, seen_id); } /* Parse a direct declarator or direct abstract declarator; arguments as c_parser_declarator. */ static struct c_declarator * c_parser_direct_declarator (c_parser *parser, bool type_seen_p, c_dtr_syn kind, bool *seen_id) { /* The direct declarator must start with an identifier (possibly omitted) or a parenthesized declarator (possibly abstract). In an ordinary declarator, initial parentheses must start a parenthesized declarator. In an abstract declarator or parameter declarator, they could start a parenthesized declarator or a parameter list. To tell which, the open parenthesis and any following attributes must be read. If a declaration specifier follows, then it is a parameter list; if the specifier is a typedef name, there might be an ambiguity about redeclaring it, which is resolved in the direction of treating it as a typedef name. If a close parenthesis follows, it is also an empty parameter list, as the syntax does not permit empty abstract declarators. Otherwise, it is a parenthesized declarator (in which case the analysis may be repeated inside it, recursively). ??? There is an ambiguity in a parameter declaration "int (__attribute__((foo)) x)", where x is not a typedef name: it could be an abstract declarator for a function, or declare x with parentheses. The proper resolution of this ambiguity needs documenting. At present we follow an accident of the old parser's implementation, whereby the first parameter must have some declaration specifiers other than just attributes. Thus as a parameter declaration it is treated as a parenthesized parameter named x, and as an abstract declarator it is rejected. ??? Also following the old parser, attributes inside an empty parameter list are ignored, making it a list not yielding a prototype, rather than giving an error or making it have one parameter with implicit type int. ??? Also following the old parser, typedef names may be redeclared in declarators, but not Objective-C class names. */ if (kind != C_DTR_ABSTRACT && c_parser_next_token_is (parser, CPP_NAME) && ((type_seen_p && c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME) || c_parser_peek_token (parser)->id_kind == C_ID_ID)) { struct c_declarator *inner = build_id_declarator (c_parser_peek_token (parser)->value); *seen_id = true; inner->id_loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); return c_parser_direct_declarator_inner (parser, *seen_id, inner); } if (kind != C_DTR_NORMAL && c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { struct c_declarator *inner = build_id_declarator (NULL_TREE); return c_parser_direct_declarator_inner (parser, *seen_id, inner); } /* Either we are at the end of an abstract declarator, or we have parentheses. */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree attrs; struct c_declarator *inner; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); if (kind != C_DTR_NORMAL && (c_parser_next_token_starts_declspecs (parser) || c_parser_next_token_is (parser, CPP_CLOSE_PAREN))) { struct c_arg_info *args = c_parser_parms_declarator (parser, kind == C_DTR_NORMAL, attrs); if (args == NULL) return NULL; else { inner = build_function_declarator (args, build_id_declarator (NULL_TREE)); return c_parser_direct_declarator_inner (parser, *seen_id, inner); } } /* A parenthesized declarator. */ inner = c_parser_declarator (parser, type_seen_p, kind, seen_id); if (inner != NULL && attrs != NULL) inner = build_attrs_declarator (attrs, inner); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (inner == NULL) return NULL; else return c_parser_direct_declarator_inner (parser, *seen_id, inner); } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } else { if (kind == C_DTR_NORMAL) { c_parser_error (parser, "expected identifier or %<(%>"); return NULL; } else return build_id_declarator (NULL_TREE); } } /* Parse part of a direct declarator or direct abstract declarator, given that some (in INNER) has already been parsed; ID_PRESENT is true if an identifier is present, false for an abstract declarator. */ static struct c_declarator * c_parser_direct_declarator_inner (c_parser *parser, bool id_present, struct c_declarator *inner) { /* Parse a sequence of array declarators and parameter lists. */ if (c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { struct c_declarator *declarator; struct c_declspecs *quals_attrs = build_null_declspecs (); bool static_seen; bool star_seen; tree dimen; c_parser_consume_token (parser); c_parser_declspecs (parser, quals_attrs, false, false, true); static_seen = c_parser_next_token_is_keyword (parser, RID_STATIC); if (static_seen) c_parser_consume_token (parser); if (static_seen && !quals_attrs->declspecs_seen_p) c_parser_declspecs (parser, quals_attrs, false, false, true); if (!quals_attrs->declspecs_seen_p) quals_attrs = NULL; /* If "static" is present, there must be an array dimension. Otherwise, there may be a dimension, "*", or no dimension. */ if (static_seen) { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL).value; } else { if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) { dimen = NULL_TREE; star_seen = false; } else if (c_parser_next_token_is (parser, CPP_MULT)) { if (c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_SQUARE) { dimen = NULL_TREE; star_seen = true; c_parser_consume_token (parser); } else { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL).value; } } else { star_seen = false; dimen = c_parser_expr_no_commas (parser, NULL).value; } } if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) c_parser_consume_token (parser); else { c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); return NULL; } declarator = build_array_declarator (dimen, quals_attrs, static_seen, star_seen); if (declarator == NULL) return NULL; inner = set_array_declarator_inner (declarator, inner, !id_present); return c_parser_direct_declarator_inner (parser, id_present, inner); } else if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree attrs; struct c_arg_info *args; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); args = c_parser_parms_declarator (parser, id_present, attrs); if (args == NULL) return NULL; else { inner = build_function_declarator (args, inner); return c_parser_direct_declarator_inner (parser, id_present, inner); } } return inner; } /* Parse a parameter list or identifier list, including the closing parenthesis but not the opening one. ATTRS are the attributes at the start of the list. ID_LIST_OK is true if an identifier list is acceptable; such a list must not have attributes at the start. */ static struct c_arg_info * c_parser_parms_declarator (c_parser *parser, bool id_list_ok, tree attrs) { push_scope (); declare_parm_level (); /* If the list starts with an identifier, it is an identifier list. Otherwise, it is either a prototype list or an empty list. */ if (id_list_ok && !attrs && c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { tree list = NULL_TREE, *nextp = &list; while (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { *nextp = build_tree_list (NULL_TREE, c_parser_peek_token (parser)->value); nextp = & TREE_CHAIN (*nextp); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_COMMA)) break; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_error (parser, "expected identifier"); break; } } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { struct c_arg_info *ret = XOBNEW (&parser_obstack, struct c_arg_info); ret->parms = 0; ret->tags = 0; ret->types = list; ret->others = 0; ret->pending_sizes = 0; ret->had_vla_unspec = 0; c_parser_consume_token (parser); pop_scope (); return ret; } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); pop_scope (); return NULL; } } else { struct c_arg_info *ret = c_parser_parms_list_declarator (parser, attrs); pop_scope (); return ret; } } /* Parse a parameter list (possibly empty), including the closing parenthesis but not the opening one. ATTRS are the attributes at the start of the list. */ static struct c_arg_info * c_parser_parms_list_declarator (c_parser *parser, tree attrs) { bool good_parm = false; /* ??? Following the old parser, forward parameter declarations may use abstract declarators, and if no real parameter declarations follow the forward declarations then this is not diagnosed. Also note as above that attributes are ignored as the only contents of the parentheses, or as the only contents after forward declarations. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { struct c_arg_info *ret = XOBNEW (&parser_obstack, struct c_arg_info); ret->parms = 0; ret->tags = 0; ret->types = 0; ret->others = 0; ret->pending_sizes = 0; ret->had_vla_unspec = 0; c_parser_consume_token (parser); return ret; } if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { struct c_arg_info *ret = XOBNEW (&parser_obstack, struct c_arg_info); ret->parms = 0; ret->tags = 0; ret->others = 0; ret->pending_sizes = 0; ret->had_vla_unspec = 0; /* Suppress -Wold-style-definition for this case. */ ret->types = error_mark_node; error ("ISO C requires a named argument before %<...%>"); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); return ret; } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } /* Nonempty list of parameters, either terminated with semicolon (forward declarations; recurse) or with close parenthesis (normal function) or with ", ... )" (variadic function). */ while (true) { /* Parse a parameter. */ struct c_parm *parm = c_parser_parameter_declaration (parser, attrs); attrs = NULL_TREE; if (parm != NULL) { good_parm = true; push_parm_decl (parm); } if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { tree new_attrs; c_parser_consume_token (parser); mark_forward_parm_decls (); new_attrs = c_parser_attributes (parser); return c_parser_parms_list_declarator (parser, new_attrs); } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (good_parm) return get_parm_info (false); else { struct c_arg_info *ret = XOBNEW (&parser_obstack, struct c_arg_info); ret->parms = 0; ret->tags = 0; ret->types = 0; ret->others = 0; ret->pending_sizes = 0; ret->had_vla_unspec = 0; return ret; } } if (!c_parser_require (parser, CPP_COMMA, "expected %<;%>, %<,%> or %<)%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL; } if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { c_parser_consume_token (parser); if (good_parm) return get_parm_info (true); else { struct c_arg_info *ret = XOBNEW (&parser_obstack, struct c_arg_info); ret->parms = 0; ret->tags = 0; ret->types = 0; ret->others = 0; ret->pending_sizes = 0; ret->had_vla_unspec = 0; return ret; } } else { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return NULL; } } } } /* Parse a parameter declaration. ATTRS are the attributes at the start of the declaration if it is the first parameter. */ static struct c_parm * c_parser_parameter_declaration (c_parser *parser, tree attrs) { struct c_declspecs *specs; struct c_declarator *declarator; tree prefix_attrs; tree postfix_attrs = NULL_TREE; bool dummy = false; if (!c_parser_next_token_starts_declspecs (parser)) { /* ??? In some Objective-C cases '...' isn't applicable so there should be a different message. */ c_parser_error (parser, "expected declaration specifiers or %<...%>"); c_parser_skip_to_end_of_parameter (parser); return NULL; } specs = build_null_declspecs (); if (attrs) { declspecs_add_attrs (specs, attrs); attrs = NULL_TREE; } c_parser_declspecs (parser, specs, true, true, true); finish_declspecs (specs); pending_xref_error (); prefix_attrs = specs->attrs; specs->attrs = NULL_TREE; declarator = c_parser_declarator (parser, specs->type_seen_p, C_DTR_PARM, &dummy); if (declarator == NULL) { c_parser_skip_until_found (parser, CPP_COMMA, NULL); return NULL; } if (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) postfix_attrs = c_parser_attributes (parser); return build_c_parm (specs, chainon (postfix_attrs, prefix_attrs), declarator); } /* Parse a string literal in an asm expression. It should not be translated, and wide string literals are an error although permitted by the syntax. This is a GNU extension. asm-string-literal: string-literal ??? At present, following the old parser, the caller needs to have set c_lex_string_translate to 0. It would be better to follow the C++ parser rather than using the c_lex_string_translate kludge. */ static tree c_parser_asm_string_literal (c_parser *parser) { tree str; if (c_parser_next_token_is (parser, CPP_STRING)) { str = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else if (c_parser_next_token_is (parser, CPP_WSTRING)) { error ("wide string literal in %<asm%>"); str = build_string (1, ""); c_parser_consume_token (parser); } else { c_parser_error (parser, "expected string literal"); str = NULL_TREE; } return str; } /* Parse a simple asm expression. This is used in restricted contexts, where a full expression with inputs and outputs does not make sense. This is a GNU extension. simple-asm-expr: asm ( asm-string-literal ) */ static tree c_parser_simple_asm_expr (c_parser *parser) { tree str; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ASM)); /* ??? Follow the C++ parser rather than using the c_lex_string_translate kludge. */ c_lex_string_translate = 0; c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { c_lex_string_translate = 1; return NULL_TREE; } str = c_parser_asm_string_literal (parser); c_lex_string_translate = 1; if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } return str; } /* Parse (possibly empty) attributes. This is a GNU extension. attributes: empty attributes attribute attribute: __attribute__ ( ( attribute-list ) ) attribute-list: attrib attribute_list , attrib attrib: empty any-word any-word ( identifier ) any-word ( identifier , nonempty-expr-list ) any-word ( expr-list ) where the "identifier" must not be declared as a type, and "any-word" may be any identifier (including one declared as a type), a reserved word storage class specifier, type specifier or type qualifier. ??? This still leaves out most reserved keywords (following the old parser), shouldn't we include them, and why not allow identifiers declared as types to start the arguments? */ static tree c_parser_attributes (c_parser *parser) { tree attrs = NULL_TREE; while (c_parser_next_token_is_keyword (parser, RID_ATTRIBUTE)) { /* ??? Follow the C++ parser rather than using the c_lex_string_translate kludge. */ c_lex_string_translate = 0; c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { c_lex_string_translate = 1; return attrs; } if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return attrs; } /* Parse the attribute list. */ while (c_parser_next_token_is (parser, CPP_COMMA) || c_parser_next_token_is (parser, CPP_NAME) || c_parser_next_token_is (parser, CPP_KEYWORD)) { tree attr, attr_name, attr_args; if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); continue; } if (c_parser_next_token_is (parser, CPP_KEYWORD)) { /* ??? See comment above about what keywords are accepted here. */ bool ok; switch (c_parser_peek_token (parser)->keyword) { case RID_STATIC: case RID_UNSIGNED: case RID_LONG: case RID_CONST: case RID_EXTERN: case RID_REGISTER: case RID_TYPEDEF: case RID_SHORT: case RID_INLINE: case RID_VOLATILE: case RID_SIGNED: case RID_AUTO: case RID_RESTRICT: case RID_COMPLEX: case RID_THREAD: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_DFLOAT32: case RID_DFLOAT64: case RID_DFLOAT128: case RID_BOOL: ok = true; break; default: ok = false; break; } if (!ok) break; } attr_name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_OPEN_PAREN)) { attr = build_tree_list (attr_name, NULL_TREE); attrs = chainon (attrs, attr); continue; } c_parser_consume_token (parser); /* Parse the attribute contents. If they start with an identifier which is followed by a comma or close parenthesis, then the arguments start with that identifier; otherwise they are an expression list. */ if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID && ((c_parser_peek_2nd_token (parser)->type == CPP_COMMA) || (c_parser_peek_2nd_token (parser)->type == CPP_CLOSE_PAREN))) { tree arg1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) attr_args = build_tree_list (NULL_TREE, arg1); else { c_parser_consume_token (parser); attr_args = tree_cons (NULL_TREE, arg1, c_parser_expr_list (parser, false)); } } else { if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) attr_args = NULL_TREE; else attr_args = c_parser_expr_list (parser, false); } attr = build_tree_list (attr_name, attr_args); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } attrs = chainon (attrs, attr); } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) c_parser_consume_token (parser); else { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return attrs; } c_lex_string_translate = 1; } return attrs; } /* Parse a type name (C90 6.5.5, C99 6.7.6). type-name: specifier-qualifier-list abstract-declarator[opt] */ static struct c_type_name * c_parser_type_name (c_parser *parser) { struct c_declspecs *specs = build_null_declspecs (); struct c_declarator *declarator; struct c_type_name *ret; bool dummy = false; c_parser_declspecs (parser, specs, false, true, true); if (!specs->declspecs_seen_p) { c_parser_error (parser, "expected specifier-qualifier-list"); return NULL; } pending_xref_error (); finish_declspecs (specs); declarator = c_parser_declarator (parser, specs->type_seen_p, C_DTR_ABSTRACT, &dummy); if (declarator == NULL) return NULL; ret = XOBNEW (&parser_obstack, struct c_type_name); ret->specs = specs; ret->declarator = declarator; return ret; } /* Parse an initializer (C90 6.5.7, C99 6.7.8). initializer: assignment-expression { initializer-list } { initializer-list , } initializer-list: designation[opt] initializer initializer-list , designation[opt] initializer designation: designator-list = designator-list: designator designator-list designator designator: array-designator . identifier array-designator: [ constant-expression ] GNU extensions: initializer: { } designation: array-designator identifier : array-designator: [ constant-expression ... constant-expression ] Any expression without commas is accepted in the syntax for the constant-expressions, with non-constant expressions rejected later. This function is only used for top-level initializers; for nested ones, see c_parser_initval. */ static struct c_expr c_parser_initializer (c_parser *parser) { if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) return c_parser_braced_init (parser, NULL_TREE, false); else { struct c_expr ret; ret = c_parser_expr_no_commas (parser, NULL); if (TREE_CODE (ret.value) != STRING_CST && TREE_CODE (ret.value) != COMPOUND_LITERAL_EXPR) ret = default_function_array_conversion (ret); return ret; } } /* Parse a braced initializer list. TYPE is the type specified for a compound literal, and NULL_TREE for other initializers and for nested braced lists. NESTED_P is true for nested braced lists, false for the list of a compound literal or the list that is the top-level initializer in a declaration. */ static struct c_expr c_parser_braced_init (c_parser *parser, tree type, bool nested_p) { gcc_assert (c_parser_next_token_is (parser, CPP_OPEN_BRACE)); c_parser_consume_token (parser); if (nested_p) push_init_level (0); else really_start_incremental_init (type); if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { if (pedantic) pedwarn ("ISO C forbids empty initializer braces"); } else { /* Parse a non-empty initializer list, possibly with a trailing comma. */ while (true) { c_parser_initelt (parser); if (parser->error) break; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) break; } } if (c_parser_next_token_is_not (parser, CPP_CLOSE_BRACE)) { struct c_expr ret; ret.value = error_mark_node; ret.original_code = ERROR_MARK; c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, "expected %<}%>"); return ret; } c_parser_consume_token (parser); return pop_init_level (0); } /* Parse a nested initializer, including designators. */ static void c_parser_initelt (c_parser *parser) { /* Parse any designator or designator list. A single array designator may have the subsequent "=" omitted in GNU C, but a longer list or a structure member designator may not. */ if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON) { /* Old-style structure member designator. */ set_init_label (c_parser_peek_token (parser)->value); if (pedantic) pedwarn ("obsolete use of designated initializer with %<:%>"); c_parser_consume_token (parser); c_parser_consume_token (parser); } else { /* des_seen is 0 if there have been no designators, 1 if there has been a single array designator and 2 otherwise. */ int des_seen = 0; while (c_parser_next_token_is (parser, CPP_OPEN_SQUARE) || c_parser_next_token_is (parser, CPP_DOT)) { int des_prev = des_seen; if (des_seen < 2) des_seen++; if (c_parser_next_token_is (parser, CPP_DOT)) { des_seen = 2; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { set_init_label (c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } else { struct c_expr init; init.value = error_mark_node; init.original_code = ERROR_MARK; c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_COMMA, NULL); process_init_element (init); return; } } else { tree first, second; /* ??? Following the old parser, [ objc-receiver objc-message-args ] is accepted as an initializer, being distinguished from a designator by what follows the first assignment expression inside the square brackets, but after a first array designator a subsequent square bracket is for Objective-C taken to start an expression, using the obsolete form of designated initializer without '=', rather than possibly being a second level of designation: in LALR terms, the '[' is shifted rather than reducing designator to designator-list. */ if (des_prev == 1 && c_dialect_objc ()) { des_seen = des_prev; break; } if (des_prev == 0 && c_dialect_objc ()) { /* This might be an array designator or an Objective-C message expression. If the former, continue parsing here; if the latter, parse the remainder of the initializer given the starting primary-expression. ??? It might make sense to distinguish when des_prev == 1 as well; see previous comment. */ tree rec, args; struct c_expr mexpr; c_parser_consume_token (parser); if (c_parser_peek_token (parser)->type == CPP_NAME && ((c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME) || (c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME))) { /* Type name receiver. */ tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); rec = objc_get_class_reference (id); goto parse_message_args; } first = c_parser_expr_no_commas (parser, NULL).value; if (c_parser_next_token_is (parser, CPP_ELLIPSIS) || c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) goto array_desig_after_first; /* Expression receiver. So far only one part without commas has been parsed; there might be more of the expression. */ rec = first; while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_expr next; c_parser_consume_token (parser); next = c_parser_expr_no_commas (parser, NULL); next = default_function_array_conversion (next); rec = build_compound_expr (rec, next.value); } parse_message_args: /* Now parse the objc-message-args. */ args = c_parser_objc_message_args (parser); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); mexpr.value = objc_build_message_expr (build_tree_list (rec, args)); mexpr.original_code = ERROR_MARK; /* Now parse and process the remainder of the initializer, starting with this message expression as a primary-expression. */ c_parser_initval (parser, &mexpr); return; } c_parser_consume_token (parser); first = c_parser_expr_no_commas (parser, NULL).value; array_desig_after_first: if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { c_parser_consume_token (parser); second = c_parser_expr_no_commas (parser, NULL).value; } else second = NULL_TREE; if (c_parser_next_token_is (parser, CPP_CLOSE_SQUARE)) { c_parser_consume_token (parser); set_init_index (first, second); if (pedantic && second) pedwarn ("ISO C forbids specifying range of " "elements to initialize"); } else c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); } } if (des_seen >= 1) { if (c_parser_next_token_is (parser, CPP_EQ)) { if (pedantic && !flag_isoc99) pedwarn ("ISO C90 forbids specifying subobject to initialize"); c_parser_consume_token (parser); } else { if (des_seen == 1) { if (pedantic) pedwarn ("obsolete use of designated initializer " "without %<=%>"); } else { struct c_expr init; init.value = error_mark_node; init.original_code = ERROR_MARK; c_parser_error (parser, "expected %<=%>"); c_parser_skip_until_found (parser, CPP_COMMA, NULL); process_init_element (init); return; } } } } c_parser_initval (parser, NULL); } /* Parse a nested initializer; as c_parser_initializer but parses initializers within braced lists, after any designators have been applied. If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the initializer. */ static void c_parser_initval (c_parser *parser, struct c_expr *after) { struct c_expr init; gcc_assert (!after || c_dialect_objc ()); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE) && !after) init = c_parser_braced_init (parser, NULL_TREE, true); else { init = c_parser_expr_no_commas (parser, after); if (init.value != NULL_TREE && TREE_CODE (init.value) != STRING_CST && TREE_CODE (init.value) != COMPOUND_LITERAL_EXPR) init = default_function_array_conversion (init); } process_init_element (init); } /* Parse a compound statement (possibly a function body) (C90 6.6.2, C99 6.8.2). compound-statement: { block-item-list[opt] } { label-declarations block-item-list } block-item-list: block-item block-item-list block-item block-item: nested-declaration statement nested-declaration: declaration GNU extensions: compound-statement: { label-declarations block-item-list } nested-declaration: __extension__ nested-declaration nested-function-definition label-declarations: label-declaration label-declarations label-declaration label-declaration: __label__ identifier-list ; Allowing the mixing of declarations and code is new in C99. The GNU syntax also permits (not shown above) labels at the end of compound statements, which yield an error. We don't allow labels on declarations; this might seem like a natural extension, but there would be a conflict between attributes on the label and prefix attributes on the declaration. ??? The syntax follows the old parser in requiring something after label declarations. Although they are erroneous if the labels declared aren't defined, is it useful for the syntax to be this way? OpenMP: block-item: openmp-directive openmp-directive: barrier-directive flush-directive */ static tree c_parser_compound_statement (c_parser *parser) { tree stmt; if (!c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) return error_mark_node; stmt = c_begin_compound_stmt (true); c_parser_compound_statement_nostart (parser); return c_end_compound_stmt (stmt, true); } /* Parse a compound statement except for the opening brace. This is used for parsing both compound statements and statement expressions (which follow different paths to handling the opening). */ static void c_parser_compound_statement_nostart (c_parser *parser) { bool last_stmt = false; bool last_label = false; if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); return; } if (c_parser_next_token_is_keyword (parser, RID_LABEL)) { /* Read zero or more forward-declarations for labels that nested functions can jump to. */ while (c_parser_next_token_is_keyword (parser, RID_LABEL)) { c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree label; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } label = declare_label (c_parser_peek_token (parser)->value); C_DECLARED_LABEL_FLAG (label) = 1; add_stmt (build_stmt (DECL_EXPR, label)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* ??? Locating this diagnostic on the token after the declarations end follows the old parser, but it might be better to locate it where the declarations start instead. */ if (pedantic) pedwarn ("ISO C forbids label declarations"); } /* We must now have at least one statement, label or declaration. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_error (parser, "expected declaration or statement"); c_parser_consume_token (parser); return; } while (c_parser_next_token_is_not (parser, CPP_CLOSE_BRACE)) { location_t loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is_keyword (parser, RID_CASE) || c_parser_next_token_is_keyword (parser, RID_DEFAULT) || (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON)) { last_label = true; last_stmt = false; c_parser_label (parser); } else if (!last_label && c_parser_next_token_starts_declspecs (parser)) { last_label = false; c_parser_declaration_or_fndef (parser, true, true, true, true); if (last_stmt && ((pedantic && !flag_isoc99) || warn_declaration_after_statement)) pedwarn_c90 ("%HISO C90 forbids mixed declarations and code", &loc); last_stmt = false; } else if (!last_label && c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { /* __extension__ can start a declaration, but is also an unary operator that can start an expression. Consume all but the last of a possible series of __extension__ to determine which. */ while (c_parser_peek_2nd_token (parser)->type == CPP_KEYWORD && (c_parser_peek_2nd_token (parser)->keyword == RID_EXTENSION)) c_parser_consume_token (parser); if (c_token_starts_declspecs (c_parser_peek_2nd_token (parser))) { int ext; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); last_label = false; c_parser_declaration_or_fndef (parser, true, true, true, true); /* Following the old parser, __extension__ does not disable this diagnostic. */ restore_extension_diagnostics (ext); if (last_stmt && ((pedantic && !flag_isoc99) || warn_declaration_after_statement)) pedwarn_c90 ("%HISO C90 forbids mixed declarations and code", &loc); last_stmt = false; } else goto statement; } else if (c_parser_next_token_is (parser, CPP_PRAGMA)) { /* External pragmas, and some omp pragmas, are not associated with regular c code, and so are not to be considered statements syntactically. This ensures that the user doesn't put them places that would turn into syntax errors if the directive were ignored. */ if (c_parser_pragma (parser, pragma_compound)) last_label = false, last_stmt = true; } else if (c_parser_next_token_is (parser, CPP_EOF)) { c_parser_error (parser, "expected declaration or statement"); return; } else { statement: last_label = false; last_stmt = true; c_parser_statement_after_labels (parser); } parser->error = false; } if (last_label) error ("label at end of compound statement"); c_parser_consume_token (parser); } /* Parse a label (C90 6.6.1, C99 6.8.1). label: identifier : attributes[opt] case constant-expression : default : GNU extensions: label: case constant-expression ... constant-expression : The use of attributes on labels is a GNU extension. The syntax in GNU C accepts any expressions without commas, non-constant expressions being rejected later. */ static void c_parser_label (c_parser *parser) { location_t loc1 = c_parser_peek_token (parser)->location; tree label = NULL_TREE; if (c_parser_next_token_is_keyword (parser, RID_CASE)) { tree exp1, exp2; c_parser_consume_token (parser); exp1 = c_parser_expr_no_commas (parser, NULL).value; if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); label = do_case (exp1, NULL_TREE); } else if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { c_parser_consume_token (parser); exp2 = c_parser_expr_no_commas (parser, NULL).value; if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) label = do_case (exp1, exp2); } else c_parser_error (parser, "expected %<:%> or %<...%>"); } else if (c_parser_next_token_is_keyword (parser, RID_DEFAULT)) { c_parser_consume_token (parser); if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) label = do_case (NULL_TREE, NULL_TREE); } else { tree name = c_parser_peek_token (parser)->value; tree tlab; location_t loc2; tree attrs; gcc_assert (c_parser_next_token_is (parser, CPP_NAME)); c_parser_consume_token (parser); gcc_assert (c_parser_next_token_is (parser, CPP_COLON)); loc2 = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); attrs = c_parser_attributes (parser); tlab = define_label (loc2, name); if (tlab) { decl_attributes (&tlab, attrs, 0); label = add_stmt (build_stmt (LABEL_EXPR, tlab)); } } if (label) SET_EXPR_LOCATION (label, loc1); } /* Parse a statement (C90 6.6, C99 6.8). statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement labeled-statement: label statement expression-statement: expression[opt] ; selection-statement: if-statement switch-statement iteration-statement: while-statement do-statement for-statement jump-statement: goto identifier ; continue ; break ; return expression[opt] ; GNU extensions: statement: asm-statement jump-statement: goto * expression ; Objective-C: statement: objc-throw-statement objc-try-catch-statement objc-synchronized-statement objc-throw-statement: @throw expression ; @throw ; OpenMP: statement: openmp-construct openmp-construct: parallel-construct for-construct sections-construct single-construct parallel-for-construct parallel-sections-construct master-construct critical-construct atomic-construct ordered-construct parallel-construct: parallel-directive structured-block for-construct: for-directive iteration-statement sections-construct: sections-directive section-scope single-construct: single-directive structured-block parallel-for-construct: parallel-for-directive iteration-statement parallel-sections-construct: parallel-sections-directive section-scope master-construct: master-directive structured-block critical-construct: critical-directive structured-block atomic-construct: atomic-directive expression-statement ordered-construct: ordered-directive structured-block */ static void c_parser_statement (c_parser *parser) { while (c_parser_next_token_is_keyword (parser, RID_CASE) || c_parser_next_token_is_keyword (parser, RID_DEFAULT) || (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON)) c_parser_label (parser); c_parser_statement_after_labels (parser); } /* Parse a statement, other than a labeled statement. */ static void c_parser_statement_after_labels (c_parser *parser) { location_t loc = c_parser_peek_token (parser)->location; tree stmt = NULL_TREE; switch (c_parser_peek_token (parser)->type) { case CPP_OPEN_BRACE: add_stmt (c_parser_compound_statement (parser)); break; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_IF: c_parser_if_statement (parser); break; case RID_SWITCH: c_parser_switch_statement (parser); break; case RID_WHILE: c_parser_while_statement (parser); break; case RID_DO: c_parser_do_statement (parser); break; case RID_FOR: c_parser_for_statement (parser); break; case RID_GOTO: c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { stmt = c_finish_goto_label (c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } else if (c_parser_next_token_is (parser, CPP_MULT)) { c_parser_consume_token (parser); stmt = c_finish_goto_ptr (c_parser_expression (parser).value); } else c_parser_error (parser, "expected identifier or %<*%>"); goto expect_semicolon; case RID_CONTINUE: c_parser_consume_token (parser); stmt = c_finish_bc_stmt (&c_cont_label, false); goto expect_semicolon; case RID_BREAK: c_parser_consume_token (parser); stmt = c_finish_bc_stmt (&c_break_label, true); goto expect_semicolon; case RID_RETURN: c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { stmt = c_finish_return (NULL_TREE); c_parser_consume_token (parser); } else { stmt = c_finish_return (c_parser_expression_conv (parser).value); goto expect_semicolon; } break; case RID_ASM: stmt = c_parser_asm_statement (parser); break; case RID_AT_THROW: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { stmt = objc_build_throw_stmt (NULL_TREE); c_parser_consume_token (parser); } else { stmt = objc_build_throw_stmt (c_parser_expression (parser).value); goto expect_semicolon; } break; case RID_AT_TRY: gcc_assert (c_dialect_objc ()); c_parser_objc_try_catch_statement (parser); break; case RID_AT_SYNCHRONIZED: gcc_assert (c_dialect_objc ()); c_parser_objc_synchronized_statement (parser); break; default: goto expr_stmt; } break; case CPP_SEMICOLON: c_parser_consume_token (parser); break; case CPP_CLOSE_PAREN: case CPP_CLOSE_SQUARE: /* Avoid infinite loop in error recovery: c_parser_skip_until_found stops at a closing nesting delimiter without consuming it, but here we need to consume it to proceed further. */ c_parser_error (parser, "expected statement"); c_parser_consume_token (parser); break; case CPP_PRAGMA: c_parser_pragma (parser, pragma_stmt); break; default: expr_stmt: stmt = c_finish_expr_stmt (c_parser_expression_conv (parser).value); expect_semicolon: c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); break; } /* Two cases cannot and do not have line numbers associated: If stmt is degenerate, such as "2;", then stmt is an INTEGER_CST, which cannot hold line numbers. But that's OK because the statement will either be changed to a MODIFY_EXPR during gimplification of the statement expr, or discarded. If stmt was compound, but without new variables, we will have skipped the creation of a BIND and will have a bare STATEMENT_LIST. But that's OK because (recursively) all of the component statements should already have line numbers assigned. ??? Can we discard no-op statements earlier? */ if (stmt && EXPR_P (stmt)) SET_EXPR_LOCATION (stmt, loc); } /* Parse a parenthesized condition from an if, do or while statement. condition: ( expression ) */ static tree c_parser_paren_condition (c_parser *parser) { location_t loc; tree cond; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) return error_mark_node; loc = c_parser_peek_token (parser)->location; cond = c_objc_common_truthvalue_conversion (c_parser_expression_conv (parser).value); if (EXPR_P (cond)) SET_EXPR_LOCATION (cond, loc); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); return cond; } /* Parse a statement which is a block in C99. */ static tree c_parser_c99_block_statement (c_parser *parser) { tree block = c_begin_compound_stmt (flag_isoc99); c_parser_statement (parser); return c_end_compound_stmt (block, flag_isoc99); } /* Parse the body of an if statement or the else half thereof. This is just parsing a statement but (a) it is a block in C99, (b) we track whether the body is an if statement for the sake of -Wparentheses warnings, (c) we handle an empty body specially for the sake of -Wextra warnings. */ static tree c_parser_if_body (c_parser *parser, bool *if_p) { tree block = c_begin_compound_stmt (flag_isoc99); while (c_parser_next_token_is_keyword (parser, RID_CASE) || c_parser_next_token_is_keyword (parser, RID_DEFAULT) || (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_COLON)) c_parser_label (parser); *if_p = c_parser_next_token_is_keyword (parser, RID_IF); if (extra_warnings && c_parser_next_token_is (parser, CPP_SEMICOLON)) add_stmt (build_empty_stmt ()); c_parser_statement_after_labels (parser); return c_end_compound_stmt (block, flag_isoc99); } /* Parse an if statement (C90 6.6.4, C99 6.8.4). if-statement: if ( expression ) statement if ( expression ) statement else statement */ static void c_parser_if_statement (c_parser *parser) { tree block; location_t loc; tree cond; bool first_if = false, second_if = false; tree first_body, second_body; gcc_assert (c_parser_next_token_is_keyword (parser, RID_IF)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; cond = c_parser_paren_condition (parser); first_body = c_parser_if_body (parser, &first_if); if (c_parser_next_token_is_keyword (parser, RID_ELSE)) { c_parser_consume_token (parser); second_body = c_parser_if_body (parser, &second_if); } else second_body = NULL_TREE; c_finish_if_stmt (loc, cond, first_body, second_body, first_if); add_stmt (c_end_compound_stmt (block, flag_isoc99)); } /* Parse a switch statement (C90 6.6.4, C99 6.8.4). switch-statement: switch (expression) statement */ static void c_parser_switch_statement (c_parser *parser) { tree block, expr, body, save_break; gcc_assert (c_parser_next_token_is_keyword (parser, RID_SWITCH)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else expr = error_mark_node; c_start_case (expr); save_break = c_break_label; c_break_label = NULL_TREE; body = c_parser_c99_block_statement (parser); c_finish_case (body); if (c_break_label) add_stmt (build1 (LABEL_EXPR, void_type_node, c_break_label)); c_break_label = save_break; add_stmt (c_end_compound_stmt (block, flag_isoc99)); } /* Parse a while statement (C90 6.6.5, C99 6.8.5). while-statement: while (expression) statement */ static void c_parser_while_statement (c_parser *parser) { tree block, cond, body, save_break, save_cont; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_WHILE)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; cond = c_parser_paren_condition (parser); save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = c_parser_c99_block_statement (parser); c_finish_loop (loc, cond, NULL, body, c_break_label, c_cont_label, true); add_stmt (c_end_compound_stmt (block, flag_isoc99)); c_break_label = save_break; c_cont_label = save_cont; } /* Parse a do statement (C90 6.6.5, C99 6.8.5). do-statement: do statement while ( expression ) ; */ static void c_parser_do_statement (c_parser *parser) { tree block, cond, body, save_break, save_cont, new_break, new_cont; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_DO)); c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); loc = c_parser_peek_token (parser)->location; save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = c_parser_c99_block_statement (parser); c_parser_require_keyword (parser, RID_WHILE, "expected %<while%>"); new_break = c_break_label; c_break_label = save_break; new_cont = c_cont_label; c_cont_label = save_cont; cond = c_parser_paren_condition (parser); if (!c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) c_parser_skip_to_end_of_block_or_statement (parser); c_finish_loop (loc, cond, NULL, body, new_break, new_cont, false); add_stmt (c_end_compound_stmt (block, flag_isoc99)); } /* Parse a for statement (C90 6.6.5, C99 6.8.5). for-statement: for ( expression[opt] ; expression[opt] ; expression[opt] ) statement for ( nested-declaration expression[opt] ; expression[opt] ) statement The form with a declaration is new in C99. ??? In accordance with the old parser, the declaration may be a nested function, which is then rejected in check_for_loop_decls, but does it make any sense for this to be included in the grammar? Note in particular that the nested function does not include a trailing ';', whereas the "declaration" production includes one. Also, can we reject bad declarations earlier and cheaper than check_for_loop_decls? */ static void c_parser_for_statement (c_parser *parser) { tree block, cond, incr, save_break, save_cont, body; location_t loc; gcc_assert (c_parser_next_token_is_keyword (parser, RID_FOR)); loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); block = c_begin_compound_stmt (flag_isoc99); if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { /* Parse the initialization declaration or expression. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); c_finish_expr_stmt (NULL_TREE); } else if (c_parser_next_token_starts_declspecs (parser)) { c_parser_declaration_or_fndef (parser, true, true, true, true); check_for_loop_decls (); } else if (c_parser_next_token_is_keyword (parser, RID_EXTENSION)) { /* __extension__ can start a declaration, but is also an unary operator that can start an expression. Consume all but the last of a possible series of __extension__ to determine which. */ while (c_parser_peek_2nd_token (parser)->type == CPP_KEYWORD && (c_parser_peek_2nd_token (parser)->keyword == RID_EXTENSION)) c_parser_consume_token (parser); if (c_token_starts_declspecs (c_parser_peek_2nd_token (parser))) { int ext; ext = disable_extension_diagnostics (); c_parser_consume_token (parser); c_parser_declaration_or_fndef (parser, true, true, true, true); restore_extension_diagnostics (ext); check_for_loop_decls (); } else goto init_expr; } else { init_expr: c_finish_expr_stmt (c_parser_expression (parser).value); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse the loop condition. */ loc = c_parser_peek_token (parser)->location; if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); cond = NULL_TREE; } else { tree ocond = c_parser_expression_conv (parser).value; cond = c_objc_common_truthvalue_conversion (ocond); if (EXPR_P (cond)) SET_EXPR_LOCATION (cond, loc); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse the increment expression. */ if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) incr = c_process_expr_stmt (NULL_TREE); else incr = c_process_expr_stmt (c_parser_expression (parser).value); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else { cond = error_mark_node; incr = error_mark_node; } save_break = c_break_label; c_break_label = NULL_TREE; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = c_parser_c99_block_statement (parser); c_finish_loop (loc, cond, incr, body, c_break_label, c_cont_label, true); add_stmt (c_end_compound_stmt (block, flag_isoc99)); c_break_label = save_break; c_cont_label = save_cont; } /* Parse an asm statement, a GNU extension. This is a full-blown asm statement with inputs, outputs, clobbers, and volatile tag allowed. asm-statement: asm type-qualifier[opt] ( asm-argument ) ; asm-argument: asm-string-literal asm-string-literal : asm-operands[opt] asm-string-literal : asm-operands[opt] : asm-operands[opt] asm-string-literal : asm-operands[opt] : asm-operands[opt] : asm-clobbers Qualifiers other than volatile are accepted in the syntax but warned for. */ static tree c_parser_asm_statement (c_parser *parser) { tree quals, str, outputs, inputs, clobbers, ret; bool simple; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ASM)); c_parser_consume_token (parser); if (c_parser_next_token_is_keyword (parser, RID_VOLATILE)) { quals = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else if (c_parser_next_token_is_keyword (parser, RID_CONST) || c_parser_next_token_is_keyword (parser, RID_RESTRICT)) { warning (0, "%E qualifier ignored on asm", c_parser_peek_token (parser)->value); quals = NULL_TREE; c_parser_consume_token (parser); } else quals = NULL_TREE; /* ??? Follow the C++ parser rather than using the c_lex_string_translate kludge. */ c_lex_string_translate = 0; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { c_lex_string_translate = 1; return NULL_TREE; } str = c_parser_asm_string_literal (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { simple = true; outputs = NULL_TREE; inputs = NULL_TREE; clobbers = NULL_TREE; goto done_asm; } if (!c_parser_require (parser, CPP_COLON, "expected %<:%> or %<)%>")) { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } simple = false; /* Parse outputs. */ if (c_parser_next_token_is (parser, CPP_COLON) || c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) outputs = NULL_TREE; else outputs = c_parser_asm_operands (parser, false); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { inputs = NULL_TREE; clobbers = NULL_TREE; goto done_asm; } if (!c_parser_require (parser, CPP_COLON, "expected %<:%> or %<)%>")) { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } /* Parse inputs. */ if (c_parser_next_token_is (parser, CPP_COLON) || c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) inputs = NULL_TREE; else inputs = c_parser_asm_operands (parser, true); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) { clobbers = NULL_TREE; goto done_asm; } if (!c_parser_require (parser, CPP_COLON, "expected %<:%> or %<)%>")) { c_lex_string_translate = 1; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } /* Parse clobbers. */ clobbers = c_parser_asm_clobbers (parser); done_asm: c_lex_string_translate = 1; if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } if (!c_parser_require (parser, CPP_SEMICOLON, "expected %<;%>")) c_parser_skip_to_end_of_block_or_statement (parser); ret = build_asm_stmt (quals, build_asm_expr (str, outputs, inputs, clobbers, simple)); return ret; } /* Parse asm operands, a GNU extension. If CONVERT_P (for inputs but not outputs), apply the default conversion of functions and arrays to pointers. asm-operands: asm-operand asm-operands , asm-operand asm-operand: asm-string-literal ( expression ) [ identifier ] asm-string-literal ( expression ) */ static tree c_parser_asm_operands (c_parser *parser, bool convert_p) { tree list = NULL_TREE; while (true) { tree name, str; struct c_expr expr; if (c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); name = build_string (IDENTIFIER_LENGTH (id), IDENTIFIER_POINTER (id)); } else { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, NULL); return NULL_TREE; } c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); } else name = NULL_TREE; str = c_parser_asm_string_literal (parser); if (str == NULL_TREE) return NULL_TREE; c_lex_string_translate = 1; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { c_lex_string_translate = 0; return NULL_TREE; } expr = c_parser_expression (parser); if (convert_p) expr = default_function_array_conversion (expr); c_lex_string_translate = 0; if (!c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return NULL_TREE; } list = chainon (list, build_tree_list (build_tree_list (name, str), expr.value)); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } return list; } /* Parse asm clobbers, a GNU extension. asm-clobbers: asm-string-literal asm-clobbers , asm-string-literal */ static tree c_parser_asm_clobbers (c_parser *parser) { tree list = NULL_TREE; while (true) { tree str = c_parser_asm_string_literal (parser); if (str) list = tree_cons (NULL_TREE, str, list); else return NULL_TREE; if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } return list; } /* Parse an expression other than a compound expression; that is, an assignment expression (C90 6.3.16, C99 6.5.16). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. assignment-expression: conditional-expression unary-expression assignment-operator assignment-expression assignment-operator: one of = *= /= %= += -= <<= >>= &= ^= |= In GNU C we accept any conditional expression on the LHS and diagnose the invalid lvalue rather than producing a syntax error. */ static struct c_expr c_parser_expr_no_commas (c_parser *parser, struct c_expr *after) { struct c_expr lhs, rhs, ret; enum tree_code code; gcc_assert (!after || c_dialect_objc ()); lhs = c_parser_conditional_expression (parser, after); switch (c_parser_peek_token (parser)->type) { case CPP_EQ: code = NOP_EXPR; break; case CPP_MULT_EQ: code = MULT_EXPR; break; case CPP_DIV_EQ: code = TRUNC_DIV_EXPR; break; case CPP_MOD_EQ: code = TRUNC_MOD_EXPR; break; case CPP_PLUS_EQ: code = PLUS_EXPR; break; case CPP_MINUS_EQ: code = MINUS_EXPR; break; case CPP_LSHIFT_EQ: code = LSHIFT_EXPR; break; case CPP_RSHIFT_EQ: code = RSHIFT_EXPR; break; case CPP_AND_EQ: code = BIT_AND_EXPR; break; case CPP_XOR_EQ: code = BIT_XOR_EXPR; break; case CPP_OR_EQ: code = BIT_IOR_EXPR; break; default: return lhs; } c_parser_consume_token (parser); rhs = c_parser_expr_no_commas (parser, NULL); rhs = default_function_array_conversion (rhs); ret.value = build_modify_expr (lhs.value, code, rhs.value); if (code == NOP_EXPR) ret.original_code = MODIFY_EXPR; else { TREE_NO_WARNING (ret.value) = 1; ret.original_code = ERROR_MARK; } return ret; } /* Parse a conditional expression (C90 6.3.15, C99 6.5.15). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. conditional-expression: logical-OR-expression logical-OR-expression ? expression : conditional-expression GNU extensions: conditional-expression: logical-OR-expression ? : conditional-expression */ static struct c_expr c_parser_conditional_expression (c_parser *parser, struct c_expr *after) { struct c_expr cond, exp1, exp2, ret; gcc_assert (!after || c_dialect_objc ()); cond = c_parser_binary_expression (parser, after); if (c_parser_next_token_is_not (parser, CPP_QUERY)) return cond; cond = default_function_array_conversion (cond); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COLON)) { if (pedantic) pedwarn ("ISO C forbids omitting the middle term of a ?: expression"); /* Make sure first operand is calculated only once. */ exp1.value = save_expr (default_conversion (cond.value)); cond.value = c_objc_common_truthvalue_conversion (exp1.value); skip_evaluation += cond.value == truthvalue_true_node; } else { cond.value = c_objc_common_truthvalue_conversion (default_conversion (cond.value)); skip_evaluation += cond.value == truthvalue_false_node; exp1 = c_parser_expression_conv (parser); skip_evaluation += ((cond.value == truthvalue_true_node) - (cond.value == truthvalue_false_node)); } if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) { skip_evaluation -= cond.value == truthvalue_true_node; ret.value = error_mark_node; ret.original_code = ERROR_MARK; return ret; } exp2 = c_parser_conditional_expression (parser, NULL); exp2 = default_function_array_conversion (exp2); skip_evaluation -= cond.value == truthvalue_true_node; ret.value = build_conditional_expr (cond.value, exp1.value, exp2.value); ret.original_code = ERROR_MARK; return ret; } /* Parse a binary expression; that is, a logical-OR-expression (C90 6.3.5-6.3.14, C99 6.5.5-6.5.14). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. multiplicative-expression: cast-expression multiplicative-expression * cast-expression multiplicative-expression / cast-expression multiplicative-expression % cast-expression additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression shift-expression: additive-expression shift-expression << additive-expression shift-expression >> additive-expression relational-expression: shift-expression relational-expression < shift-expression relational-expression > shift-expression relational-expression <= shift-expression relational-expression >= shift-expression equality-expression: relational-expression equality-expression == relational-expression equality-expression != relational-expression AND-expression: equality-expression AND-expression & equality-expression exclusive-OR-expression: AND-expression exclusive-OR-expression ^ AND-expression inclusive-OR-expression: exclusive-OR-expression inclusive-OR-expression | exclusive-OR-expression logical-AND-expression: inclusive-OR-expression logical-AND-expression && inclusive-OR-expression logical-OR-expression: logical-AND-expression logical-OR-expression || logical-AND-expression */ static struct c_expr c_parser_binary_expression (c_parser *parser, struct c_expr *after) { /* A binary expression is parsed using operator-precedence parsing, with the operands being cast expressions. All the binary operators are left-associative. Thus a binary expression is of form: E0 op1 E1 op2 E2 ... which we represent on a stack. On the stack, the precedence levels are strictly increasing. When a new operator is encountered of higher precedence than that at the top of the stack, it is pushed; its LHS is the top expression, and its RHS is everything parsed until it is popped. When a new operator is encountered with precedence less than or equal to that at the top of the stack, triples E[i-1] op[i] E[i] are popped and replaced by the result of the operation until the operator at the top of the stack has lower precedence than the new operator or there is only one element on the stack; then the top expression is the LHS of the new operator. In the case of logical AND and OR expressions, we also need to adjust skip_evaluation as appropriate when the operators are pushed and popped. */ /* The precedence levels, where 0 is a dummy lowest level used for the bottom of the stack. */ enum prec { PREC_NONE, PREC_LOGOR, PREC_LOGAND, PREC_BITOR, PREC_BITXOR, PREC_BITAND, PREC_EQ, PREC_REL, PREC_SHIFT, PREC_ADD, PREC_MULT, NUM_PRECS }; struct { /* The expression at this stack level. */ struct c_expr expr; /* The precedence of the operator on its left, PREC_NONE at the bottom of the stack. */ enum prec prec; /* The operation on its left. */ enum tree_code op; } stack[NUM_PRECS]; int sp; #define POP \ do { \ switch (stack[sp].op) \ { \ case TRUTH_ANDIF_EXPR: \ skip_evaluation -= stack[sp - 1].expr.value == truthvalue_false_node; \ break; \ case TRUTH_ORIF_EXPR: \ skip_evaluation -= stack[sp - 1].expr.value == truthvalue_true_node; \ break; \ default: \ break; \ } \ stack[sp - 1].expr \ = default_function_array_conversion (stack[sp - 1].expr); \ stack[sp].expr \ = default_function_array_conversion (stack[sp].expr); \ stack[sp - 1].expr = parser_build_binary_op (stack[sp].op, \ stack[sp - 1].expr, \ stack[sp].expr); \ sp--; \ } while (0) gcc_assert (!after || c_dialect_objc ()); stack[0].expr = c_parser_cast_expression (parser, after); stack[0].prec = PREC_NONE; sp = 0; while (true) { enum prec oprec; enum tree_code ocode; if (parser->error) goto out; switch (c_parser_peek_token (parser)->type) { case CPP_MULT: oprec = PREC_MULT; ocode = MULT_EXPR; break; case CPP_DIV: oprec = PREC_MULT; ocode = TRUNC_DIV_EXPR; break; case CPP_MOD: oprec = PREC_MULT; ocode = TRUNC_MOD_EXPR; break; case CPP_PLUS: oprec = PREC_ADD; ocode = PLUS_EXPR; break; case CPP_MINUS: oprec = PREC_ADD; ocode = MINUS_EXPR; break; case CPP_LSHIFT: oprec = PREC_SHIFT; ocode = LSHIFT_EXPR; break; case CPP_RSHIFT: oprec = PREC_SHIFT; ocode = RSHIFT_EXPR; break; case CPP_LESS: oprec = PREC_REL; ocode = LT_EXPR; break; case CPP_GREATER: oprec = PREC_REL; ocode = GT_EXPR; break; case CPP_LESS_EQ: oprec = PREC_REL; ocode = LE_EXPR; break; case CPP_GREATER_EQ: oprec = PREC_REL; ocode = GE_EXPR; break; case CPP_EQ_EQ: oprec = PREC_EQ; ocode = EQ_EXPR; break; case CPP_NOT_EQ: oprec = PREC_EQ; ocode = NE_EXPR; break; case CPP_AND: oprec = PREC_BITAND; ocode = BIT_AND_EXPR; break; case CPP_XOR: oprec = PREC_BITXOR; ocode = BIT_XOR_EXPR; break; case CPP_OR: oprec = PREC_BITOR; ocode = BIT_IOR_EXPR; break; case CPP_AND_AND: oprec = PREC_LOGAND; ocode = TRUTH_ANDIF_EXPR; break; case CPP_OR_OR: oprec = PREC_LOGOR; ocode = TRUTH_ORIF_EXPR; break; default: /* Not a binary operator, so end of the binary expression. */ goto out; } c_parser_consume_token (parser); while (oprec <= stack[sp].prec) POP; switch (ocode) { case TRUTH_ANDIF_EXPR: stack[sp].expr = default_function_array_conversion (stack[sp].expr); stack[sp].expr.value = c_objc_common_truthvalue_conversion (default_conversion (stack[sp].expr.value)); skip_evaluation += stack[sp].expr.value == truthvalue_false_node; break; case TRUTH_ORIF_EXPR: stack[sp].expr = default_function_array_conversion (stack[sp].expr); stack[sp].expr.value = c_objc_common_truthvalue_conversion (default_conversion (stack[sp].expr.value)); skip_evaluation += stack[sp].expr.value == truthvalue_true_node; break; default: break; } sp++; stack[sp].expr = c_parser_cast_expression (parser, NULL); stack[sp].prec = oprec; stack[sp].op = ocode; } out: while (sp > 0) POP; return stack[0].expr; #undef POP } /* Parse a cast expression (C90 6.3.4, C99 6.5.4). If AFTER is not NULL then it is an Objective-C message expression which is the primary-expression starting the expression as an initializer. cast-expression: unary-expression ( type-name ) unary-expression */ static struct c_expr c_parser_cast_expression (c_parser *parser, struct c_expr *after) { gcc_assert (!after || c_dialect_objc ()); if (after) return c_parser_postfix_expression_after_primary (parser, *after); /* If the expression begins with a parenthesized type name, it may be either a cast or a compound literal; we need to see whether the next character is '{' to tell the difference. If not, it is an unary expression. */ if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { struct c_type_name *type_name; struct c_expr ret; struct c_expr expr; c_parser_consume_token (parser); type_name = c_parser_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (type_name == NULL) { ret.value = error_mark_node; ret.original_code = ERROR_MARK; return ret; } /* Save casted types in the function's used types hash table. */ used_types_insert (type_name->specs->type); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) return c_parser_postfix_expression_after_paren_type (parser, type_name); expr = c_parser_cast_expression (parser, NULL); expr = default_function_array_conversion (expr); ret.value = c_cast_expr (type_name, expr.value); ret.original_code = ERROR_MARK; return ret; } else return c_parser_unary_expression (parser); } /* Parse an unary expression (C90 6.3.3, C99 6.5.3). unary-expression: postfix-expression ++ unary-expression -- unary-expression unary-operator cast-expression sizeof unary-expression sizeof ( type-name ) unary-operator: one of & * + - ~ ! GNU extensions: unary-expression: __alignof__ unary-expression __alignof__ ( type-name ) && identifier unary-operator: one of __extension__ __real__ __imag__ In addition, the GNU syntax treats ++ and -- as unary operators, so they may be applied to cast expressions with errors for non-lvalues given later. */ static struct c_expr c_parser_unary_expression (c_parser *parser) { int ext; struct c_expr ret, op; switch (c_parser_peek_token (parser)->type) { case CPP_PLUS_PLUS: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (PREINCREMENT_EXPR, op); case CPP_MINUS_MINUS: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (PREDECREMENT_EXPR, op); case CPP_AND: c_parser_consume_token (parser); return parser_build_unary_op (ADDR_EXPR, c_parser_cast_expression (parser, NULL)); case CPP_MULT: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); ret.value = build_indirect_ref (op.value, "unary *"); ret.original_code = ERROR_MARK; return ret; case CPP_PLUS: c_parser_consume_token (parser); if (!c_dialect_objc () && !in_system_header) warning (OPT_Wtraditional, "traditional C rejects the unary plus operator"); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (CONVERT_EXPR, op); case CPP_MINUS: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (NEGATE_EXPR, op); case CPP_COMPL: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (BIT_NOT_EXPR, op); case CPP_NOT: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (TRUTH_NOT_EXPR, op); case CPP_AND_AND: /* Refer to the address of a label as a pointer. */ c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { ret.value = finish_label_address_expr (c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } else { c_parser_error (parser, "expected identifier"); ret.value = error_mark_node; } ret.original_code = ERROR_MARK; return ret; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_SIZEOF: return c_parser_sizeof_expression (parser); case RID_ALIGNOF: return c_parser_alignof_expression (parser); case RID_EXTENSION: c_parser_consume_token (parser); ext = disable_extension_diagnostics (); ret = c_parser_cast_expression (parser, NULL); restore_extension_diagnostics (ext); return ret; case RID_REALPART: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (REALPART_EXPR, op); case RID_IMAGPART: c_parser_consume_token (parser); op = c_parser_cast_expression (parser, NULL); op = default_function_array_conversion (op); return parser_build_unary_op (IMAGPART_EXPR, op); default: return c_parser_postfix_expression (parser); } default: return c_parser_postfix_expression (parser); } } /* Parse a sizeof expression. */ static struct c_expr c_parser_sizeof_expression (c_parser *parser) { struct c_expr expr; gcc_assert (c_parser_next_token_is_keyword (parser, RID_SIZEOF)); c_parser_consume_token (parser); skip_evaluation++; in_sizeof++; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { /* Either sizeof ( type-name ) or sizeof unary-expression starting with a compound literal. */ struct c_type_name *type_name; c_parser_consume_token (parser); type_name = c_parser_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (type_name == NULL) { struct c_expr ret; skip_evaluation--; in_sizeof--; ret.value = error_mark_node; ret.original_code = ERROR_MARK; return ret; } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { expr = c_parser_postfix_expression_after_paren_type (parser, type_name); goto sizeof_expr; } /* sizeof ( type-name ). */ skip_evaluation--; in_sizeof--; if (type_name->declarator->kind == cdk_array && type_name->declarator->u.array.vla_unspec_p) { /* C99 6.7.5.2p4 */ error ("%<[*]%> not allowed in other than a declaration"); } return c_expr_sizeof_type (type_name); } else { expr = c_parser_unary_expression (parser); sizeof_expr: skip_evaluation--; in_sizeof--; if (TREE_CODE (expr.value) == COMPONENT_REF && DECL_C_BIT_FIELD (TREE_OPERAND (expr.value, 1))) error ("%<sizeof%> applied to a bit-field"); return c_expr_sizeof_expr (expr); } } /* Parse an alignof expression. */ static struct c_expr c_parser_alignof_expression (c_parser *parser) { struct c_expr expr; gcc_assert (c_parser_next_token_is_keyword (parser, RID_ALIGNOF)); c_parser_consume_token (parser); skip_evaluation++; in_alignof++; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN) && c_token_starts_typename (c_parser_peek_2nd_token (parser))) { /* Either __alignof__ ( type-name ) or __alignof__ unary-expression starting with a compound literal. */ struct c_type_name *type_name; struct c_expr ret; c_parser_consume_token (parser); type_name = c_parser_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (type_name == NULL) { struct c_expr ret; skip_evaluation--; in_alignof--; ret.value = error_mark_node; ret.original_code = ERROR_MARK; return ret; } if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { expr = c_parser_postfix_expression_after_paren_type (parser, type_name); goto alignof_expr; } /* alignof ( type-name ). */ skip_evaluation--; in_alignof--; ret.value = c_alignof (groktypename (type_name)); ret.original_code = ERROR_MARK; return ret; } else { struct c_expr ret; expr = c_parser_unary_expression (parser); alignof_expr: skip_evaluation--; in_alignof--; ret.value = c_alignof_expr (expr.value); ret.original_code = ERROR_MARK; return ret; } } /* Parse a postfix expression (C90 6.3.1-6.3.2, C99 6.5.1-6.5.2). postfix-expression: primary-expression postfix-expression [ expression ] postfix-expression ( argument-expression-list[opt] ) postfix-expression . identifier postfix-expression -> identifier postfix-expression ++ postfix-expression -- ( type-name ) { initializer-list } ( type-name ) { initializer-list , } argument-expression-list: argument-expression argument-expression-list , argument-expression primary-expression: identifier constant string-literal ( expression ) GNU extensions: primary-expression: __func__ (treated as a keyword in GNU C) __FUNCTION__ __PRETTY_FUNCTION__ ( compound-statement ) __builtin_va_arg ( assignment-expression , type-name ) __builtin_offsetof ( type-name , offsetof-member-designator ) __builtin_choose_expr ( assignment-expression , assignment-expression , assignment-expression ) __builtin_types_compatible_p ( type-name , type-name ) offsetof-member-designator: identifier offsetof-member-designator . identifier offsetof-member-designator [ expression ] Objective-C: primary-expression: [ objc-receiver objc-message-args ] @selector ( objc-selector-arg ) @protocol ( identifier ) @encode ( type-name ) objc-string-literal */ static struct c_expr c_parser_postfix_expression (c_parser *parser) { struct c_expr expr, e1, e2, e3; struct c_type_name *t1, *t2; switch (c_parser_peek_token (parser)->type) { case CPP_NUMBER: case CPP_CHAR: case CPP_WCHAR: expr.value = c_parser_peek_token (parser)->value; expr.original_code = ERROR_MARK; c_parser_consume_token (parser); break; case CPP_STRING: case CPP_WSTRING: expr.value = c_parser_peek_token (parser)->value; expr.original_code = STRING_CST; c_parser_consume_token (parser); break; case CPP_OBJC_STRING: gcc_assert (c_dialect_objc ()); expr.value = objc_build_string_object (c_parser_peek_token (parser)->value); expr.original_code = ERROR_MARK; c_parser_consume_token (parser); break; case CPP_NAME: if (c_parser_peek_token (parser)->id_kind != C_ID_ID) { c_parser_error (parser, "expected expression"); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } { tree id = c_parser_peek_token (parser)->value; location_t loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); expr.value = build_external_ref (id, (c_parser_peek_token (parser)->type == CPP_OPEN_PAREN), loc); expr.original_code = ERROR_MARK; } break; case CPP_OPEN_PAREN: /* A parenthesized expression, statement expression or compound literal. */ if (c_parser_peek_2nd_token (parser)->type == CPP_OPEN_BRACE) { /* A statement expression. */ tree stmt; c_parser_consume_token (parser); c_parser_consume_token (parser); if (cur_stmt_list == NULL) { error ("braced-group within expression allowed " "only inside a function"); parser->error = true; c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, NULL); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } stmt = c_begin_stmt_expr (); c_parser_compound_statement_nostart (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (pedantic) pedwarn ("ISO C forbids braced-groups within expressions"); expr.value = c_finish_stmt_expr (stmt); expr.original_code = ERROR_MARK; } else if (c_token_starts_typename (c_parser_peek_2nd_token (parser))) { /* A compound literal. ??? Can we actually get here rather than going directly to c_parser_postfix_expression_after_paren_type from elsewhere? */ struct c_type_name *type_name; c_parser_consume_token (parser); type_name = c_parser_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (type_name == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; } else expr = c_parser_postfix_expression_after_paren_type (parser, type_name); } else { /* A parenthesized expression. */ c_parser_consume_token (parser); expr = c_parser_expression (parser); if (TREE_CODE (expr.value) == MODIFY_EXPR) TREE_NO_WARNING (expr.value) = 1; expr.original_code = ERROR_MARK; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } break; case CPP_KEYWORD: switch (c_parser_peek_token (parser)->keyword) { case RID_FUNCTION_NAME: case RID_PRETTY_FUNCTION_NAME: case RID_C99_FUNCTION_NAME: expr.value = fname_decl (c_parser_peek_token (parser)->keyword, c_parser_peek_token (parser)->value); expr.original_code = ERROR_MARK; c_parser_consume_token (parser); break; case RID_VA_ARG: c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } e1 = c_parser_expr_no_commas (parser, NULL); if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } t1 = c_parser_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (t1 == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; } else { expr.value = build_va_arg (e1.value, groktypename (t1)); expr.original_code = ERROR_MARK; } break; case RID_OFFSETOF: c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } t1 = c_parser_type_name (parser); if (t1 == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } { tree type = groktypename (t1); tree offsetof_ref; if (type == error_mark_node) offsetof_ref = error_mark_node; else offsetof_ref = build1 (INDIRECT_REF, type, null_pointer_node); /* Parse the second argument to __builtin_offsetof. We must have one identifier, and beyond that we want to accept sub structure and sub array references. */ if (c_parser_next_token_is (parser, CPP_NAME)) { offsetof_ref = build_component_ref (offsetof_ref, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); while (c_parser_next_token_is (parser, CPP_DOT) || c_parser_next_token_is (parser, CPP_OPEN_SQUARE)) { if (c_parser_next_token_is (parser, CPP_DOT)) { c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } offsetof_ref = build_component_ref (offsetof_ref, c_parser_peek_token (parser)->value); c_parser_consume_token (parser); } else { tree idx; c_parser_consume_token (parser); idx = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); offsetof_ref = build_array_ref (offsetof_ref, idx); } } } else c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); expr.value = fold_offsetof (offsetof_ref, NULL_TREE); expr.original_code = ERROR_MARK; } break; case RID_CHOOSE_EXPR: c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } e1 = c_parser_expr_no_commas (parser, NULL); if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } e2 = c_parser_expr_no_commas (parser, NULL); if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } e3 = c_parser_expr_no_commas (parser, NULL); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); { tree c; c = fold (e1.value); if (TREE_CODE (c) != INTEGER_CST) error ("first argument to %<__builtin_choose_expr%> not" " a constant"); expr = integer_zerop (c) ? e3 : e2; } break; case RID_TYPES_COMPATIBLE_P: c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } t1 = c_parser_type_name (parser); if (t1 == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } if (!c_parser_require (parser, CPP_COMMA, "expected %<,%>")) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } t2 = c_parser_type_name (parser); if (t2 == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); { tree e1, e2; e1 = TYPE_MAIN_VARIANT (groktypename (t1)); e2 = TYPE_MAIN_VARIANT (groktypename (t2)); expr.value = comptypes (e1, e2) ? build_int_cst (NULL_TREE, 1) : build_int_cst (NULL_TREE, 0); expr.original_code = ERROR_MARK; } break; case RID_AT_SELECTOR: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } { tree sel = c_parser_objc_selector_arg (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); expr.value = objc_build_selector_expr (sel); expr.original_code = ERROR_MARK; } break; case RID_AT_PROTOCOL: gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); expr.value = objc_build_protocol_expr (id); expr.original_code = ERROR_MARK; } break; case RID_AT_ENCODE: /* Extension to support C-structures in the archiver. */ gcc_assert (c_dialect_objc ()); c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } t1 = c_parser_type_name (parser); if (t1 == NULL) { expr.value = error_mark_node; expr.original_code = ERROR_MARK; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); break; } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); { tree type = groktypename (t1); expr.value = objc_build_encode_expr (type); expr.original_code = ERROR_MARK; } break; default: c_parser_error (parser, "expected expression"); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } break; case CPP_OPEN_SQUARE: if (c_dialect_objc ()) { tree receiver, args; c_parser_consume_token (parser); receiver = c_parser_objc_receiver (parser); args = c_parser_objc_message_args (parser); c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); expr.value = objc_build_message_expr (build_tree_list (receiver, args)); expr.original_code = ERROR_MARK; break; } /* Else fall through to report error. */ default: c_parser_error (parser, "expected expression"); expr.value = error_mark_node; expr.original_code = ERROR_MARK; break; } return c_parser_postfix_expression_after_primary (parser, expr); } /* Parse a postfix expression after a parenthesized type name: the brace-enclosed initializer of a compound literal, possibly followed by some postfix operators. This is separate because it is not possible to tell until after the type name whether a cast expression has a cast or a compound literal, or whether the operand of sizeof is a parenthesized type name or starts with a compound literal. */ static struct c_expr c_parser_postfix_expression_after_paren_type (c_parser *parser, struct c_type_name *type_name) { tree type; struct c_expr init; struct c_expr expr; start_init (NULL_TREE, NULL, 0); type = groktypename (type_name); if (type != error_mark_node && C_TYPE_VARIABLE_SIZE (type)) { error ("compound literal has variable size"); type = error_mark_node; } init = c_parser_braced_init (parser, type, false); finish_init (); maybe_warn_string_init (type, init); if (pedantic && !flag_isoc99) pedwarn ("ISO C90 forbids compound literals"); expr.value = build_compound_literal (type, init.value); expr.original_code = ERROR_MARK; return c_parser_postfix_expression_after_primary (parser, expr); } /* Parse a postfix expression after the initial primary or compound literal; that is, parse a series of postfix operators. */ static struct c_expr c_parser_postfix_expression_after_primary (c_parser *parser, struct c_expr expr) { tree ident, idx, exprlist; while (true) { switch (c_parser_peek_token (parser)->type) { case CPP_OPEN_SQUARE: /* Array reference. */ c_parser_consume_token (parser); idx = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_SQUARE, "expected %<]%>"); expr.value = build_array_ref (expr.value, idx); expr.original_code = ERROR_MARK; break; case CPP_OPEN_PAREN: /* Function call. */ c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_CLOSE_PAREN)) exprlist = NULL_TREE; else exprlist = c_parser_expr_list (parser, true); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); expr.value = build_function_call (expr.value, exprlist); expr.original_code = ERROR_MARK; break; case CPP_DOT: /* Structure element reference. */ c_parser_consume_token (parser); expr = default_function_array_conversion (expr); if (c_parser_next_token_is (parser, CPP_NAME)) ident = c_parser_peek_token (parser)->value; else { c_parser_error (parser, "expected identifier"); expr.value = error_mark_node; expr.original_code = ERROR_MARK; return expr; } c_parser_consume_token (parser); expr.value = build_component_ref (expr.value, ident); expr.original_code = ERROR_MARK; break; case CPP_DEREF: /* Structure element reference. */ c_parser_consume_token (parser); expr = default_function_array_conversion (expr); if (c_parser_next_token_is (parser, CPP_NAME)) ident = c_parser_peek_token (parser)->value; else { c_parser_error (parser, "expected identifier"); expr.value = error_mark_node; expr.original_code = ERROR_MARK; return expr; } c_parser_consume_token (parser); expr.value = build_component_ref (build_indirect_ref (expr.value, "->"), ident); expr.original_code = ERROR_MARK; break; case CPP_PLUS_PLUS: /* Postincrement. */ c_parser_consume_token (parser); expr = default_function_array_conversion (expr); expr.value = build_unary_op (POSTINCREMENT_EXPR, expr.value, 0); expr.original_code = ERROR_MARK; break; case CPP_MINUS_MINUS: /* Postdecrement. */ c_parser_consume_token (parser); expr = default_function_array_conversion (expr); expr.value = build_unary_op (POSTDECREMENT_EXPR, expr.value, 0); expr.original_code = ERROR_MARK; break; default: return expr; } } } /* Parse an expression (C90 6.3.17, C99 6.5.17). expression: assignment-expression expression , assignment-expression */ static struct c_expr c_parser_expression (c_parser *parser) { struct c_expr expr; expr = c_parser_expr_no_commas (parser, NULL); while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_expr next; c_parser_consume_token (parser); next = c_parser_expr_no_commas (parser, NULL); next = default_function_array_conversion (next); expr.value = build_compound_expr (expr.value, next.value); expr.original_code = COMPOUND_EXPR; } return expr; } /* Parse an expression and convert functions or arrays to pointers. */ static struct c_expr c_parser_expression_conv (c_parser *parser) { struct c_expr expr; expr = c_parser_expression (parser); expr = default_function_array_conversion (expr); #ifdef TARG_SL /* Verify sequence points for expr, Warning for undefined behaviors */ if (warn_sequence_point) verify_sequence_points (expr.value); #endif return expr; } /* Parse a non-empty list of expressions. If CONVERT_P, convert functions and arrays to pointers. nonempty-expr-list: assignment-expression nonempty-expr-list , assignment-expression */ static tree c_parser_expr_list (c_parser *parser, bool convert_p) { struct c_expr expr; tree ret, cur; expr = c_parser_expr_no_commas (parser, NULL); if (convert_p) expr = default_function_array_conversion (expr); ret = cur = build_tree_list (NULL_TREE, expr.value); while (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); expr = c_parser_expr_no_commas (parser, NULL); if (convert_p) expr = default_function_array_conversion (expr); cur = TREE_CHAIN (cur) = build_tree_list (NULL_TREE, expr.value); } return ret; } /* Parse Objective-C-specific constructs. */ /* Parse an objc-class-definition. objc-class-definition: @interface identifier objc-superclass[opt] objc-protocol-refs[opt] objc-class-instance-variables[opt] objc-methodprotolist @end @implementation identifier objc-superclass[opt] objc-class-instance-variables[opt] @interface identifier ( identifier ) objc-protocol-refs[opt] objc-methodprotolist @end @implementation identifier ( identifier ) objc-superclass: : identifier "@interface identifier (" must start "@interface identifier ( identifier ) ...": objc-methodprotolist in the first production may not start with a parenthesized identifier as a declarator of a data definition with no declaration specifiers if the objc-superclass, objc-protocol-refs and objc-class-instance-variables are omitted. */ static void c_parser_objc_class_definition (c_parser *parser) { bool iface_p; tree id1; tree superclass; if (c_parser_next_token_is_keyword (parser, RID_AT_INTERFACE)) iface_p = true; else if (c_parser_next_token_is_keyword (parser, RID_AT_IMPLEMENTATION)) iface_p = false; else gcc_unreachable (); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } id1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree id2; tree proto = NULL_TREE; c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); return; } id2 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (!iface_p) { objc_start_category_implementation (id1, id2); return; } if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); objc_start_category_interface (id1, id2, proto); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); objc_finish_interface (); return; } if (c_parser_next_token_is (parser, CPP_COLON)) { c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } superclass = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else superclass = NULL_TREE; if (iface_p) { tree proto = NULL_TREE; if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); objc_start_class_interface (id1, superclass, proto); } else objc_start_class_implementation (id1, superclass); if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) c_parser_objc_class_instance_variables (parser); if (iface_p) { objc_continue_interface (); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); objc_finish_interface (); } else { objc_continue_implementation (); return; } } /* Parse objc-class-instance-variables. objc-class-instance-variables: { objc-instance-variable-decl-list[opt] } objc-instance-variable-decl-list: objc-visibility-spec objc-instance-variable-decl ; ; objc-instance-variable-decl-list objc-visibility-spec objc-instance-variable-decl-list objc-instance-variable-decl ; objc-instance-variable-decl-list ; objc-visibility-spec: @private @protected @public objc-instance-variable-decl: struct-declaration */ static void c_parser_objc_class_instance_variables (c_parser *parser) { gcc_assert (c_parser_next_token_is (parser, CPP_OPEN_BRACE)); c_parser_consume_token (parser); while (c_parser_next_token_is_not (parser, CPP_EOF)) { tree decls; /* Parse any stray semicolon. */ if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { if (pedantic) pedwarn ("extra semicolon in struct or union specified"); c_parser_consume_token (parser); continue; } /* Stop if at the end of the instance variables. */ if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); break; } /* Parse any objc-visibility-spec. */ if (c_parser_next_token_is_keyword (parser, RID_AT_PRIVATE)) { c_parser_consume_token (parser); objc_set_visibility (2); continue; } else if (c_parser_next_token_is_keyword (parser, RID_AT_PROTECTED)) { c_parser_consume_token (parser); objc_set_visibility (0); continue; } else if (c_parser_next_token_is_keyword (parser, RID_AT_PUBLIC)) { c_parser_consume_token (parser); objc_set_visibility (1); continue; } else if (c_parser_next_token_is (parser, CPP_PRAGMA)) { c_parser_pragma (parser, pragma_external); continue; } /* Parse some comma-separated declarations. */ decls = c_parser_struct_declaration (parser); { /* Comma-separated instance variables are chained together in reverse order; add them one by one. */ tree ivar = nreverse (decls); for (; ivar; ivar = TREE_CHAIN (ivar)) objc_add_instance_variable (copy_node (ivar)); } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } } /* Parse an objc-class-declaration. objc-class-declaration: @class identifier-list ; */ static void c_parser_objc_class_declaration (c_parser *parser) { tree list = NULL_TREE; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_CLASS)); c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } id = c_parser_peek_token (parser)->value; list = chainon (list, build_tree_list (NULL_TREE, id)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_declare_class (list); } /* Parse an objc-alias-declaration. objc-alias-declaration: @compatibility_alias identifier identifier ; */ static void c_parser_objc_alias_declaration (c_parser *parser) { tree id1, id2; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_ALIAS)); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); return; } id1 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); c_parser_skip_until_found (parser, CPP_SEMICOLON, NULL); return; } id2 = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_declare_alias (id1, id2); } /* Parse an objc-protocol-definition. objc-protocol-definition: @protocol identifier objc-protocol-refs[opt] objc-methodprotolist @end @protocol identifier-list ; "@protocol identifier ;" should be resolved as "@protocol identifier-list ;": objc-methodprotolist may not start with a semicolon in the first alternative if objc-protocol-refs are omitted. */ static void c_parser_objc_protocol_definition (c_parser *parser) { gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_PROTOCOL)); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return; } if (c_parser_peek_2nd_token (parser)->type == CPP_COMMA || c_parser_peek_2nd_token (parser)->type == CPP_SEMICOLON) { tree list = NULL_TREE; /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } id = c_parser_peek_token (parser)->value; list = chainon (list, build_tree_list (NULL_TREE, id)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); objc_declare_protocols (list); } else { tree id = c_parser_peek_token (parser)->value; tree proto = NULL_TREE; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_LESS)) proto = c_parser_objc_protocol_refs (parser); objc_pq_context = 1; objc_start_protocol (id, proto); c_parser_objc_methodprotolist (parser); c_parser_require_keyword (parser, RID_AT_END, "expected %<@end%>"); objc_pq_context = 0; objc_finish_interface (); } } /* Parse an objc-method-type. objc-method-type: + - */ static enum tree_code c_parser_objc_method_type (c_parser *parser) { switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: c_parser_consume_token (parser); return PLUS_EXPR; case CPP_MINUS: c_parser_consume_token (parser); return MINUS_EXPR; default: gcc_unreachable (); } } /* Parse an objc-method-definition. objc-method-definition: objc-method-type objc-method-decl ;[opt] compound-statement */ static void c_parser_objc_method_definition (c_parser *parser) { enum tree_code type = c_parser_objc_method_type (parser); tree decl; objc_set_method_type (type); objc_pq_context = 1; decl = c_parser_objc_method_decl (parser); if (c_parser_next_token_is (parser, CPP_SEMICOLON)) { c_parser_consume_token (parser); if (pedantic) pedwarn ("extra semicolon in method definition specified"); } if (!c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { c_parser_error (parser, "expected %<{%>"); return; } objc_pq_context = 0; objc_start_method_definition (decl); add_stmt (c_parser_compound_statement (parser)); objc_finish_method_definition (current_function_decl); } /* Parse an objc-methodprotolist. objc-methodprotolist: empty objc-methodprotolist objc-methodproto objc-methodprotolist declaration objc-methodprotolist ; The declaration is a data definition, which may be missing declaration specifiers under the same rules and diagnostics as other data definitions outside functions, and the stray semicolon is diagnosed the same way as a stray semicolon outside a function. */ static void c_parser_objc_methodprotolist (c_parser *parser) { while (true) { /* The list is terminated by @end. */ switch (c_parser_peek_token (parser)->type) { case CPP_SEMICOLON: if (pedantic) pedwarn ("ISO C does not allow extra %<;%> outside of a function"); c_parser_consume_token (parser); break; case CPP_PLUS: case CPP_MINUS: c_parser_objc_methodproto (parser); break; case CPP_PRAGMA: c_parser_pragma (parser, pragma_external); break; case CPP_EOF: return; default: if (c_parser_next_token_is_keyword (parser, RID_AT_END)) return; c_parser_declaration_or_fndef (parser, false, true, false, true); break; } } } /* Parse an objc-methodproto. objc-methodproto: objc-method-type objc-method-decl ; */ static void c_parser_objc_methodproto (c_parser *parser) { enum tree_code type = c_parser_objc_method_type (parser); tree decl; objc_set_method_type (type); /* Remember protocol qualifiers in prototypes. */ objc_pq_context = 1; decl = c_parser_objc_method_decl (parser); /* Forget protocol qualifiers here. */ objc_pq_context = 0; objc_add_method_declaration (decl); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* Parse an objc-method-decl. objc-method-decl: ( objc-type-name ) objc-selector objc-selector ( objc-type-name ) objc-keyword-selector objc-optparmlist objc-keyword-selector objc-optparmlist objc-keyword-selector: objc-keyword-decl objc-keyword-selector objc-keyword-decl objc-keyword-decl: objc-selector : ( objc-type-name ) identifier objc-selector : identifier : ( objc-type-name ) identifier : identifier objc-optparmlist: objc-optparms objc-optellipsis objc-optparms: empty objc-opt-parms , parameter-declaration objc-optellipsis: empty , ... */ static tree c_parser_objc_method_decl (c_parser *parser) { tree type = NULL_TREE; tree sel; tree parms = NULL_TREE; bool ellipsis = false; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); type = c_parser_objc_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } sel = c_parser_objc_selector (parser); /* If there is no selector, or a colon follows, we have an objc-keyword-selector. If there is a selector, and a colon does not follow, that selector ends the objc-method-decl. */ if (!sel || c_parser_next_token_is (parser, CPP_COLON)) { tree tsel = sel; tree list = NULL_TREE; while (true) { tree atype = NULL_TREE, id, keyworddecl; if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) break; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); atype = c_parser_objc_type_name (parser); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); return error_mark_node; } id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); keyworddecl = objc_build_keyword_decl (tsel, atype, id); list = chainon (list, keyworddecl); tsel = c_parser_objc_selector (parser); if (!tsel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } /* Parse the optional parameter list. Optional Objective-C method parameters follow the C syntax, and may include '...' to denote a variable number of arguments. */ parms = make_node (TREE_LIST); while (c_parser_next_token_is (parser, CPP_COMMA)) { struct c_parm *parm; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_ELLIPSIS)) { ellipsis = true; c_parser_consume_token (parser); break; } parm = c_parser_parameter_declaration (parser, NULL_TREE); if (parm == NULL) break; parms = chainon (parms, build_tree_list (NULL_TREE, grokparm (parm))); } sel = list; } return objc_build_method_signature (type, sel, parms, ellipsis); } /* Parse an objc-type-name. objc-type-name: objc-type-qualifiers[opt] type-name objc-type-qualifiers[opt] objc-type-qualifiers: objc-type-qualifier objc-type-qualifiers objc-type-qualifier objc-type-qualifier: one of in out inout bycopy byref oneway */ static tree c_parser_objc_type_name (c_parser *parser) { tree quals = NULL_TREE; struct c_type_name *typename = NULL; tree type = NULL_TREE; while (true) { c_token *token = c_parser_peek_token (parser); if (token->type == CPP_KEYWORD && (token->keyword == RID_IN || token->keyword == RID_OUT || token->keyword == RID_INOUT || token->keyword == RID_BYCOPY || token->keyword == RID_BYREF || token->keyword == RID_ONEWAY)) { quals = chainon (quals, build_tree_list (NULL_TREE, token->value)); c_parser_consume_token (parser); } else break; } if (c_parser_next_token_starts_typename (parser)) typename = c_parser_type_name (parser); if (typename) type = groktypename (typename); return build_tree_list (quals, type); } /* Parse objc-protocol-refs. objc-protocol-refs: < identifier-list > */ static tree c_parser_objc_protocol_refs (c_parser *parser) { tree list = NULL_TREE; gcc_assert (c_parser_next_token_is (parser, CPP_LESS)); c_parser_consume_token (parser); /* Any identifiers, including those declared as type names, are OK here. */ while (true) { tree id; if (c_parser_next_token_is_not (parser, CPP_NAME)) { c_parser_error (parser, "expected identifier"); break; } id = c_parser_peek_token (parser)->value; list = chainon (list, build_tree_list (NULL_TREE, id)); c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) c_parser_consume_token (parser); else break; } c_parser_require (parser, CPP_GREATER, "expected %<>%>"); return list; } /* Parse an objc-try-catch-statement. objc-try-catch-statement: @try compound-statement objc-catch-list[opt] @try compound-statement objc-catch-list[opt] @finally compound-statement objc-catch-list: @catch ( parameter-declaration ) compound-statement objc-catch-list @catch ( parameter-declaration ) compound-statement */ static void c_parser_objc_try_catch_statement (c_parser *parser) { location_t loc; tree stmt; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_TRY)); c_parser_consume_token (parser); loc = c_parser_peek_token (parser)->location; stmt = c_parser_compound_statement (parser); objc_begin_try_stmt (loc, stmt); while (c_parser_next_token_is_keyword (parser, RID_AT_CATCH)) { struct c_parm *parm; c_parser_consume_token (parser); if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) break; parm = c_parser_parameter_declaration (parser, NULL_TREE); if (parm == NULL) { c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, NULL); break; } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); objc_begin_catch_clause (grokparm (parm)); if (c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) c_parser_compound_statement_nostart (parser); objc_finish_catch_clause (); } if (c_parser_next_token_is_keyword (parser, RID_AT_FINALLY)) { location_t finloc; tree finstmt; c_parser_consume_token (parser); finloc = c_parser_peek_token (parser)->location; finstmt = c_parser_compound_statement (parser); objc_build_finally_clause (finloc, finstmt); } objc_finish_try_stmt (); } /* Parse an objc-synchronized-statement. objc-synchronized-statement: @synchronized ( expression ) compound-statement */ static void c_parser_objc_synchronized_statement (c_parser *parser) { location_t loc; tree expr, stmt; gcc_assert (c_parser_next_token_is_keyword (parser, RID_AT_SYNCHRONIZED)); c_parser_consume_token (parser); loc = c_parser_peek_token (parser)->location; if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { expr = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else expr = error_mark_node; stmt = c_parser_compound_statement (parser); objc_build_synchronized (loc, expr, stmt); } /* Parse an objc-selector; return NULL_TREE without an error if the next token is not an objc-selector. objc-selector: identifier one of enum struct union if else while do for switch case default break continue return goto asm sizeof typeof __alignof unsigned long const short volatile signed restrict _Complex in out inout bycopy byref oneway int char float double void _Bool ??? Why this selection of keywords but not, for example, storage class specifiers? */ static tree c_parser_objc_selector (c_parser *parser) { c_token *token = c_parser_peek_token (parser); tree value = token->value; if (token->type == CPP_NAME) { c_parser_consume_token (parser); return value; } if (token->type != CPP_KEYWORD) return NULL_TREE; switch (token->keyword) { case RID_ENUM: case RID_STRUCT: case RID_UNION: case RID_IF: case RID_ELSE: case RID_WHILE: case RID_DO: case RID_FOR: case RID_SWITCH: case RID_CASE: case RID_DEFAULT: case RID_BREAK: case RID_CONTINUE: case RID_RETURN: case RID_GOTO: case RID_ASM: case RID_SIZEOF: case RID_TYPEOF: case RID_ALIGNOF: case RID_UNSIGNED: case RID_LONG: case RID_CONST: case RID_SHORT: case RID_VOLATILE: case RID_SIGNED: case RID_RESTRICT: case RID_COMPLEX: case RID_IN: case RID_OUT: case RID_INOUT: case RID_BYCOPY: case RID_BYREF: case RID_ONEWAY: case RID_INT: case RID_CHAR: case RID_FLOAT: case RID_DOUBLE: case RID_VOID: case RID_BOOL: c_parser_consume_token (parser); return value; default: return NULL_TREE; } } /* Parse an objc-selector-arg. objc-selector-arg: objc-selector objc-keywordname-list objc-keywordname-list: objc-keywordname objc-keywordname-list objc-keywordname objc-keywordname: objc-selector : : */ static tree c_parser_objc_selector_arg (c_parser *parser) { tree sel = c_parser_objc_selector (parser); tree list = NULL_TREE; if (sel && c_parser_next_token_is_not (parser, CPP_COLON)) return sel; while (true) { if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) return list; list = chainon (list, build_tree_list (sel, NULL_TREE)); sel = c_parser_objc_selector (parser); if (!sel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } return list; } /* Parse an objc-receiver. objc-receiver: expression class-name type-name */ static tree c_parser_objc_receiver (c_parser *parser) { if (c_parser_peek_token (parser)->type == CPP_NAME && (c_parser_peek_token (parser)->id_kind == C_ID_TYPENAME || c_parser_peek_token (parser)->id_kind == C_ID_CLASSNAME)) { tree id = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); return objc_get_class_reference (id); } return c_parser_expression (parser).value; } /* Parse objc-message-args. objc-message-args: objc-selector objc-keywordarg-list objc-keywordarg-list: objc-keywordarg objc-keywordarg-list objc-keywordarg objc-keywordarg: objc-selector : objc-keywordexpr : objc-keywordexpr */ static tree c_parser_objc_message_args (c_parser *parser) { tree sel = c_parser_objc_selector (parser); tree list = NULL_TREE; if (sel && c_parser_next_token_is_not (parser, CPP_COLON)) return sel; while (true) { tree keywordexpr; if (!c_parser_require (parser, CPP_COLON, "expected %<:%>")) return list; keywordexpr = c_parser_objc_keywordexpr (parser); list = chainon (list, build_tree_list (sel, keywordexpr)); sel = c_parser_objc_selector (parser); if (!sel && c_parser_next_token_is_not (parser, CPP_COLON)) break; } return list; } /* Parse an objc-keywordexpr. objc-keywordexpr: nonempty-expr-list */ static tree c_parser_objc_keywordexpr (c_parser *parser) { tree list = c_parser_expr_list (parser, true); if (TREE_CHAIN (list) == NULL_TREE) { /* Just return the expression, remove a level of indirection. */ return TREE_VALUE (list); } else { /* We have a comma expression, we will collapse later. */ return list; } } /* Handle pragmas. Some OpenMP pragmas are associated with, and therefore should be considered, statements. ALLOW_STMT is true if we're within the context of a function and such pragmas are to be allowed. Returns true if we actually parsed such a pragma. */ static bool c_parser_pragma (c_parser *parser, enum pragma_context context) { unsigned int id; id = c_parser_peek_token (parser)->pragma_kind; gcc_assert (id != PRAGMA_NONE); switch (id) { case PRAGMA_OMP_BARRIER: if (context != pragma_compound) { if (context == pragma_stmt) c_parser_error (parser, "%<#pragma omp barrier%> may only be " "used in compound statements"); goto bad_stmt; } c_parser_omp_barrier (parser); return false; case PRAGMA_OMP_FLUSH: if (context != pragma_compound) { if (context == pragma_stmt) c_parser_error (parser, "%<#pragma omp flush%> may only be " "used in compound statements"); goto bad_stmt; } c_parser_omp_flush (parser); return false; case PRAGMA_OMP_TASKWAIT: if (context != pragma_compound) { if (context == pragma_stmt) c_parser_error (parser, "%<#pragma omp taskwait%> may only be " "used in compound statements"); goto bad_stmt; } c_parser_omp_taskwait (parser); return false; case PRAGMA_OMP_THREADPRIVATE: c_parser_omp_threadprivate (parser); return false; case PRAGMA_OMP_SECTION: error ("%<#pragma omp section%> may only be used in " "%<#pragma omp sections%> construct"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; case PRAGMA_GCC_PCH_PREPROCESS: c_parser_error (parser, "%<#pragma GCC pch_preprocess%> must be first"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; default: if (id < PRAGMA_FIRST_EXTERNAL) { if (context == pragma_external) { bad_stmt: c_parser_error (parser, "expected declaration specifiers"); c_parser_skip_until_found (parser, CPP_PRAGMA_EOL, NULL); return false; } c_parser_omp_construct (parser); return true; } break; } c_parser_consume_pragma (parser); c_invoke_pragma_handler (id); /* Skip to EOL, but suppress any error message. Those will have been generated by the handler routine through calling error, as opposed to calling c_parser_error. */ parser->error = true; c_parser_skip_to_pragma_eol (parser); return false; } /* The interface the pragma parsers have to the lexer. */ enum cpp_ttype pragma_lex (tree *value) { c_token *tok = c_parser_peek_token (the_parser); enum cpp_ttype ret = tok->type; *value = tok->value; if (ret == CPP_PRAGMA_EOL || ret == CPP_EOF) ret = CPP_EOF; else { if (ret == CPP_KEYWORD) ret = CPP_NAME; c_parser_consume_token (the_parser); } return ret; } static void c_parser_pragma_pch_preprocess (c_parser *parser) { tree name = NULL; c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_STRING)) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); } else c_parser_error (parser, "expected string literal"); c_parser_skip_to_pragma_eol (parser); if (name) c_common_pch_pragma (parse_in, TREE_STRING_POINTER (name)); } /* OpenMP 2.5 parsing routines. */ /* Returns name of the next clause. If the clause is not recognized PRAGMA_OMP_CLAUSE_NONE is returned and the token is not consumed. Otherwise appropriate pragma_omp_clause is returned and the token is consumed. */ static pragma_omp_clause c_parser_omp_clause_name (c_parser *parser) { pragma_omp_clause result = PRAGMA_OMP_CLAUSE_NONE; if (c_parser_next_token_is_keyword (parser, RID_IF)) result = PRAGMA_OMP_CLAUSE_IF; else if (c_parser_next_token_is_keyword (parser, RID_DEFAULT)) result = PRAGMA_OMP_CLAUSE_DEFAULT; else if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); switch (p[0]) { case 'c': if (!strcmp ("collapse", p)) result = PRAGMA_OMP_CLAUSE_COLLAPSE; else if (!strcmp ("copyin", p)) result = PRAGMA_OMP_CLAUSE_COPYIN; else if (!strcmp ("copyprivate", p)) result = PRAGMA_OMP_CLAUSE_COPYPRIVATE; break; case 'f': if (!strcmp ("firstprivate", p)) result = PRAGMA_OMP_CLAUSE_FIRSTPRIVATE; break; case 'l': if (!strcmp ("lastprivate", p)) result = PRAGMA_OMP_CLAUSE_LASTPRIVATE; break; case 'n': if (!strcmp ("nowait", p)) result = PRAGMA_OMP_CLAUSE_NOWAIT; else if (!strcmp ("num_threads", p)) result = PRAGMA_OMP_CLAUSE_NUM_THREADS; break; case 'o': if (!strcmp ("ordered", p)) result = PRAGMA_OMP_CLAUSE_ORDERED; break; case 'p': if (!strcmp ("private", p)) result = PRAGMA_OMP_CLAUSE_PRIVATE; break; case 'r': if (!strcmp ("reduction", p)) result = PRAGMA_OMP_CLAUSE_REDUCTION; break; case 's': if (!strcmp ("schedule", p)) result = PRAGMA_OMP_CLAUSE_SCHEDULE; else if (!strcmp ("shared", p)) result = PRAGMA_OMP_CLAUSE_SHARED; break; case 'u': if (!strcmp ("untied", p)) result = PRAGMA_OMP_CLAUSE_UNTIED; break; } } if (result != PRAGMA_OMP_CLAUSE_NONE) c_parser_consume_token (parser); return result; } /* Validate that a clause of the given type does not already exist. */ static void check_no_duplicate_clause (tree clauses, enum tree_code code, const char *name) { tree c; for (c = clauses; c ; c = OMP_CLAUSE_CHAIN (c)) if (OMP_CLAUSE_CODE (c) == code) { error ("too many %qs clauses", name); break; } } /* OpenMP 2.5: variable-list: identifier variable-list , identifier If KIND is nonzero, create the appropriate node and install the decl in OMP_CLAUSE_DECL and add the node to the head of the list. If KIND is zero, create a TREE_LIST with the decl in TREE_PURPOSE; return the list created. */ static tree c_parser_omp_variable_list (c_parser *parser, enum omp_clause_code kind, tree list) { if (c_parser_next_token_is_not (parser, CPP_NAME) || c_parser_peek_token (parser)->id_kind != C_ID_ID) c_parser_error (parser, "expected identifier"); while (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_token (parser)->id_kind == C_ID_ID) { tree t = lookup_name (c_parser_peek_token (parser)->value); if (t == NULL_TREE) undeclared_variable (c_parser_peek_token (parser)->value, c_parser_peek_token (parser)->location); else if (t == error_mark_node) ; else if (kind != 0) { tree u = build_omp_clause (kind); OMP_CLAUSE_DECL (u) = t; OMP_CLAUSE_CHAIN (u) = list; list = u; } else list = tree_cons (t, NULL_TREE, list); c_parser_consume_token (parser); if (c_parser_next_token_is_not (parser, CPP_COMMA)) break; c_parser_consume_token (parser); } return list; } /* Similarly, but expect leading and trailing parenthesis. This is a very common case for omp clauses. */ static tree c_parser_omp_var_list_parens (c_parser *parser, enum tree_code kind, tree list) { if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { list = c_parser_omp_variable_list (parser, kind, list); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } return list; } /* OpenMP 3.0: collapse ( constant-expression ) */ static tree c_parser_omp_clause_collapse (c_parser *parser, tree list) { tree c, num = error_mark_node; HOST_WIDE_INT n; location_t loc; check_no_duplicate_clause (list, OMP_CLAUSE_COLLAPSE, "collapse"); loc = c_parser_peek_token (parser)->location; if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { num = c_parser_expr_no_commas (parser, NULL).value; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } if (num == error_mark_node) return list; if (!INTEGRAL_TYPE_P (TREE_TYPE (num)) || !host_integerp (num, 0) || (n = tree_low_cst (num, 0)) <= 0 || (int) n != n) { error ("%Hcollapse argument needs positive constant integer expression", &loc); return list; } c = build_omp_clause (OMP_CLAUSE_COLLAPSE); OMP_CLAUSE_COLLAPSE_EXPR (c) = num; OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: copyin ( variable-list ) */ static tree c_parser_omp_clause_copyin (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_COPYIN, list); } /* OpenMP 2.5: copyprivate ( variable-list ) */ static tree c_parser_omp_clause_copyprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_COPYPRIVATE, list); } /* OpenMP 2.5: default ( shared | none ) */ static tree c_parser_omp_clause_default (c_parser *parser, tree list) { enum omp_clause_default_kind kind = OMP_CLAUSE_DEFAULT_UNSPECIFIED; tree c; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) return list; if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); switch (p[0]) { case 'n': if (strcmp ("none", p) != 0) goto invalid_kind; kind = OMP_CLAUSE_DEFAULT_NONE; break; case 's': if (strcmp ("shared", p) != 0) goto invalid_kind; kind = OMP_CLAUSE_DEFAULT_SHARED; break; default: goto invalid_kind; } c_parser_consume_token (parser); } else { invalid_kind: c_parser_error (parser, "expected %<none%> or %<shared%>"); } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (kind == OMP_CLAUSE_DEFAULT_UNSPECIFIED) return list; check_no_duplicate_clause (list, OMP_CLAUSE_DEFAULT, "default"); c = build_omp_clause (OMP_CLAUSE_DEFAULT); OMP_CLAUSE_CHAIN (c) = list; OMP_CLAUSE_DEFAULT_KIND (c) = kind; return c; } /* OpenMP 2.5: firstprivate ( variable-list ) */ static tree c_parser_omp_clause_firstprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_FIRSTPRIVATE, list); } /* OpenMP 2.5: if ( expression ) */ static tree c_parser_omp_clause_if (c_parser *parser, tree list) { if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { tree t = c_parser_paren_condition (parser); tree c; check_no_duplicate_clause (list, OMP_CLAUSE_IF, "if"); c = build_omp_clause (OMP_CLAUSE_IF); OMP_CLAUSE_IF_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } else c_parser_error (parser, "expected %<(%>"); return list; } /* OpenMP 2.5: lastprivate ( variable-list ) */ static tree c_parser_omp_clause_lastprivate (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_LASTPRIVATE, list); } /* OpenMP 2.5: nowait */ static tree c_parser_omp_clause_nowait (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; check_no_duplicate_clause (list, OMP_CLAUSE_NOWAIT, "nowait"); c = build_omp_clause (OMP_CLAUSE_NOWAIT); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: num_threads ( expression ) */ static tree c_parser_omp_clause_num_threads (c_parser *parser, tree list) { if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { tree c, t = c_parser_expression (parser).value; c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (!INTEGRAL_TYPE_P (TREE_TYPE (t))) { c_parser_error (parser, "expected integer expression"); return list; } /* Attempt to statically determine when the number isn't positive. */ c = fold_build2 (LE_EXPR, boolean_type_node, t, build_int_cst (TREE_TYPE (t), 0)); if (c == boolean_true_node) { warning (0, "%<num_threads%> value must be positive"); t = integer_one_node; } check_no_duplicate_clause (list, OMP_CLAUSE_NUM_THREADS, "num_threads"); c = build_omp_clause (OMP_CLAUSE_NUM_THREADS); OMP_CLAUSE_NUM_THREADS_EXPR (c) = t; OMP_CLAUSE_CHAIN (c) = list; list = c; } return list; } /* OpenMP 2.5: ordered */ static tree c_parser_omp_clause_ordered (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; check_no_duplicate_clause (list, OMP_CLAUSE_ORDERED, "ordered"); c = build_omp_clause (OMP_CLAUSE_ORDERED); OMP_CLAUSE_CHAIN (c) = list; return c; } /* OpenMP 2.5: private ( variable-list ) */ static tree c_parser_omp_clause_private (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_PRIVATE, list); } /* OpenMP 2.5: reduction ( reduction-operator : variable-list ) reduction-operator: One of: + * - & ^ | && || */ static tree c_parser_omp_clause_reduction (c_parser *parser, tree list) { if (c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) { enum tree_code code; switch (c_parser_peek_token (parser)->type) { case CPP_PLUS: code = PLUS_EXPR; break; case CPP_MULT: code = MULT_EXPR; break; case CPP_MINUS: code = MINUS_EXPR; break; case CPP_AND: code = BIT_AND_EXPR; break; case CPP_XOR: code = BIT_XOR_EXPR; break; case CPP_OR: code = BIT_IOR_EXPR; break; case CPP_AND_AND: code = TRUTH_ANDIF_EXPR; break; case CPP_OR_OR: code = TRUTH_ORIF_EXPR; break; default: c_parser_error (parser, "expected %<+%>, %<*%>, %<-%>, %<&%>, " "%<^%>, %<|%>, %<&&%>, or %<||%>"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, 0); return list; } c_parser_consume_token (parser); if (c_parser_require (parser, CPP_COLON, "expected %<:%>")) { tree nl, c; nl = c_parser_omp_variable_list (parser, OMP_CLAUSE_REDUCTION, list); for (c = nl; c != list; c = OMP_CLAUSE_CHAIN (c)) OMP_CLAUSE_REDUCTION_CODE (c) = code; list = nl; } c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } return list; } /* OpenMP 2.5: schedule ( schedule-kind ) schedule ( schedule-kind , expression ) schedule-kind: static | dynamic | guided | runtime | auto */ static tree c_parser_omp_clause_schedule (c_parser *parser, tree list) { tree c, t; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) return list; c = build_omp_clause (OMP_CLAUSE_SCHEDULE); if (c_parser_next_token_is (parser, CPP_NAME)) { tree kind = c_parser_peek_token (parser)->value; const char *p = IDENTIFIER_POINTER (kind); switch (p[0]) { case 'd': if (strcmp ("dynamic", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_DYNAMIC; break; case 'g': if (strcmp ("guided", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_GUIDED; break; case 'r': if (strcmp ("runtime", p) != 0) goto invalid_kind; OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_RUNTIME; break; default: goto invalid_kind; } } else if (c_parser_next_token_is_keyword (parser, RID_STATIC)) OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_STATIC; else if (c_parser_next_token_is_keyword (parser, RID_AUTO)) OMP_CLAUSE_SCHEDULE_KIND (c) = OMP_CLAUSE_SCHEDULE_AUTO; else goto invalid_kind; c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_COMMA)) { c_parser_consume_token (parser); t = c_parser_expr_no_commas (parser, NULL).value; if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_RUNTIME) error ("schedule %<runtime%> does not take " "a %<chunk_size%> parameter"); else if (OMP_CLAUSE_SCHEDULE_KIND (c) == OMP_CLAUSE_SCHEDULE_AUTO) error ("%schedule %<auto%> does not take " "a %<chunk_size%> parameter"); else if (TREE_CODE (TREE_TYPE (t)) == INTEGER_TYPE) OMP_CLAUSE_SCHEDULE_CHUNK_EXPR (c) = t; else c_parser_error (parser, "expected integer expression"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<,%> or %<)%>"); check_no_duplicate_clause (list, OMP_CLAUSE_SCHEDULE, "schedule"); OMP_CLAUSE_CHAIN (c) = list; return c; invalid_kind: c_parser_error (parser, "invalid schedule kind"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, 0); return list; } /* OpenMP 2.5: shared ( variable-list ) */ static tree c_parser_omp_clause_shared (c_parser *parser, tree list) { return c_parser_omp_var_list_parens (parser, OMP_CLAUSE_SHARED, list); } /* OpenMP 3.0: untied */ static tree c_parser_omp_clause_untied (c_parser *parser ATTRIBUTE_UNUSED, tree list) { tree c; /* FIXME: Should we allow duplicates? */ check_no_duplicate_clause (list, OMP_CLAUSE_UNTIED, "untied"); c = build_omp_clause (OMP_CLAUSE_UNTIED); OMP_CLAUSE_CHAIN (c) = list; return c; } /* Parse all OpenMP clauses. The set clauses allowed by the directive is a bitmask in MASK. Return the list of clauses found; the result of clause default goes in *pdefault. */ static tree c_parser_omp_all_clauses (c_parser *parser, unsigned int mask, const char *where) { tree clauses = NULL; while (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) { const pragma_omp_clause c_kind = c_parser_omp_clause_name (parser); const char *c_name; tree prev = clauses; switch (c_kind) { case PRAGMA_OMP_CLAUSE_COLLAPSE: clauses = c_parser_omp_clause_collapse (parser, clauses); c_name = "collapse"; break; case PRAGMA_OMP_CLAUSE_COPYIN: clauses = c_parser_omp_clause_copyin (parser, clauses); c_name = "copyin"; break; case PRAGMA_OMP_CLAUSE_COPYPRIVATE: clauses = c_parser_omp_clause_copyprivate (parser, clauses); c_name = "copyprivate"; break; case PRAGMA_OMP_CLAUSE_DEFAULT: clauses = c_parser_omp_clause_default (parser, clauses); c_name = "default"; break; case PRAGMA_OMP_CLAUSE_FIRSTPRIVATE: clauses = c_parser_omp_clause_firstprivate (parser, clauses); c_name = "firstprivate"; break; case PRAGMA_OMP_CLAUSE_IF: clauses = c_parser_omp_clause_if (parser, clauses); c_name = "if"; break; case PRAGMA_OMP_CLAUSE_LASTPRIVATE: clauses = c_parser_omp_clause_lastprivate (parser, clauses); c_name = "lastprivate"; break; case PRAGMA_OMP_CLAUSE_NOWAIT: clauses = c_parser_omp_clause_nowait (parser, clauses); c_name = "nowait"; break; case PRAGMA_OMP_CLAUSE_NUM_THREADS: clauses = c_parser_omp_clause_num_threads (parser, clauses); c_name = "num_threads"; break; case PRAGMA_OMP_CLAUSE_ORDERED: clauses = c_parser_omp_clause_ordered (parser, clauses); c_name = "ordered"; break; case PRAGMA_OMP_CLAUSE_PRIVATE: clauses = c_parser_omp_clause_private (parser, clauses); c_name = "private"; break; case PRAGMA_OMP_CLAUSE_REDUCTION: clauses = c_parser_omp_clause_reduction (parser, clauses); c_name = "reduction"; break; case PRAGMA_OMP_CLAUSE_SCHEDULE: clauses = c_parser_omp_clause_schedule (parser, clauses); c_name = "schedule"; break; case PRAGMA_OMP_CLAUSE_SHARED: clauses = c_parser_omp_clause_shared (parser, clauses); c_name = "shared"; break; case PRAGMA_OMP_CLAUSE_UNTIED: clauses = c_parser_omp_clause_untied (parser, clauses); c_name = "untied"; break; default: c_parser_error (parser, "expected %<#pragma omp%> clause"); goto saw_error; } if (((mask >> c_kind) & 1) == 0 && !parser->error) { /* Remove the invalid clause(s) from the list to avoid confusing the rest of the compiler. */ clauses = prev; error ("%qs is not valid for %qs", c_name, where); } } saw_error: c_parser_skip_to_pragma_eol (parser); return c_finish_omp_clauses (clauses); } /* OpenMP 2.5: structured-block: statement In practice, we're also interested in adding the statement to an outer node. So it is convenient if we work around the fact that c_parser_statement calls add_stmt. */ static tree c_parser_omp_structured_block (c_parser *parser) { tree stmt = push_stmt_list (); c_parser_statement (parser); return pop_stmt_list (stmt); } /* OpenMP 2.5: # pragma omp atomic new-line expression-stmt expression-stmt: x binop= expr | x++ | ++x | x-- | --x binop: +, *, -, /, &, ^, |, <<, >> where x is an lvalue expression with scalar type. */ static void c_parser_omp_atomic (c_parser *parser) { tree lhs, rhs; tree stmt; enum tree_code code; c_parser_skip_to_pragma_eol (parser); lhs = c_parser_unary_expression (parser).value; switch (TREE_CODE (lhs)) { case ERROR_MARK: saw_error: c_parser_skip_to_end_of_block_or_statement (parser); return; case PREINCREMENT_EXPR: case POSTINCREMENT_EXPR: lhs = TREE_OPERAND (lhs, 0); code = PLUS_EXPR; rhs = integer_one_node; break; case PREDECREMENT_EXPR: case POSTDECREMENT_EXPR: lhs = TREE_OPERAND (lhs, 0); code = MINUS_EXPR; rhs = integer_one_node; break; default: switch (c_parser_peek_token (parser)->type) { case CPP_MULT_EQ: code = MULT_EXPR; break; case CPP_DIV_EQ: code = TRUNC_DIV_EXPR; break; case CPP_PLUS_EQ: code = PLUS_EXPR; break; case CPP_MINUS_EQ: code = MINUS_EXPR; break; case CPP_LSHIFT_EQ: code = LSHIFT_EXPR; break; case CPP_RSHIFT_EQ: code = RSHIFT_EXPR; break; case CPP_AND_EQ: code = BIT_AND_EXPR; break; case CPP_OR_EQ: code = BIT_IOR_EXPR; break; case CPP_XOR_EQ: code = BIT_XOR_EXPR; break; default: c_parser_error (parser, "invalid operator for %<#pragma omp atomic%>"); goto saw_error; } c_parser_consume_token (parser); rhs = c_parser_expression (parser).value; break; } stmt = c_finish_omp_atomic (code, lhs, rhs); if (stmt != error_mark_node) add_stmt (stmt); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } /* OpenMP 2.5: # pragma omp barrier new-line */ static void c_parser_omp_barrier (c_parser *parser) { c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); c_finish_omp_barrier (); } /* OpenMP 2.5: # pragma omp critical [(name)] new-line structured-block */ static tree c_parser_omp_critical (c_parser *parser) { tree stmt, name = NULL; if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) { c_parser_consume_token (parser); if (c_parser_next_token_is (parser, CPP_NAME)) { name = c_parser_peek_token (parser)->value; c_parser_consume_token (parser); c_parser_require (parser, CPP_CLOSE_PAREN, "expected %<)%>"); } else c_parser_error (parser, "expected identifier"); } else if (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) c_parser_error (parser, "expected %<(%> or end of line"); c_parser_skip_to_pragma_eol (parser); stmt = c_parser_omp_structured_block (parser); return c_finish_omp_critical (stmt, name); } /* OpenMP 2.5: # pragma omp flush flush-vars[opt] new-line flush-vars: ( variable-list ) */ static void c_parser_omp_flush (c_parser *parser) { c_parser_consume_pragma (parser); if (c_parser_next_token_is (parser, CPP_OPEN_PAREN)) c_parser_omp_var_list_parens (parser, 0, NULL); else if (c_parser_next_token_is_not (parser, CPP_PRAGMA_EOL)) c_parser_error (parser, "expected %<(%> or end of line"); c_parser_skip_to_pragma_eol (parser); c_finish_omp_flush (); } /* Parse the restricted form of the for statement allowed by OpenMP. The real trick here is to determine the loop control variable early so that we can push a new decl if necessary to make it private. */ static tree c_parser_omp_for_loop (c_parser *parser, tree clauses, tree *par_clauses) { tree decl, cond, incr, save_break, save_cont, body, init, stmt, cl; tree declv, condv, incrv, initv, for_block = NULL, ret = NULL; location_t loc; bool fail = false, open_brace_parsed = false; int i, collapse = 1, nbraces = 0; for (cl = clauses; cl; cl = OMP_CLAUSE_CHAIN (cl)) if (OMP_CLAUSE_CODE (cl) == OMP_CLAUSE_COLLAPSE) collapse = tree_low_cst (OMP_CLAUSE_COLLAPSE_EXPR (cl), 0); gcc_assert (collapse >= 1); declv = make_tree_vec (collapse); initv = make_tree_vec (collapse); condv = make_tree_vec (collapse); incrv = make_tree_vec (collapse); if (!c_parser_next_token_is_keyword (parser, RID_FOR)) { c_parser_error (parser, "for statement expected"); return NULL; } loc = c_parser_peek_token (parser)->location; c_parser_consume_token (parser); for (i = 0; i < collapse; i++) { int bracecount = 0; if (!c_parser_require (parser, CPP_OPEN_PAREN, "expected %<(%>")) goto pop_scopes; /* Parse the initialization declaration or expression. */ if (c_parser_next_token_starts_declspecs (parser)) { if (i > 0) for_block = tree_cons (NULL, c_begin_compound_stmt (true), for_block); c_parser_declaration_or_fndef (parser, true, true, true, true); decl = check_for_loop_decls (); if (decl == NULL) goto error_init; if (DECL_INITIAL (decl) == error_mark_node) decl = error_mark_node; init = decl; } else if (c_parser_next_token_is (parser, CPP_NAME) && c_parser_peek_2nd_token (parser)->type == CPP_EQ) { struct c_expr init_exp; decl = c_parser_postfix_expression (parser).value; c_parser_require (parser, CPP_EQ, "expected %<=%>"); init_exp = c_parser_expr_no_commas (parser, NULL); init_exp = default_function_array_conversion (init_exp); init = build_modify_expr (decl, NOP_EXPR, init_exp.value); init = c_process_expr_stmt (init); c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); } else { error_init: c_parser_error (parser, "expected iteration declaration or initialization"); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); fail = true; goto parse_next; } /* Parse the loop condition. */ cond = NULL_TREE; if (c_parser_next_token_is_not (parser, CPP_SEMICOLON)) { cond = c_parser_expression_conv (parser).value; cond = c_objc_common_truthvalue_conversion (cond); if (cond && EXPR_P (cond)) SET_EXPR_LOCATION (cond, input_location); } c_parser_skip_until_found (parser, CPP_SEMICOLON, "expected %<;%>"); /* Parse the increment expression. */ incr = NULL_TREE; if (c_parser_next_token_is_not (parser, CPP_CLOSE_PAREN)) incr = c_process_expr_stmt (c_parser_expression (parser).value); c_parser_skip_until_found (parser, CPP_CLOSE_PAREN, "expected %<)%>"); if (decl == NULL || decl == error_mark_node || init == error_mark_node) fail = true; else { TREE_VEC_ELT (declv, i) = decl; TREE_VEC_ELT (initv, i) = init; TREE_VEC_ELT (condv, i) = cond; TREE_VEC_ELT (incrv, i) = incr; } parse_next: if (i == collapse - 1) break; /* FIXME: OpenMP 3.0 draft isn't very clear on what exactly is allowed in between the collapsed for loops to be still considered perfectly nested. Hopefully the final version clarifies this. For now handle (multiple) {'s and empty statements. */ do { if (c_parser_next_token_is_keyword (parser, RID_FOR)) { c_parser_consume_token (parser); break; } else if (c_parser_next_token_is (parser, CPP_OPEN_BRACE)) { c_parser_consume_token (parser); bracecount++; } else if (bracecount && c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { c_parser_error (parser, "not enough perfectly nested loops"); if (bracecount) { open_brace_parsed = true; bracecount--; } fail = true; collapse = 0; break; } } while (1); nbraces += bracecount; } save_break = c_break_label; c_break_label = size_one_node; save_cont = c_cont_label; c_cont_label = NULL_TREE; body = push_stmt_list (); if (open_brace_parsed) { stmt = c_begin_compound_stmt (true); c_parser_compound_statement_nostart (parser); add_stmt (c_end_compound_stmt (stmt, true)); } else add_stmt (c_parser_c99_block_statement (parser)); if (c_cont_label) add_stmt (build1 (LABEL_EXPR, void_type_node, c_cont_label)); body = pop_stmt_list (body); c_break_label = save_break; c_cont_label = save_cont; while (nbraces) { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) { c_parser_consume_token (parser); nbraces--; } else if (c_parser_next_token_is (parser, CPP_SEMICOLON)) c_parser_consume_token (parser); else { c_parser_error (parser, "collapsed loops not perfectly nested"); while (nbraces) { stmt = c_begin_compound_stmt (true); add_stmt (body); c_parser_compound_statement_nostart (parser); body = c_end_compound_stmt (stmt, true); nbraces--; } goto pop_scopes; } } /* Only bother calling c_finish_omp_for if we havn't already generated an error from the initialization parsing. */ if (!fail) { stmt = c_finish_omp_for (loc, declv, initv, condv, incrv, body, NULL); if (stmt) { if (par_clauses != NULL) { tree *c; for (c = par_clauses; *c ; ) if (OMP_CLAUSE_CODE (*c) != OMP_CLAUSE_FIRSTPRIVATE && OMP_CLAUSE_CODE (*c) != OMP_CLAUSE_LASTPRIVATE) c = &OMP_CLAUSE_CHAIN (*c); else { for (i = 0; i < collapse; i++) if (TREE_VEC_ELT (declv, i) == OMP_CLAUSE_DECL (*c)) break; if (i == collapse) c = &OMP_CLAUSE_CHAIN (*c); else if (OMP_CLAUSE_CODE (*c) == OMP_CLAUSE_FIRSTPRIVATE) { error ("%Hiteration variable %qD should not be firstprivate", &loc, OMP_CLAUSE_DECL (*c)); *c = OMP_CLAUSE_CHAIN (*c); } else { /* Copy lastprivate (decl) clause to OMP_FOR_CLAUSES, change it to shared (decl) in OMP_PARALLEL_CLAUSES. */ tree l = build_omp_clause (OMP_CLAUSE_LASTPRIVATE); OMP_CLAUSE_DECL (l) = OMP_CLAUSE_DECL (*c); OMP_CLAUSE_CHAIN (l) = clauses; clauses = l; OMP_CLAUSE_SET_CODE (*c, OMP_CLAUSE_SHARED); } } } OMP_FOR_CLAUSES (stmt) = clauses; } ret = stmt; } pop_scopes: while (for_block) { stmt = c_end_compound_stmt (TREE_VALUE (for_block), true); add_stmt (stmt); for_block = TREE_CHAIN (for_block); } return ret; } /* OpenMP 2.5: #pragma omp for for-clause[optseq] new-line for-loop */ #define OMP_FOR_CLAUSE_MASK \ ( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (1u << PRAGMA_OMP_CLAUSE_ORDERED) \ | (1u << PRAGMA_OMP_CLAUSE_SCHEDULE) \ | (1u << PRAGMA_OMP_CLAUSE_COLLAPSE) \ | (1u << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_for (c_parser *parser) { tree block, clauses, ret; clauses = c_parser_omp_all_clauses (parser, OMP_FOR_CLAUSE_MASK, "#pragma omp for"); block = c_begin_compound_stmt (true); ret = c_parser_omp_for_loop (parser, clauses, NULL); block = c_end_compound_stmt (block, true); add_stmt (block); return ret; } /* OpenMP 2.5: # pragma omp master new-line structured-block */ static tree c_parser_omp_master (c_parser *parser) { c_parser_skip_to_pragma_eol (parser); return c_finish_omp_master (c_parser_omp_structured_block (parser)); } /* OpenMP 2.5: # pragma omp ordered new-line structured-block */ static tree c_parser_omp_ordered (c_parser *parser) { c_parser_skip_to_pragma_eol (parser); return c_finish_omp_ordered (c_parser_omp_structured_block (parser)); } /* OpenMP 2.5: section-scope: { section-sequence } section-sequence: section-directive[opt] structured-block section-sequence section-directive structured-block */ static tree c_parser_omp_sections_scope (c_parser *parser) { tree stmt, substmt; bool error_suppress = false; location_t loc; if (!c_parser_require (parser, CPP_OPEN_BRACE, "expected %<{%>")) { /* Avoid skipping until the end of the block. */ parser->error = false; return NULL_TREE; } stmt = push_stmt_list (); loc = c_parser_peek_token (parser)->location; if (c_parser_peek_token (parser)->pragma_kind != PRAGMA_OMP_SECTION) { substmt = push_stmt_list (); while (1) { c_parser_statement (parser); if (c_parser_peek_token (parser)->pragma_kind == PRAGMA_OMP_SECTION) break; if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) break; if (c_parser_next_token_is (parser, CPP_EOF)) break; } substmt = pop_stmt_list (substmt); substmt = build1 (OMP_SECTION, void_type_node, substmt); SET_EXPR_LOCATION (substmt, loc); add_stmt (substmt); } while (1) { if (c_parser_next_token_is (parser, CPP_CLOSE_BRACE)) break; if (c_parser_next_token_is (parser, CPP_EOF)) break; loc = c_parser_peek_token (parser)->location; if (c_parser_peek_token (parser)->pragma_kind == PRAGMA_OMP_SECTION) { c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); error_suppress = false; } else if (!error_suppress) { error ("expected %<#pragma omp section%> or %<}%>"); error_suppress = true; } substmt = c_parser_omp_structured_block (parser); substmt = build1 (OMP_SECTION, void_type_node, substmt); SET_EXPR_LOCATION (substmt, loc); add_stmt (substmt); } c_parser_skip_until_found (parser, CPP_CLOSE_BRACE, "expected %<#pragma omp section%> or %<}%>"); substmt = pop_stmt_list (stmt); stmt = make_node (OMP_SECTIONS); TREE_TYPE (stmt) = void_type_node; OMP_SECTIONS_BODY (stmt) = substmt; return add_stmt (stmt); } /* OpenMP 2.5: # pragma omp sections sections-clause[optseq] newline sections-scope */ #define OMP_SECTIONS_CLAUSE_MASK \ ( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_LASTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (1u << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_sections (c_parser *parser) { tree block, clauses, ret; clauses = c_parser_omp_all_clauses (parser, OMP_SECTIONS_CLAUSE_MASK, "#pragma omp sections"); block = c_begin_compound_stmt (true); ret = c_parser_omp_sections_scope (parser); if (ret) OMP_SECTIONS_CLAUSES (ret) = clauses; block = c_end_compound_stmt (block, true); add_stmt (block); return ret; } /* OpenMP 2.5: # pragma parallel parallel-clause new-line # pragma parallel for parallel-for-clause new-line # pragma parallel sections parallel-sections-clause new-line */ #define OMP_PARALLEL_CLAUSE_MASK \ ( (1u << PRAGMA_OMP_CLAUSE_IF) \ | (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_DEFAULT) \ | (1u << PRAGMA_OMP_CLAUSE_SHARED) \ | (1u << PRAGMA_OMP_CLAUSE_COPYIN) \ | (1u << PRAGMA_OMP_CLAUSE_REDUCTION) \ | (1u << PRAGMA_OMP_CLAUSE_NUM_THREADS)) static tree c_parser_omp_parallel (c_parser *parser) { enum pragma_kind p_kind = PRAGMA_OMP_PARALLEL; const char *p_name = "#pragma omp parallel"; tree stmt, clauses, par_clause, ws_clause, block; unsigned int mask = OMP_PARALLEL_CLAUSE_MASK; if (c_parser_next_token_is_keyword (parser, RID_FOR)) { c_parser_consume_token (parser); p_kind = PRAGMA_OMP_PARALLEL_FOR; p_name = "#pragma omp parallel for"; mask |= OMP_FOR_CLAUSE_MASK; mask &= ~(1u << PRAGMA_OMP_CLAUSE_NOWAIT); } else if (c_parser_next_token_is (parser, CPP_NAME)) { const char *p = IDENTIFIER_POINTER (c_parser_peek_token (parser)->value); if (strcmp (p, "sections") == 0) { c_parser_consume_token (parser); p_kind = PRAGMA_OMP_PARALLEL_SECTIONS; p_name = "#pragma omp parallel sections"; mask |= OMP_SECTIONS_CLAUSE_MASK; mask &= ~(1u << PRAGMA_OMP_CLAUSE_NOWAIT); } } clauses = c_parser_omp_all_clauses (parser, mask, p_name); switch (p_kind) { case PRAGMA_OMP_PARALLEL: block = c_begin_omp_parallel (); c_parser_statement (parser); stmt = c_finish_omp_parallel (clauses, block); break; case PRAGMA_OMP_PARALLEL_FOR: block = c_begin_omp_parallel (); c_split_parallel_clauses (clauses, &par_clause, &ws_clause); c_parser_omp_for_loop (parser, ws_clause, &par_clause); stmt = c_finish_omp_parallel (par_clause, block); OMP_PARALLEL_COMBINED (stmt) = 1; break; case PRAGMA_OMP_PARALLEL_SECTIONS: block = c_begin_omp_parallel (); c_split_parallel_clauses (clauses, &par_clause, &ws_clause); stmt = c_parser_omp_sections_scope (parser); if (stmt) OMP_SECTIONS_CLAUSES (stmt) = ws_clause; stmt = c_finish_omp_parallel (par_clause, block); OMP_PARALLEL_COMBINED (stmt) = 1; break; default: gcc_unreachable (); } return stmt; } /* OpenMP 2.5: # pragma omp single single-clause[optseq] new-line structured-block */ #define OMP_SINGLE_CLAUSE_MASK \ ( (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_COPYPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_NOWAIT)) static tree c_parser_omp_single (c_parser *parser) { tree stmt = make_node (OMP_SINGLE); TREE_TYPE (stmt) = void_type_node; OMP_SINGLE_CLAUSES (stmt) = c_parser_omp_all_clauses (parser, OMP_SINGLE_CLAUSE_MASK, "#pragma omp single"); OMP_SINGLE_BODY (stmt) = c_parser_omp_structured_block (parser); return add_stmt (stmt); } /* OpenMP 3.0: # pragma omp task task-clause[optseq] new-line */ #define OMP_TASK_CLAUSE_MASK \ ( (1u << PRAGMA_OMP_CLAUSE_IF) \ | (1u << PRAGMA_OMP_CLAUSE_UNTIED) \ | (1u << PRAGMA_OMP_CLAUSE_DEFAULT) \ | (1u << PRAGMA_OMP_CLAUSE_PRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_FIRSTPRIVATE) \ | (1u << PRAGMA_OMP_CLAUSE_SHARED)) static tree c_parser_omp_task (c_parser *parser) { tree clauses, block; clauses = c_parser_omp_all_clauses (parser, OMP_TASK_CLAUSE_MASK, "#pragma omp task"); block = c_begin_omp_task (); c_parser_statement (parser); return c_finish_omp_task (clauses, block); } /* OpenMP 3.0: # pragma omp taskwait new-line */ static void c_parser_omp_taskwait (c_parser *parser) { c_parser_consume_pragma (parser); c_parser_skip_to_pragma_eol (parser); c_finish_omp_taskwait (); } /* Main entry point to parsing most OpenMP pragmas. */ static void c_parser_omp_construct (c_parser *parser) { enum pragma_kind p_kind; location_t loc; tree stmt; loc = c_parser_peek_token (parser)->location; p_kind = c_parser_peek_token (parser)->pragma_kind; c_parser_consume_pragma (parser); /* For all constructs below except #pragma omp atomic MUST_NOT_THROW catch handlers are needed when exceptions are enabled. */ if (p_kind != PRAGMA_OMP_ATOMIC) c_maybe_initialize_eh (); switch (p_kind) { case PRAGMA_OMP_ATOMIC: c_parser_omp_atomic (parser); return; case PRAGMA_OMP_CRITICAL: stmt = c_parser_omp_critical (parser); break; case PRAGMA_OMP_FOR: stmt = c_parser_omp_for (parser); break; case PRAGMA_OMP_MASTER: stmt = c_parser_omp_master (parser); break; case PRAGMA_OMP_ORDERED: stmt = c_parser_omp_ordered (parser); break; case PRAGMA_OMP_PARALLEL: stmt = c_parser_omp_parallel (parser); break; case PRAGMA_OMP_SECTIONS: stmt = c_parser_omp_sections (parser); break; case PRAGMA_OMP_SINGLE: stmt = c_parser_omp_single (parser); break; case PRAGMA_OMP_TASK: stmt = c_parser_omp_task (parser); break; default: gcc_unreachable (); } if (stmt) SET_EXPR_LOCATION (stmt, loc); } /* OpenMP 2.5: # pragma omp threadprivate (variable-list) */ static void c_parser_omp_threadprivate (c_parser *parser) { tree vars, t; c_parser_consume_pragma (parser); vars = c_parser_omp_var_list_parens (parser, 0, NULL); /* Mark every variable in VARS to be assigned thread local storage. */ for (t = vars; t; t = TREE_CHAIN (t)) { tree v = TREE_PURPOSE (t); /* If V had already been marked threadprivate, it doesn't matter whether it had been used prior to this point. */ if (TREE_USED (v) && !C_DECL_THREADPRIVATE_P (v)) error ("%qE declared %<threadprivate%> after first use", v); else if (! TREE_STATIC (v) && ! DECL_EXTERNAL (v)) error ("automatic variable %qE cannot be %<threadprivate%>", v); else if (! COMPLETE_TYPE_P (TREE_TYPE (v))) error ("%<threadprivate%> %qE has incomplete type", v); else { if (! DECL_THREAD_LOCAL_P (v)) { DECL_TLS_MODEL (v) = decl_default_tls_model (v); /* If rtl has been already set for this var, call make_decl_rtl once again, so that encode_section_info has a chance to look at the new decl flags. */ if (DECL_RTL_SET_P (v)) make_decl_rtl (v); } C_DECL_THREADPRIVATE_P (v) = 1; } } c_parser_skip_to_pragma_eol (parser); } /* Parse a single source file. */ void c_parse_file (void) { /* Use local storage to begin. If the first token is a pragma, parse it. If it is #pragma GCC pch_preprocess, then this will load a PCH file which will cause garbage collection. */ c_parser tparser; memset (&tparser, 0, sizeof tparser); the_parser = &tparser; if (c_parser_peek_token (&tparser)->pragma_kind == PRAGMA_GCC_PCH_PREPROCESS) c_parser_pragma_pch_preprocess (&tparser); the_parser = GGC_NEW (c_parser); *the_parser = tparser; c_parser_translation_unit (the_parser); the_parser = NULL; } #include "gt-c-parser.h"
connector_base.h
/* * connector_base.h * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef CONNECTOR_BASE_H #define CONNECTOR_BASE_H // Generated includes: #include "config.h" // C++ includes: #include <cstdlib> #include <vector> #include <deque> // Includes from libnestutil: #include "compose.hpp" // Includes from nestkernel: #include "common_synapse_properties.h" #include "connection_label.h" #include "connector_model.h" #include "event.h" #include "kernel_manager.h" #include "nest_datums.h" #include "nest_names.h" #include "node.h" #include "spikecounter.h" // Includes from sli: #include "dictutils.h" #ifdef USE_PMA #ifdef IS_K extern PaddedPMA poormansallocpool[]; #else extern PoorMansAllocator poormansallocpool; #ifdef _OPENMP #pragma omp threadprivate( poormansallocpool ) #endif #endif #endif template < typename Tnew, typename Told, typename C > inline Tnew* suicide_and_resurrect( Told* connector, C connection ) { #if defined _OPENMP && defined USE_PMA #ifdef IS_K Tnew* p = new ( poormansallocpool[ nest::kernel().vp_manager.get_thread_id() ].alloc( sizeof( Tnew ) ) ) Tnew( *connector, connection ); #else Tnew* p = new ( poormansallocpool.alloc( sizeof( Tnew ) ) ) Tnew( *connector, connection ); #endif connector->~Told(); #else Tnew* p = new Tnew( *connector, connection ); delete connector; // suicide #endif return p; } template < typename Tnew, typename Told > inline Tnew* suicide_and_resurrect( Told* connector, size_t i ) { #if defined _OPENMP && defined USE_PMA #ifdef IS_K Tnew* p = new ( poormansallocpool[ nest::kernel().vp_manager.get_thread_id() ].alloc( sizeof( Tnew ) ) ) Tnew( *connector, i ); #else Tnew* p = new ( poormansallocpool.alloc( sizeof( Tnew ) ) ) Tnew( *connector, i ); #endif connector->~Told(); #else Tnew* p = new Tnew( *connector, i ); delete connector; // suicide #endif return p; } template < typename Tnew, typename Told > inline void suicide( Told* connector ) { #ifdef USE_PMA connector->~Told(); #else delete connector; // suicide #endif } // when to truncate the recursive instantiation #define K_CUTOFF 3 namespace nest { // base clase to provide interface to decide // - homogeneous connector (containing =1 synapse type) // -- which synapse type stored (syn_id) // - heterogeneous connector (containing >1 synapse type) class ConnectorBase { public: ConnectorBase(); virtual void get_synapse_status( synindex syn_id, DictionaryDatum& d, port p, const thread tid ) const = 0; virtual void set_synapse_status( synindex syn_id, ConnectorModel& cm, const DictionaryDatum& d, port p ) = 0; virtual size_t get_num_connections() = 0; virtual size_t get_num_connections( synindex syn_id ) = 0; virtual size_t get_num_connections( size_t target_gid, size_t thrd, synindex syn_id ) = 0; virtual void get_connections( size_t source_gid, size_t thrd, synindex synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const = 0; virtual void get_connections( size_t source_gid, size_t target_gid, size_t thrd, size_t synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const = 0; virtual void get_target_gids( std::vector< size_t >& target_gids, size_t thrd, synindex synapse_id, std::string post_synaptic_element ) const = 0; virtual void send( Event& e, thread t, const std::vector< ConnectorModel* >& cm ) = 0; void send_weight_event( const CommonSynapseProperties& cp, const Event& e, const thread t ); virtual void trigger_update_weight( long vt_gid, thread t, const std::vector< spikecounter >& dopa_spikes, double t_trig, const std::vector< ConnectorModel* >& cm ) = 0; virtual void send_secondary( SecondaryEvent& e, thread t, const std::vector< ConnectorModel* >& cm ) = 0; // returns id of synapse type virtual synindex get_syn_id() const = 0; // returns true, if all synapse models are of same type virtual bool homogeneous_model() = 0; // destructor needed to delete connections virtual ~ConnectorBase(){}; double get_t_lastspike() const { return t_lastspike_; } void set_t_lastspike( const double t_lastspike ) { t_lastspike_ = t_lastspike; } private: double t_lastspike_; }; inline void ConnectorBase::send_weight_event( const CommonSynapseProperties& cp, const Event& e, const thread t ) { if ( cp.get_weight_recorder() ) { // Create new event to record the weight and copy relevant content. WeightRecorderEvent wr_e; wr_e.set_port( e.get_port() ); wr_e.set_rport( e.get_rport() ); wr_e.set_stamp( e.get_stamp() ); wr_e.set_sender( e.get_sender() ); wr_e.set_sender_gid( e.get_sender_gid() ); wr_e.set_weight( e.get_weight() ); wr_e.set_delay( e.get_delay() ); // set weight_recorder as receiver wr_e.set_receiver( *cp.get_weight_recorder()->get_thread_sibling( t ) ); // but the gid of the postsynaptic node as receiver gid wr_e.set_receiver_gid( e.get_receiver().get_gid() ); wr_e(); } } // vector with 1 vtable overhead // vector like base class to abstract away the template argument K // provides interface like vector i.p. (suicidal) push_back template < typename ConnectionT > class vector_like : public ConnectorBase { public: virtual ConnectorBase& push_back( const ConnectionT& c ) = 0; virtual ConnectorBase& erase( size_t i ) = 0; virtual size_t size() = 0; virtual ConnectionT& at( size_t i ) = 0; void send_secondary( SecondaryEvent&, thread, const std::vector< ConnectorModel* >& ) { assert( false ); // should not be called, only needed for heterogeneous connectors }; }; // homogeneous connector containing K entries template < size_t K, typename ConnectionT > class Connector : public vector_like< ConnectionT > { ConnectionT C_[ K ]; public: Connector( const Connector< K - 1, ConnectionT >& Cm1, const ConnectionT& c ) { for ( size_t i = 0; i < K - 1; i++ ) { C_[ i ] = Cm1.get_C()[ i ]; } C_[ K - 1 ] = c; } /** * Creates a new connector and remove the ith connection. To do so, the * contents of the original connector are copied into the new one. The copy is * performed in two parts, first up to the specified index and then the rest * of the connections after the specified index in order to exclude the ith * connection from the copy. As a result, returns a connector with size K from * a connector of size K+1. * * @param Cm1 the original connector * @param i the index of the connection to be deleted */ Connector( const Connector< K + 1, ConnectionT >& Cm1, size_t i ) { assert( i < K && i >= 0 ); for ( size_t k = 0; k < i; k++ ) { C_[ k ] = Cm1.get_C()[ k ]; } for ( size_t k = i + 1; k < K + 1; k++ ) { C_[ k - 1 ] = Cm1.get_C()[ k ]; } } ~Connector() { } void get_synapse_status( synindex syn_id, DictionaryDatum& d, port p, const thread tid ) const { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( p >= 0 && static_cast< size_t >( p ) < K ); C_[ p ].get_status( d ); // set target gid here, where tid is available def< long >( d, names::target, C_[ p ].get_target( tid )->get_gid() ); } } void set_synapse_status( synindex syn_id, ConnectorModel& cm, const DictionaryDatum& d, port p ) { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( p >= 0 && static_cast< size_t >( p ) < K ); C_[ p ].set_status( d, static_cast< GenericConnectorModel< ConnectionT >& >( cm ) ); } } size_t get_num_connections() { return K; } size_t get_num_connections( synindex syn_id ) { if ( syn_id == get_syn_id() ) { return K; } else { return 0; } } /** * Returns the number of connections that this connector is holding for * a given target and synapse type. * @param target_gid The GID of the target of the searched connections * @param thrd The thread id of the target * @param syn_id Id of the synapse of the searched connections * @return */ size_t get_num_connections( size_t target_gid, size_t thrd, synindex syn_id ) { size_t num_connections = 0; if ( syn_id == get_syn_id() ) { for ( size_t i = 0; i < K; i++ ) { if ( C_[ i ].get_target( thrd )->get_gid() == target_gid ) { num_connections++; } } } return num_connections; } ConnectorBase& push_back( const ConnectionT& c ) { return *suicide_and_resurrect< Connector< K + 1, ConnectionT > >( this, c ); } /** * Delete a single connection from the connector * @param i the index of the connection to be erased * @return A connector of size K-1 */ ConnectorBase& erase( size_t i ) { // try to cast the connector one size shorter return *suicide_and_resurrect< Connector< K - 1, ConnectionT > >( this, i ); } /** * Getter for the size of the Connection array * @return The number of connections which this Connector currently holds */ size_t size() { return K; } /** * Operator to obtain a connection at a given index from the Connector, * in the same manner as it would work with an array. * @param i the index of the connection to be retrieved. * @return The connection stored at position i. */ ConnectionT& at( size_t i ) { if ( i >= K || i < 0 ) { throw std::out_of_range( String::compose( "Invalid attempt to access a connection: index %1 out of range.", i ) ); } return C_[ i ]; } void get_connections( size_t source_gid, size_t thrd, synindex synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { for ( size_t i = 0; i < K; i++ ) { if ( get_syn_id() == synapse_id ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ i ].get_label() == synapse_label ) { conns.push_back( ConnectionID( source_gid, C_[ i ].get_target( thrd )->get_gid(), thrd, synapse_id, i ) ); } } } } void get_connections( size_t source_gid, size_t target_gid, size_t thrd, size_t synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { for ( size_t i = 0; i < K; i++ ) { if ( get_syn_id() == synapse_id ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ i ].get_label() == synapse_label ) { if ( C_[ i ].get_target( thrd )->get_gid() == target_gid ) { conns.push_back( ConnectionID( source_gid, target_gid, thrd, synapse_id, i ) ); } } } } } /** * Return the GIDs of the target nodes in a given thread, for all connections * on this Connector which match a defined synapse_id. * @param target_gids Vector to store the GIDs of the target nodes * @param thrd Thread where targets are being looked for * @param synapse_id Synapse type */ void get_target_gids( std::vector< size_t >& target_gids, const size_t thrd, const synindex synapse_id, const std::string post_synaptic_element ) const { if ( get_syn_id() == synapse_id ) { for ( size_t i = 0; i < K; ++i ) { if ( C_[ i ].get_target( thrd )->get_synaptic_elements( post_synaptic_element ) != 0.0 ) { target_gids.push_back( C_[ i ].get_target( thrd )->get_gid() ); } } } } void send( Event& e, thread t, const std::vector< ConnectorModel* >& cm ) { synindex syn_id = C_[ 0 ].get_syn_id(); typename ConnectionT::CommonPropertiesType const& cp = static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties(); for ( size_t i = 0; i < K; i++ ) { e.set_port( i ); C_[ i ].send( e, t, ConnectorBase::get_t_lastspike(), cp ); ConnectorBase::send_weight_event( cp, e, t ); } ConnectorBase::set_t_lastspike( e.get_stamp().get_ms() ); } void trigger_update_weight( long vt_gid, thread t, const std::vector< spikecounter >& dopa_spikes, double t_trig, const std::vector< ConnectorModel* >& cm ) { synindex syn_id = C_[ 0 ].get_syn_id(); for ( size_t i = 0; i < K; i++ ) { if ( static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() .get_vt_gid() == vt_gid ) { C_[ i ].trigger_update_weight( t, dopa_spikes, t_trig, static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() ); } } } synindex get_syn_id() const { // return syn_id_; return C_[ 0 ].get_syn_id(); } const ConnectionT* get_C() const { return C_; } bool homogeneous_model() { return true; } }; // homogeneous connector containing 1 entry (specialization to define // constructor) template < typename ConnectionT > class Connector< 1, ConnectionT > : public vector_like< ConnectionT > { ConnectionT C_[ 1 ]; public: Connector( const ConnectionT& c ) { C_[ 0 ] = c; }; /** * Returns a new Connector of size 1 after deleting one of the * connections. * @param Cm1 Original Connector of size 2 * @param i Index of the connection to be erased */ Connector( const Connector< 2, ConnectionT >& Cm1, size_t i ) { assert( i < 2 && i >= 0 ); if ( i == 0 ) { C_[ 0 ] = Cm1.get_C()[ 1 ]; } if ( i == 1 ) { C_[ 0 ] = Cm1.get_C()[ 0 ]; } } ~Connector() { } void get_synapse_status( synindex syn_id, DictionaryDatum& d, port p, const thread tid ) const { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( static_cast< size_t >( p ) == 0 ); C_[ 0 ].get_status( d ); // set target gid here, where tid is available def< long >( d, names::target, C_[ 0 ].get_target( tid )->get_gid() ); } } void set_synapse_status( synindex syn_id, ConnectorModel& cm, const DictionaryDatum& d, port p ) { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( static_cast< size_t >( p ) == 0 ); C_[ 0 ].set_status( d, static_cast< GenericConnectorModel< ConnectionT >& >( cm ) ); } } size_t get_num_connections() { return 1; } size_t get_num_connections( synindex syn_id ) { if ( syn_id == get_syn_id() ) { return 1; } else { return 0; } } size_t get_num_connections( size_t target_gid, size_t thrd, synindex syn_id ) { size_t num_connections = 0; if ( syn_id == get_syn_id() ) { if ( C_[ 0 ].get_target( thrd )->get_gid() == target_gid ) { num_connections = 1; } } return num_connections; } ConnectorBase& push_back( const ConnectionT& c ) { return *suicide_and_resurrect< Connector< 2, ConnectionT > >( this, c ); } ConnectorBase& erase( size_t ) { // erase() must never be called on a connector with just as single synapse. // Delete the connector instead. assert( false ); std::abort(); // we must not pass this point even if compiled with -DNDEBUG return *this; // dummy value, will never be returned } size_t size() { return 1; } ConnectionT& at( size_t i ) { if ( i != 0 ) { throw std::out_of_range( String::compose( "Invalid attempt to access a connection: index %1 out of range.", i ) ); } return C_[ i ]; } void get_connections( size_t source_gid, size_t thrd, synindex synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { if ( get_syn_id() == synapse_id ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ 0 ].get_label() == synapse_label ) { conns.push_back( ConnectionID( source_gid, C_[ 0 ].get_target( thrd )->get_gid(), thrd, synapse_id, 0 ) ); } } } void get_connections( size_t source_gid, size_t target_gid, size_t thrd, size_t synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { if ( get_syn_id() == synapse_id ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ 0 ].get_label() == synapse_label ) { if ( C_[ 0 ].get_target( thrd )->get_gid() == target_gid ) { conns.push_back( ConnectionID( source_gid, target_gid, thrd, synapse_id, 0 ) ); } } } } void get_target_gids( std::vector< size_t >& target_gids, const size_t thrd, const synindex synapse_id, const std::string post_synaptic_element ) const { if ( get_syn_id() == synapse_id ) { if ( C_[ 0 ].get_target( thrd )->get_synaptic_elements( post_synaptic_element ) != 0.0 ) { target_gids.push_back( C_[ 0 ].get_target( thrd )->get_gid() ); } } } void send( Event& e, thread t, const std::vector< ConnectorModel* >& cm ) { typename ConnectionT::CommonPropertiesType const& cp = static_cast< GenericConnectorModel< ConnectionT >* >( cm[ C_[ 0 ].get_syn_id() ] )->get_common_properties(); e.set_port( 0 ); C_[ 0 ].send( e, t, ConnectorBase::get_t_lastspike(), cp ); ConnectorBase::set_t_lastspike( e.get_stamp().get_ms() ); ConnectorBase::send_weight_event( cp, e, t ); } void trigger_update_weight( long vt_gid, thread t, const std::vector< spikecounter >& dopa_spikes, double t_trig, const std::vector< ConnectorModel* >& cm ) { synindex syn_id = C_[ 0 ].get_syn_id(); if ( static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() .get_vt_gid() == vt_gid ) { C_[ 0 ].trigger_update_weight( t, dopa_spikes, t_trig, static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() ); } } synindex get_syn_id() const { return C_[ 0 ].get_syn_id(); } const ConnectionT* get_C() const { return C_; } bool homogeneous_model() { return true; } }; // homogeneous connector containing >=K_CUTOFF entries // specialization to define recursion termination for push_back // internally use a normal vector to store elements template < typename ConnectionT > class Connector< K_CUTOFF, ConnectionT > : public vector_like< ConnectionT > { std::vector< ConnectionT > C_; public: Connector( const Connector< K_CUTOFF - 1, ConnectionT >& C, const ConnectionT& c ) : C_( K_CUTOFF ) //, syn_id_(C.get_syn_id()) { for ( size_t i = 0; i < K_CUTOFF - 1; i++ ) { C_[ i ] = C.get_C()[ i ]; } C_[ K_CUTOFF - 1 ] = c; }; /** * Creates a new connector and removes the ith connection. To do so, the * contents of the original connector are copied into the new one. The copy is * performed in two parts, first up to the specified index and then the rest * of the connections after the specified index in order to exclude the ith * connection from the copy. As a result, returns a connector with size * K_CUTOFF-1 from a connector of size K_CUTOFF. * * @param Cm1 Original connector of size K_CUTOFF * @param i The index of the connection to be deleted. */ Connector( const Connector< K_CUTOFF, ConnectionT >& Cm1, size_t i ) { assert( i < Cm1.get_C().size() && i >= 0 ); for ( size_t k = 0; k < i; k++ ) { C_[ k ] = Cm1.get_C()[ k ]; } for ( size_t k = i + 1; k < K_CUTOFF; k++ ) { C_[ k ] = Cm1.get_C()[ k + 1 ]; } } ~Connector() { } void get_synapse_status( synindex syn_id, DictionaryDatum& d, port p, const thread tid ) const { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( p >= 0 && static_cast< size_t >( p ) < C_.size() ); C_[ p ].get_status( d ); // set target gid here, where tid is available def< long >( d, names::target, C_[ p ].get_target( tid )->get_gid() ); } } void set_synapse_status( synindex syn_id, ConnectorModel& cm, const DictionaryDatum& d, port p ) { if ( syn_id == C_[ 0 ].get_syn_id() ) { assert( p >= 0 && static_cast< size_t >( p ) < C_.size() ); C_[ p ].set_status( d, static_cast< GenericConnectorModel< ConnectionT >& >( cm ) ); } } size_t get_num_connections() { return C_.size(); } size_t get_num_connections( synindex syn_id ) { if ( syn_id == get_syn_id() ) { return C_.size(); } else { return 0; } } size_t get_num_connections( size_t target_gid, size_t thrd, synindex syn_id ) { typename std::vector< ConnectionT >::iterator C_it; size_t num_connections = 0; if ( syn_id == get_syn_id() ) { for ( C_it = C_.begin(); C_it != C_.end(); C_it++ ) { if ( ( *C_it ).get_target( thrd )->get_gid() == target_gid ) { num_connections++; } } } return num_connections; } ConnectorBase& push_back( const ConnectionT& c ) { C_.push_back( c ); return *this; } ConnectorBase& erase( size_t i ) { typename std::vector< ConnectionT >::iterator it; it = C_.begin() + i; C_.erase( it ); return *this; } size_t size() { return C_.size(); } ConnectionT& at( size_t i ) { if ( i >= C_.size() || i < 0 ) { throw std::out_of_range( String::compose( "Invalid attempt to access a connection: index %1 out of range.", i ) ); } return C_[ i ]; } void get_connections( size_t source_gid, size_t thrd, synindex synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { for ( size_t i = 0; i < C_.size(); i++ ) { if ( get_syn_id() == synapse_id ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ i ].get_label() == synapse_label ) { conns.push_back( ConnectionID( source_gid, C_[ i ].get_target( thrd )->get_gid(), thrd, synapse_id, i ) ); } } } } void get_connections( size_t source_gid, size_t target_gid, size_t thrd, size_t synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { if ( get_syn_id() == synapse_id ) { for ( size_t i = 0; i < C_.size(); i++ ) { if ( synapse_label == UNLABELED_CONNECTION || C_[ i ].get_label() == synapse_label ) { if ( C_[ i ].get_target( thrd )->get_gid() == target_gid ) { conns.push_back( ConnectionID( source_gid, target_gid, thrd, synapse_id, i ) ); } } } } } void get_target_gids( std::vector< size_t >& target_gids, const size_t thrd, const synindex synapse_id, const std::string post_synaptic_element ) const { typename std::vector< ConnectionT >::const_iterator C_it; if ( get_syn_id() == synapse_id ) { for ( C_it = C_.begin(); C_it != C_.end(); ++C_it ) { if ( ( *C_it ).get_target( thrd )->get_synaptic_elements( post_synaptic_element ) != 0.0 ) { target_gids.push_back( ( *C_it ).get_target( thrd )->get_gid() ); } } } } void send( Event& e, thread t, const std::vector< ConnectorModel* >& cm ) { synindex syn_id = C_[ 0 ].get_syn_id(); typename ConnectionT::CommonPropertiesType const& cp = static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties(); for ( size_t i = 0; i < C_.size(); i++ ) { e.set_port( i ); C_[ i ].send( e, t, ConnectorBase::get_t_lastspike(), cp ); ConnectorBase::send_weight_event( cp, e, t ); } ConnectorBase::set_t_lastspike( e.get_stamp().get_ms() ); } void trigger_update_weight( long vt_gid, thread t, const std::vector< spikecounter >& dopa_spikes, double t_trig, const std::vector< ConnectorModel* >& cm ) { synindex syn_id = C_[ 0 ].get_syn_id(); for ( size_t i = 0; i < C_.size(); i++ ) { if ( static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() .get_vt_gid() == vt_gid ) { C_[ i ].trigger_update_weight( t, dopa_spikes, t_trig, static_cast< GenericConnectorModel< ConnectionT >* >( cm[ syn_id ] ) ->get_common_properties() ); } } } synindex get_syn_id() const { return C_[ 0 ].get_syn_id(); } bool homogeneous_model() { return true; } }; // heterogeneous connector containing different types of synapses // each entry is of type connectorbase, so in principle the structure could be // nested indefinitely // the logic in add_connection, however, assumes that these entries are // homogeneous connectors class HetConnector : public std::vector< ConnectorBase* >, public ConnectorBase { private: synindex primary_end_; // index of first secondary connector contained in the // heterogeneous connector public: HetConnector() : std::vector< ConnectorBase* >() , primary_end_( 0 ) { } virtual ~HetConnector() { for ( size_t i = 0; i < size(); i++ ) { #ifdef USE_PMA at( i )->~ConnectorBase(); #else delete at( i ); #endif } } void get_synapse_status( synindex syn_id, DictionaryDatum& d, port p, const thread tid ) const { for ( size_t i = 0; i < size(); i++ ) { at( i )->get_synapse_status( syn_id, d, p, tid ); } } void set_synapse_status( synindex syn_id, ConnectorModel& cm, const DictionaryDatum& d, port p ) { for ( size_t i = 0; i < size(); i++ ) { at( i )->set_synapse_status( syn_id, cm, d, p ); } } size_t get_num_connections() { size_t n = 0; for ( size_t i = 0; i < size(); i++ ) { n += at( i )->get_num_connections(); } return n; } size_t get_num_connections( synindex syn_id ) { for ( size_t i = 0; i < size(); i++ ) { if ( syn_id == at( i )->get_syn_id() ) { return at( i )->get_num_connections(); } } return 0; } size_t get_num_connections( size_t target_gid, size_t thrd, synindex syn_id ) { for ( size_t i = 0; i < size(); i++ ) { if ( syn_id == at( i )->get_syn_id() ) { return at( i )->get_num_connections( target_gid, thrd, syn_id ); } } return 0; } void get_connections( size_t source_gid, size_t thrd, synindex synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { for ( size_t i = 0; i < size(); i++ ) { at( i )->get_connections( source_gid, thrd, synapse_id, synapse_label, conns ); } } void get_connections( size_t source_gid, size_t target_gid, size_t thrd, size_t synapse_id, long synapse_label, std::deque< ConnectionID >& conns ) const { for ( size_t i = 0; i < size(); i++ ) { at( i )->get_connections( source_gid, target_gid, thrd, synapse_id, synapse_label, conns ); } } void get_target_gids( std::vector< size_t >& target_gids, const size_t thrd, const synindex synapse_id, const std::string post_synaptic_element ) const { for ( size_t i = 0; i < size(); ++i ) { if ( synapse_id == at( i )->get_syn_id() ) { at( i )->get_target_gids( target_gids, thrd, synapse_id, post_synaptic_element ); } } } void send( Event& e, thread t, const std::vector< ConnectorModel* >& cm ) { // for all primary connections delegate send to homogeneous connectors for ( size_t i = 0; i < primary_end_; i++ ) { at( i )->send( e, t, cm ); } } void trigger_update_weight( long vt_gid, thread t, const std::vector< spikecounter >& dopa_spikes, double t_trig, const std::vector< ConnectorModel* >& cm ) { for ( size_t i = 0; i < size(); i++ ) { at( i )->trigger_update_weight( vt_gid, t, dopa_spikes, t_trig, cm ); } } void send_secondary( SecondaryEvent& e, thread t, const std::vector< ConnectorModel* >& cm ) { // for all secondary connections delegate send to the matching homogeneous // connectors only for ( size_t i = primary_end_; i < size(); i++ ) { if ( e.supports_syn_id( at( i )->get_syn_id() ) ) { at( i )->send( e, t, cm ); } } } // returns id of synapse type synindex get_syn_id() const { return invalid_synindex; } // returns true, if all synapse models are of same type bool homogeneous_model() { return false; } void add_connector( bool is_primary, ConnectorBase* conn ) { if ( is_primary ) { // if empty, insert (begin(), conn) inserts into the first position insert( begin() + primary_end_, conn ); ++primary_end_; } else { push_back( conn ); } } void reduce_primary() { --primary_end_; } }; } // of namespace nest #endif
GB_unaryop__lnot_int32_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int32_int32 // op(A') function: GB_tran__lnot_int32_int32 // C type: int32_t // A type: int32_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int32_int32 ( int32_t *Cx, // Cx and Ax may be aliased int32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int32_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
vec_add.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define N (30) int main(int argc, char *argv[]) { int nthreads, tid, idx; float a[N], b[N], c[N]; nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); // init #pragma omp parallel for for(idx=0; idx<N; ++idx) { a[idx] = b[idx] = 1.0; } // vec add #pragma omp parallel for for(idx=0; idx<N; ++idx) { c[idx] = a[idx] + b[idx]; tid = omp_get_thread_num(); printf("Thread %2d: c[%2d]=%.2f\n", tid, idx, c[idx]); } return 0; }
GB_unaryop__lnot_uint8_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint8_fp32 // op(A') function: GB_tran__lnot_uint8_fp32 // C type: uint8_t // A type: float // cast: uint8_t cij ; GB_CAST_UNSIGNED(cij,aij,8) // unaryop: cij = !(aij != 0) #define GB_ATYPE \ float #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ uint8_t z ; GB_CAST_UNSIGNED(z,x,8) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT8 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint8_fp32 ( uint8_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint8_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
qops.c
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <omp.h> #include "platform.h" #include "qstate.h" #include "arraylist.h" #include "qgate.h" #include "qops.h" REAL_TYPE get_global_phase(struct state_vector *state) { NATURAL_TYPE i; REAL_TYPE phase; COMPLEX_TYPE val; if (state->fcarg_init) { return state->fcarg; } phase = 0.0; for (i = 0; i < state->size; i++) { val = state_get(state, i); if (RE(val) != 0. || IM(val) != 0.) { if (IM(val) != 0.) { phase = ARG(val); } break; } } state->fcarg = phase; state->fcarg_init = 1; return phase; } REAL_TYPE probability(struct state_vector *state, unsigned int target_id) { NATURAL_TYPE i; REAL_TYPE value; COMPLEX_TYPE val; value = 0; #pragma omp parallel for reduction (+:value) \ default (none) \ shared (state, target_id) \ private (i, val) for (i = 0; i < state->size; i++) { if ((i & (NATURAL_ONE << target_id)) != 0) { val = state_get(state, i); value += RE(val) * RE(val) + IM(val) * IM(val); } } return value; } unsigned char join(struct state_vector *r, struct state_vector *s1, struct state_vector *s2) { NATURAL_TYPE i, j, new_index; COMPLEX_TYPE o1, o2; unsigned char exit_code; exit_code = state_init(r, s1->num_qubits + s2->num_qubits, 0); if (exit_code != 0) { return exit_code; } #pragma omp parallel for default(none) \ shared (r, s1, s2, exit_code) \ private (i, j, o1, o2, new_index) for (i = 0; i < s1->size; i++) { o1 = state_get(s1, i); for (j = 0; j < s2->size; j++) { new_index = i * s2->size + j; o2 = state_get(s2, j); state_set(r, new_index, complex_mult(o1, o2)); } } return 0; } unsigned char measure(struct state_vector *state, _Bool *result, unsigned int target, struct state_vector *new_state, REAL_TYPE roll) { NATURAL_TYPE i; REAL_TYPE sum; unsigned char exit_code; sum = probability(state, target); *result = sum > roll; exit_code = collapse(state, target, *result, new_state); return exit_code; } unsigned char collapse(struct state_vector *state, unsigned int target_id, _Bool value, struct state_vector *new_state) { unsigned char exit_code; NATURAL_TYPE i, j, count, step; _Bool toggle; REAL_TYPE norm_const; COMPLEX_TYPE aux; if (state->num_qubits == 1) { // state_clear(state); new_state->vector = NULL; new_state->num_qubits = 0; return 0; } /* new_state = MALLOC_TYPE(1, struct state_vector); if (new_state == NULL) { return 5; } */ exit_code = state_init(new_state, state->num_qubits - 1, 0); if (exit_code != 0) { free(new_state); return exit_code; } norm_const = 0; toggle = 0; count = 0; step = NATURAL_ONE << target_id; j = 0; for (i = 0; i < state->size; i++) { if (toggle == value) { aux = state_get(state, i); state_set(new_state, j, aux); norm_const += pow(RE(aux), 2) + pow(IM(aux), 2); j++; } count++; if (count == step) { count = 0; toggle = !toggle; } } new_state->norm_const = sqrt(norm_const); return 0; } unsigned char apply_gate(struct state_vector *state, struct qgate *gate, unsigned int *targets, unsigned int num_targets, unsigned int *controls, unsigned int num_controls, unsigned int *anticontrols, unsigned int num_anticontrols, struct state_vector *new_state) { struct array_list_e *not_copy; REAL_TYPE norm_const; unsigned char exit_code; not_copy = MALLOC_TYPE(1, struct array_list_e); if (not_copy == NULL) { return 11; } exit_code = alist_init(not_copy, state->size >> (num_controls + num_anticontrols)); if (exit_code != 0) { free(not_copy); return exit_code; } if (new_state == NULL) { alist_clear(not_copy); free(not_copy); return 10; } exit_code = state_init(new_state, state->num_qubits, 0); // 0 -> OK // 1 -> Error initializing chunk // 2 -> Error allocating chunk // 3 -> Error setting values (should never happens since init = 0) // 4 -> Error allocating state if (exit_code != 0) { alist_clear(not_copy); free(not_copy); free(new_state); return exit_code; } norm_const = 0; exit_code = copy_and_index(state, new_state, controls, num_controls, anticontrols, num_anticontrols, &norm_const, not_copy); if (exit_code == 0) { exit_code = calculate_empty(state, gate, targets, num_targets, controls, num_controls, anticontrols, num_anticontrols, new_state, not_copy, &norm_const); if (exit_code == 0) { new_state->norm_const = sqrt(norm_const); } else { exit_code = 5; } } else { exit_code = 6; } alist_clear(not_copy); free(not_copy); return exit_code; } unsigned char copy_and_index(struct state_vector *state, struct state_vector *new_state, unsigned int *controls, unsigned int num_controls, unsigned int *anticontrols, unsigned int num_anticontrols, REAL_TYPE *norm_const, struct array_list_e *not_copy) { NATURAL_TYPE i, count; unsigned int j; REAL_TYPE aux_const; COMPLEX_TYPE aux; unsigned char copy_only; aux_const = 0; count = 0; #pragma omp parallel for reduction (+:aux_const) \ default(none) \ shared (state, not_copy, new_state, \ controls, num_controls, \ anticontrols, num_anticontrols, \ norm_const, count) \ private (copy_only, i, j, aux) for (i = 0; i < state->size; i++) { // If there has been any error in this thread, we skip copy_only = 0; for (j = 0; j < num_controls; j++) { /* If any control bit is set to 0 we set copy_only to true */ if ((i & (NATURAL_ONE << controls[j])) == 0) { copy_only = 1; break; } } if (!copy_only) { for (j = 0; j < num_anticontrols; j++) { /* If any anticontrol bit is not set to 0 we set copy_only to true */ if ((i & (NATURAL_ONE << anticontrols[j])) != 0) { copy_only = 1; break; } } } // If copy_only is true it means that we just need to copy the old state element if (copy_only) { aux = state_get(state, i); aux_const += pow(RE(aux), 2) + pow(IM(aux), 2); state_set(new_state, i, aux); } else { #pragma omp critical (add_to_not_copy) { alist_set(not_copy, count, i); count++; } } } *norm_const = aux_const; return 0; } unsigned char calculate_empty(struct state_vector *state, struct qgate *gate, unsigned int *targets, unsigned int num_targets, unsigned int *controls, unsigned int num_controls, unsigned int *anticontrols, unsigned int num_anticontrols, struct state_vector *new_state, struct array_list_e *not_copy, REAL_TYPE *norm_const) { NATURAL_TYPE i, reg_index, curr_id; COMPLEX_TYPE sum; REAL_TYPE aux_const; unsigned char aux_code; unsigned int j, k, row; aux_code = 0; aux_const = 0; reg_index = 0; curr_id = 0; // We can calculate each element of the new state separately #pragma omp parallel for reduction (+:aux_const) \ default(none) \ shared (state, not_copy, new_state, gate, \ targets, num_targets, \ controls, num_controls, \ anticontrols, num_anticontrols, \ norm_const) \ private (curr_id, sum, row, reg_index, i, j, k) for (i = 0; i < not_copy->size; i++) { // If there has been any error in this thread, we skip curr_id = alist_get(not_copy, i); reg_index = curr_id; sum = complex_init(0, 0); // We have gate->size elements to add in sum for (j = 0; j < gate->size; j++) { // We get the value of each target qubit id on the current new state element // and we store it in rowbits following the same order as the one in targets row = 0; for (k = 0; k < num_targets; k++) { row += ((curr_id & (NATURAL_ONE << targets[k])) != 0) << k; } for (k = 0; k < gate->num_qubits; k++) { // We check the value of the kth bit of j // and set the value of the kth target bit to it if ((j & (NATURAL_ONE << k)) != 0) { reg_index |= NATURAL_ONE << targets[k]; } else { reg_index &= ~(NATURAL_ONE << targets[k]); } } sum = complex_sum(sum, complex_mult(state_get(state, reg_index), gate->matrix[row][j])); } aux_const += pow(RE(sum), 2) + pow(IM(sum), 2); // printf("[DEBUG: %i] -> new_state[%lld]\n", omp_get_thread_num(), curr_id); state_set(new_state, curr_id, sum); } *norm_const += aux_const; return aux_code; } #ifndef _MSC_VER __attribute__ ((const)) #endif COMPLEX_TYPE _densityFun(NATURAL_TYPE i, NATURAL_TYPE j, #ifndef _MSC_VER NATURAL_TYPE unused1 __attribute__((unused)), NATURAL_TYPE unused2 __attribute__((unused)), #else NATURAL_TYPE unused1, NATURAL_TYPE unused2, #endif void *rawstate) { struct state_vector *state = (struct state_vector*) rawstate; COMPLEX_TYPE elem_i, elem_j, result; elem_i = state_get(state, i); elem_j = state_get(state, j); result = complex_mult(elem_i, conj(elem_j)); return result; } FunctionalMatrix* densityMat(struct state_vector *state) { FunctionalMatrix *dm = NULL; if (state != NULL) { dm = new_FunctionalMatrix(state->size, state->size, &_densityFun, state); } return dm; }
GB_binop__isne_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_03__isne_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_uint16) // A*D function (colscale): GB (_AxD__isne_uint16) // D*A function (rowscale): GB (_DxB__isne_uint16) // C+=B function (dense accum): GB (_Cdense_accumB__isne_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__isne_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_uint16) // C=scalar+B GB (_bind1st__isne_uint16) // C=scalar+B' GB (_bind1st_tran__isne_uint16) // C=A+scalar GB (_bind2nd__isne_uint16) // C=A'+scalar GB (_bind2nd_tran__isne_uint16) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_UINT16 || GxB_NO_ISNE_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isne_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_uint16) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_uint16) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__isne_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__isne_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = Bx [p] ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = Ax [p] ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
C_pp.c
// this is autogenerated file, do not edit it. #include "ficus/ficus.h" struct _fx_N14K_form__ktyp_t_data_t; static void _fx_free_N14K_form__ktyp_t(struct _fx_N14K_form__ktyp_t_data_t** dst); struct _fx_N14C_form__ctyp_t_data_t; static void _fx_free_N14C_form__ctyp_t(struct _fx_N14C_form__ctyp_t_data_t** dst); struct _fx_N14C_form__cexp_t_data_t; static void _fx_free_N14C_form__cexp_t(struct _fx_N14C_form__cexp_t_data_t** dst); struct _fx_N15C_form__cstmt_t_data_t; static void _fx_free_N15C_form__cstmt_t(struct _fx_N15C_form__cstmt_t_data_t** dst); typedef struct _fx_LS_data_t { int_ rc; struct _fx_LS_data_t* tl; fx_str_t hd; } _fx_LS_data_t, *_fx_LS; typedef struct _fx_N17Options__optval_t { int tag; union { bool OptBool; int_ OptInt; fx_str_t OptString; } u; } _fx_N17Options__optval_t; typedef struct _fx_T2SN17Options__optval_t { fx_str_t t0; struct _fx_N17Options__optval_t t1; } _fx_T2SN17Options__optval_t; typedef struct _fx_LT2SN17Options__optval_t_data_t { int_ rc; struct _fx_LT2SN17Options__optval_t_data_t* tl; struct _fx_T2SN17Options__optval_t hd; } _fx_LT2SN17Options__optval_t_data_t, *_fx_LT2SN17Options__optval_t; typedef struct _fx_R18Options__options_t { struct _fx_LS_data_t* app_args; fx_str_t app_filename; bool arch64; bool force_rebuild; fx_str_t build_dir; fx_str_t build_rootdir; fx_str_t cflags; fx_str_t clibs; bool compile_by_cpp; fx_str_t filename; bool gen_c; struct _fx_LS_data_t* include_path; bool debug; struct _fx_LT2SN17Options__optval_t_data_t* defines; int_ optim_iters; int_ inline_thresh; bool enable_openmp; bool relax; bool use_preamble; bool make_app; int_ optimize_level; fx_str_t output_name; bool print_ast0; bool print_ast; bool print_k0; bool print_k; bool print_tokens; bool run_app; bool verbose; bool W_unused; } _fx_R18Options__options_t; typedef struct _fx_Ta2i { int_ t0; int_ t1; } _fx_Ta2i; typedef struct _fx_T2Ta2iS { struct _fx_Ta2i t0; fx_str_t t1; } _fx_T2Ta2iS; typedef struct _fx_R9Ast__id_t { int_ m; int_ i; int_ j; } _fx_R9Ast__id_t; typedef struct _fx_R10Ast__loc_t { int_ m_idx; int_ line0; int_ col0; int_ line1; int_ col1; } _fx_R10Ast__loc_t; typedef struct _fx_T2R9Ast__id_ti { struct _fx_R9Ast__id_t t0; int_ t1; } _fx_T2R9Ast__id_ti; typedef struct _fx_T2Bi { bool t0; int_ t1; } _fx_T2Bi; typedef struct _fx_N12Ast__scope_t { int tag; union { int_ ScBlock; struct _fx_T2Bi ScLoop; int_ ScFold; int_ ScArrMap; int_ ScMap; int_ ScTry; struct _fx_R9Ast__id_t ScFun; struct _fx_R9Ast__id_t ScClass; struct _fx_R9Ast__id_t ScInterface; int_ ScModule; } u; } _fx_N12Ast__scope_t; typedef struct _fx_LN12Ast__scope_t_data_t { int_ rc; struct _fx_LN12Ast__scope_t_data_t* tl; struct _fx_N12Ast__scope_t hd; } _fx_LN12Ast__scope_t_data_t, *_fx_LN12Ast__scope_t; typedef struct _fx_R16Ast__val_flags_t { bool val_flag_arg; bool val_flag_mutable; bool val_flag_temp; bool val_flag_tempref; bool val_flag_private; bool val_flag_subarray; bool val_flag_instance; struct _fx_T2R9Ast__id_ti val_flag_method; int_ val_flag_ctor; struct _fx_LN12Ast__scope_t_data_t* val_flag_global; } _fx_R16Ast__val_flags_t; typedef struct _fx_R17C_form__cdefval_t { struct _fx_R9Ast__id_t cv_name; struct _fx_N14C_form__ctyp_t_data_t* cv_typ; fx_str_t cv_cname; struct _fx_R16Ast__val_flags_t cv_flags; struct _fx_R10Ast__loc_t cv_loc; } _fx_R17C_form__cdefval_t; typedef struct _fx_R19C_form__cdeflabel_t { struct _fx_R9Ast__id_t cl_name; fx_str_t cl_cname; struct _fx_R10Ast__loc_t cl_loc; } _fx_R19C_form__cdeflabel_t; typedef struct _fx_T2R9Ast__id_tN14C_form__ctyp_t { struct _fx_R9Ast__id_t t0; struct _fx_N14C_form__ctyp_t_data_t* t1; } _fx_T2R9Ast__id_tN14C_form__ctyp_t; typedef struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t { int_ rc; struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* tl; struct _fx_T2R9Ast__id_tN14C_form__ctyp_t hd; } _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t, *_fx_LT2R9Ast__id_tN14C_form__ctyp_t; typedef struct _fx_R23C_form__cdefinterface_t { struct _fx_R9Ast__id_t ci_name; fx_str_t ci_cname; struct _fx_R9Ast__id_t ci_id; struct _fx_R9Ast__id_t ci_vtbl; struct _fx_R9Ast__id_t ci_base; struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* ci_all_methods; struct _fx_LN12Ast__scope_t_data_t* ci_scope; struct _fx_R10Ast__loc_t ci_loc; } _fx_R23C_form__cdefinterface_t; typedef struct _fx_rR23C_form__cdefinterface_t_data_t { int_ rc; struct _fx_R23C_form__cdefinterface_t data; } _fx_rR23C_form__cdefinterface_t_data_t, *_fx_rR23C_form__cdefinterface_t; typedef struct _fx_N17Ast__fun_constr_t { int tag; union { int_ CtorVariant; struct _fx_R9Ast__id_t CtorFP; struct _fx_R9Ast__id_t CtorExn; } u; } _fx_N17Ast__fun_constr_t; typedef struct _fx_R16Ast__fun_flags_t { int_ fun_flag_pure; bool fun_flag_ccode; bool fun_flag_have_keywords; bool fun_flag_inline; bool fun_flag_nothrow; bool fun_flag_really_nothrow; bool fun_flag_private; struct _fx_N17Ast__fun_constr_t fun_flag_ctor; struct _fx_R9Ast__id_t fun_flag_method_of; bool fun_flag_uses_fv; bool fun_flag_recursive; bool fun_flag_instance; } _fx_R16Ast__fun_flags_t; typedef struct _fx_LN15C_form__cstmt_t_data_t { int_ rc; struct _fx_LN15C_form__cstmt_t_data_t* tl; struct _fx_N15C_form__cstmt_t_data_t* hd; } _fx_LN15C_form__cstmt_t_data_t, *_fx_LN15C_form__cstmt_t; typedef struct _fx_N19C_form__carg_attr_t { int tag; } _fx_N19C_form__carg_attr_t; typedef struct _fx_LN19C_form__carg_attr_t_data_t { int_ rc; struct _fx_LN19C_form__carg_attr_t_data_t* tl; struct _fx_N19C_form__carg_attr_t hd; } _fx_LN19C_form__carg_attr_t_data_t, *_fx_LN19C_form__carg_attr_t; typedef struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t { struct _fx_R9Ast__id_t t0; struct _fx_N14C_form__ctyp_t_data_t* t1; struct _fx_LN19C_form__carg_attr_t_data_t* t2; } _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t; typedef struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t { int_ rc; struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t* tl; struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t hd; } _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t, *_fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t; typedef struct _fx_R17C_form__cdeffun_t { struct _fx_R9Ast__id_t cf_name; fx_str_t cf_cname; struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t* cf_args; struct _fx_N14C_form__ctyp_t_data_t* cf_rt; struct _fx_LN15C_form__cstmt_t_data_t* cf_body; struct _fx_R16Ast__fun_flags_t cf_flags; struct _fx_LN12Ast__scope_t_data_t* cf_scope; struct _fx_R10Ast__loc_t cf_loc; } _fx_R17C_form__cdeffun_t; typedef struct _fx_rR17C_form__cdeffun_t_data_t { int_ rc; struct _fx_R17C_form__cdeffun_t data; } _fx_rR17C_form__cdeffun_t_data_t, *_fx_rR17C_form__cdeffun_t; typedef struct _fx_Ta2R9Ast__id_t { struct _fx_R9Ast__id_t t0; struct _fx_R9Ast__id_t t1; } _fx_Ta2R9Ast__id_t; typedef struct _fx_LR9Ast__id_t_data_t { int_ rc; struct _fx_LR9Ast__id_t_data_t* tl; struct _fx_R9Ast__id_t hd; } _fx_LR9Ast__id_t_data_t, *_fx_LR9Ast__id_t; typedef struct _fx_R17C_form__ctprops_t { bool ctp_scalar; bool ctp_complex; bool ctp_ptr; bool ctp_pass_by_ref; struct _fx_LR9Ast__id_t_data_t* ctp_make; struct _fx_Ta2R9Ast__id_t ctp_free; struct _fx_Ta2R9Ast__id_t ctp_copy; } _fx_R17C_form__ctprops_t; typedef struct _fx_R17C_form__cdeftyp_t { struct _fx_R9Ast__id_t ct_name; struct _fx_N14C_form__ctyp_t_data_t* ct_typ; fx_str_t ct_cname; struct _fx_R17C_form__ctprops_t ct_props; int_ ct_data_start; struct _fx_R9Ast__id_t ct_enum; struct _fx_LR9Ast__id_t_data_t* ct_ifaces; struct _fx_R9Ast__id_t ct_ifaces_id; struct _fx_LN12Ast__scope_t_data_t* ct_scope; struct _fx_R10Ast__loc_t ct_loc; } _fx_R17C_form__cdeftyp_t; typedef struct _fx_rR17C_form__cdeftyp_t_data_t { int_ rc; struct _fx_R17C_form__cdeftyp_t data; } _fx_rR17C_form__cdeftyp_t_data_t, *_fx_rR17C_form__cdeftyp_t; typedef struct _fx_Nt6option1N14C_form__cexp_t { int tag; union { struct _fx_N14C_form__cexp_t_data_t* Some; } u; } _fx_Nt6option1N14C_form__cexp_t; typedef struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t { struct _fx_R9Ast__id_t t0; struct _fx_Nt6option1N14C_form__cexp_t t1; } _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t; typedef struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t { int_ rc; struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t* tl; struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t hd; } _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t, *_fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t; typedef struct _fx_R18C_form__cdefenum_t { struct _fx_R9Ast__id_t cenum_name; struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t* cenum_members; fx_str_t cenum_cname; struct _fx_LN12Ast__scope_t_data_t* cenum_scope; struct _fx_R10Ast__loc_t cenum_loc; } _fx_R18C_form__cdefenum_t; typedef struct _fx_rR18C_form__cdefenum_t_data_t { int_ rc; struct _fx_R18C_form__cdefenum_t data; } _fx_rR18C_form__cdefenum_t_data_t, *_fx_rR18C_form__cdefenum_t; typedef struct _fx_R19C_form__cdefmacro_t { struct _fx_R9Ast__id_t cm_name; fx_str_t cm_cname; struct _fx_LR9Ast__id_t_data_t* cm_args; struct _fx_LN15C_form__cstmt_t_data_t* cm_body; struct _fx_LN12Ast__scope_t_data_t* cm_scope; struct _fx_R10Ast__loc_t cm_loc; } _fx_R19C_form__cdefmacro_t; typedef struct _fx_rR19C_form__cdefmacro_t_data_t { int_ rc; struct _fx_R19C_form__cdefmacro_t data; } _fx_rR19C_form__cdefmacro_t_data_t, *_fx_rR19C_form__cdefmacro_t; typedef struct _fx_R17C_form__cdefexn_t { struct _fx_R9Ast__id_t cexn_name; fx_str_t cexn_cname; fx_str_t cexn_base_cname; struct _fx_N14C_form__ctyp_t_data_t* cexn_typ; bool cexn_std; struct _fx_R9Ast__id_t cexn_tag; struct _fx_R9Ast__id_t cexn_data; struct _fx_R9Ast__id_t cexn_info; struct _fx_R9Ast__id_t cexn_make; struct _fx_LN12Ast__scope_t_data_t* cexn_scope; struct _fx_R10Ast__loc_t cexn_loc; } _fx_R17C_form__cdefexn_t; typedef struct _fx_rR17C_form__cdefexn_t_data_t { int_ rc; struct _fx_R17C_form__cdefexn_t data; } _fx_rR17C_form__cdefexn_t_data_t, *_fx_rR17C_form__cdefexn_t; typedef struct _fx_N15C_form__cinfo_t { int tag; union { struct _fx_R17C_form__cdefval_t CVal; struct _fx_rR17C_form__cdeffun_t_data_t* CFun; struct _fx_rR17C_form__cdeftyp_t_data_t* CTyp; struct _fx_rR17C_form__cdefexn_t_data_t* CExn; struct _fx_rR23C_form__cdefinterface_t_data_t* CInterface; struct _fx_rR18C_form__cdefenum_t_data_t* CEnum; struct _fx_R19C_form__cdeflabel_t CLabel; struct _fx_rR19C_form__cdefmacro_t_data_t* CMacro; } u; } _fx_N15C_form__cinfo_t; typedef struct _fx_T2R9Ast__id_tN14K_form__ktyp_t { struct _fx_R9Ast__id_t t0; struct _fx_N14K_form__ktyp_t_data_t* t1; } _fx_T2R9Ast__id_tN14K_form__ktyp_t; typedef struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t { int_ rc; struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t* tl; struct _fx_T2R9Ast__id_tN14K_form__ktyp_t hd; } _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t, *_fx_LT2R9Ast__id_tN14K_form__ktyp_t; typedef struct _fx_LN14K_form__ktyp_t_data_t { int_ rc; struct _fx_LN14K_form__ktyp_t_data_t* tl; struct _fx_N14K_form__ktyp_t_data_t* hd; } _fx_LN14K_form__ktyp_t_data_t, *_fx_LN14K_form__ktyp_t; typedef struct _fx_T2R10Ast__loc_tS { struct _fx_R10Ast__loc_t t0; fx_str_t t1; } _fx_T2R10Ast__loc_tS; typedef struct _fx_N13PP__ppstyle_t { int tag; } _fx_N13PP__ppstyle_t; typedef struct _fx_T3iiC { int_ t0; int_ t1; char_ t2; } _fx_T3iiC; typedef struct _fx_T2iN13PP__ppstyle_t { int_ t0; struct _fx_N13PP__ppstyle_t t1; } _fx_T2iN13PP__ppstyle_t; typedef struct _fx_N11PP__pptok_t { int tag; union { fx_str_t PPString; struct _fx_T3iiC PPBreak; struct _fx_T2iN13PP__ppstyle_t PPBegin; } u; } _fx_N11PP__pptok_t; typedef struct _fx_T2N11PP__pptok_ti { struct _fx_N11PP__pptok_t t0; int_ t1; } _fx_T2N11PP__pptok_ti; typedef struct _fx_R11PP__state_t { int_ space; int_ left; int_ right; int_ top; int_ bottom; int_ lefttotal; int_ righttotal; fx_arr_t q; fx_arr_t stack; fx_arr_t pp_stack; int_ pp_top; bool emptystack; } _fx_R11PP__state_t; typedef struct _fx_FPv1S { int (*fp)(fx_str_t*, void*); fx_fcv_t* fcv; } _fx_FPv1S; typedef struct _fx_FPLS0 { int (*fp)(struct _fx_LS_data_t**, void*); fx_fcv_t* fcv; } _fx_FPLS0; typedef struct _fx_rR11PP__state_t_data_t { int_ rc; struct _fx_R11PP__state_t data; } _fx_rR11PP__state_t_data_t, *_fx_rR11PP__state_t; typedef struct _fx_R5PP__t { int_ margin; int_ default_indent; struct _fx_FPv1S print_f; struct _fx_FPLS0 get_f; struct _fx_rR11PP__state_t_data_t* r; } _fx_R5PP__t; typedef struct _fx_T2il { int_ t0; int64_t t1; } _fx_T2il; typedef struct _fx_T2iq { int_ t0; uint64_t t1; } _fx_T2iq; typedef struct _fx_T2id { int_ t0; double t1; } _fx_T2id; typedef struct _fx_N14K_form__klit_t { int tag; union { int64_t KLitInt; struct _fx_T2il KLitSInt; struct _fx_T2iq KLitUInt; struct _fx_T2id KLitFloat; fx_str_t KLitString; char_ KLitChar; bool KLitBool; struct _fx_N14K_form__ktyp_t_data_t* KLitNil; } u; } _fx_N14K_form__klit_t; typedef struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t { struct _fx_LN14K_form__ktyp_t_data_t* t0; struct _fx_N14K_form__ktyp_t_data_t* t1; } _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t; typedef struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t { struct _fx_R9Ast__id_t t0; struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t* t1; } _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t; typedef struct _fx_T2iN14K_form__ktyp_t { int_ t0; struct _fx_N14K_form__ktyp_t_data_t* t1; } _fx_T2iN14K_form__ktyp_t; typedef struct _fx_N14K_form__ktyp_t_data_t { int_ rc; int tag; union { int_ KTypSInt; int_ KTypUInt; int_ KTypFloat; struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t KTypFun; struct _fx_LN14K_form__ktyp_t_data_t* KTypTuple; struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t KTypRecord; struct _fx_R9Ast__id_t KTypName; struct _fx_T2iN14K_form__ktyp_t KTypArray; struct _fx_N14K_form__ktyp_t_data_t* KTypVector; struct _fx_N14K_form__ktyp_t_data_t* KTypList; struct _fx_N14K_form__ktyp_t_data_t* KTypRef; } u; } _fx_N14K_form__ktyp_t_data_t, *_fx_N14K_form__ktyp_t; typedef struct _fx_Nt6option1N14C_form__ctyp_t { int tag; union { struct _fx_N14C_form__ctyp_t_data_t* Some; } u; } _fx_Nt6option1N14C_form__ctyp_t; typedef struct _fx_Nt6option1R9Ast__id_t { int tag; union { struct _fx_R9Ast__id_t Some; } u; } _fx_Nt6option1R9Ast__id_t; typedef struct _fx_N12Ast__cmpop_t { int tag; } _fx_N12Ast__cmpop_t; typedef struct _fx_T2R9Ast__id_tR10Ast__loc_t { struct _fx_R9Ast__id_t t0; struct _fx_R10Ast__loc_t t1; } _fx_T2R9Ast__id_tR10Ast__loc_t; typedef struct _fx_T2SR10Ast__loc_t { fx_str_t t0; struct _fx_R10Ast__loc_t t1; } _fx_T2SR10Ast__loc_t; typedef struct _fx_N17C_form__cbinary_t { int tag; union { struct _fx_N12Ast__cmpop_t COpCmp; } u; } _fx_N17C_form__cbinary_t; typedef struct _fx_N16C_form__cunary_t { int tag; } _fx_N16C_form__cunary_t; typedef struct _fx_N19C_form__ctyp_attr_t { int tag; } _fx_N19C_form__ctyp_attr_t; typedef struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t { struct _fx_Nt6option1R9Ast__id_t t0; struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* t1; } _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t; typedef struct _fx_LN14C_form__ctyp_t_data_t { int_ rc; struct _fx_LN14C_form__ctyp_t_data_t* tl; struct _fx_N14C_form__ctyp_t_data_t* hd; } _fx_LN14C_form__ctyp_t_data_t, *_fx_LN14C_form__ctyp_t; typedef struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t { struct _fx_LN14C_form__ctyp_t_data_t* t0; struct _fx_N14C_form__ctyp_t_data_t* t1; } _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t; typedef struct _fx_LN19C_form__ctyp_attr_t_data_t { int_ rc; struct _fx_LN19C_form__ctyp_attr_t_data_t* tl; struct _fx_N19C_form__ctyp_attr_t hd; } _fx_LN19C_form__ctyp_attr_t_data_t, *_fx_LN19C_form__ctyp_attr_t; typedef struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t { struct _fx_LN19C_form__ctyp_attr_t_data_t* t0; struct _fx_N14C_form__ctyp_t_data_t* t1; } _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t; typedef struct _fx_T2iN14C_form__ctyp_t { int_ t0; struct _fx_N14C_form__ctyp_t_data_t* t1; } _fx_T2iN14C_form__ctyp_t; typedef struct _fx_N14C_form__ctyp_t_data_t { int_ rc; int tag; union { int_ CTypSInt; int_ CTypUInt; int_ CTypFloat; struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t CTypStruct; struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t CTypUnion; struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t CTypFunRawPtr; struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t CTypRawPtr; struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t CTypRawArray; struct _fx_T2iN14C_form__ctyp_t CTypArray; struct _fx_N14C_form__ctyp_t_data_t* CTypVector; struct _fx_R9Ast__id_t CTypName; } u; } _fx_N14C_form__ctyp_t_data_t, *_fx_N14C_form__ctyp_t; typedef struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14C_form__ctyp_t_data_t* t0; struct _fx_R10Ast__loc_t t1; } _fx_T2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_R9Ast__id_t t0; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t1; } _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14K_form__klit_t t0; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t1; } _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N17C_form__cbinary_t t0; struct _fx_N14C_form__cexp_t_data_t* t1; struct _fx_N14C_form__cexp_t_data_t* t2; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t3; } _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N16C_form__cunary_t t0; struct _fx_N14C_form__cexp_t_data_t* t1; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t2; } _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_R9Ast__id_t t1; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t2; } _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_N14C_form__ctyp_t_data_t* t1; struct _fx_R10Ast__loc_t t2; } _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_N14C_form__cexp_t_data_t* t1; struct _fx_N14C_form__cexp_t_data_t* t2; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t3; } _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_LN14C_form__cexp_t_data_t { int_ rc; struct _fx_LN14C_form__cexp_t_data_t* tl; struct _fx_N14C_form__cexp_t_data_t* hd; } _fx_LN14C_form__cexp_t_data_t, *_fx_LN14C_form__cexp_t; typedef struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_LN14C_form__cexp_t_data_t* t1; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t2; } _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t { struct _fx_LN14C_form__cexp_t_data_t* t0; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t t1; } _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t; typedef struct _fx_N14C_form__cexp_t_data_t { int_ rc; int tag; union { struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t CExpIdent; struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t CExpLit; struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t CExpBinary; struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t CExpUnary; struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t CExpMem; struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t CExpArrow; struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t CExpCast; struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t CExpTernary; struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t CExpCall; struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t CExpInit; struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t CExpTyp; struct _fx_T2SR10Ast__loc_t CExpCCode; } u; } _fx_N14C_form__cexp_t_data_t, *_fx_N14C_form__cexp_t; typedef struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t { struct _fx_Nt6option1N14C_form__cexp_t t0; struct _fx_R10Ast__loc_t t1; } _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t; typedef struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t { struct _fx_LN15C_form__cstmt_t_data_t* t0; struct _fx_R10Ast__loc_t t1; } _fx_T2LN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_T2R9Ast__id_tN15C_form__cstmt_t { struct _fx_R9Ast__id_t t0; struct _fx_N15C_form__cstmt_t_data_t* t1; } _fx_T2R9Ast__id_tN15C_form__cstmt_t; typedef struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_N15C_form__cstmt_t_data_t* t1; struct _fx_N15C_form__cstmt_t_data_t* t2; struct _fx_R10Ast__loc_t t3; } _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t { struct _fx_Nt6option1N14C_form__ctyp_t t0; struct _fx_LN14C_form__cexp_t_data_t* t1; struct _fx_Nt6option1N14C_form__cexp_t t2; struct _fx_LN14C_form__cexp_t_data_t* t3; struct _fx_N15C_form__cstmt_t_data_t* t4; struct _fx_R10Ast__loc_t t5; } _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_N15C_form__cstmt_t_data_t* t1; struct _fx_R10Ast__loc_t t2; } _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t { struct _fx_N15C_form__cstmt_t_data_t* t0; struct _fx_N14C_form__cexp_t_data_t* t1; struct _fx_R10Ast__loc_t t2; } _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t; typedef struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t { struct _fx_LN14C_form__cexp_t_data_t* t0; struct _fx_LN15C_form__cstmt_t_data_t* t1; } _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t; typedef struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t { int_ rc; struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t* tl; struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t hd; } _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t, *_fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t; typedef struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t* t1; struct _fx_R10Ast__loc_t t2; } _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t { struct _fx_N14C_form__ctyp_t_data_t* t0; struct _fx_R9Ast__id_t t1; struct _fx_Nt6option1N14C_form__cexp_t t2; struct _fx_R10Ast__loc_t t3; } _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t; typedef struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t { struct _fx_N14C_form__cexp_t_data_t* t0; struct _fx_LN15C_form__cstmt_t_data_t* t1; } _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t; typedef struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t { int_ rc; struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t* tl; struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t hd; } _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t, *_fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t; typedef struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t { struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t* t0; struct _fx_LN15C_form__cstmt_t_data_t* t1; struct _fx_R10Ast__loc_t t2; } _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t; typedef struct _fx_N15C_form__cstmt_t_data_t { int_ rc; int tag; union { struct _fx_R10Ast__loc_t CStmtNop; struct _fx_T2SR10Ast__loc_t CComment; struct _fx_N14C_form__cexp_t_data_t* CExp; struct _fx_R10Ast__loc_t CStmtBreak; struct _fx_R10Ast__loc_t CStmtContinue; struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t CStmtReturn; struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t CStmtBlock; struct _fx_T2R9Ast__id_tN15C_form__cstmt_t CStmtSync; struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t CStmtIf; struct _fx_T2R9Ast__id_tR10Ast__loc_t CStmtGoto; struct _fx_T2R9Ast__id_tR10Ast__loc_t CStmtLabel; struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t CStmtFor; struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t CStmtWhile; struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t CStmtDoWhile; struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t CStmtSwitch; struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t CDefVal; struct _fx_rR17C_form__cdeffun_t_data_t* CDefFun; struct _fx_rR17C_form__cdeftyp_t_data_t* CDefTyp; struct _fx_T2R9Ast__id_tR10Ast__loc_t CDefForwardSym; struct _fx_T2R9Ast__id_tR10Ast__loc_t CDefForwardTyp; struct _fx_rR18C_form__cdefenum_t_data_t* CDefEnum; struct _fx_rR23C_form__cdefinterface_t_data_t* CDefInterface; struct _fx_rR19C_form__cdefmacro_t_data_t* CMacroDef; struct _fx_T2R9Ast__id_tR10Ast__loc_t CMacroUndef; struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t CMacroIf; struct _fx_T2SR10Ast__loc_t CMacroInclude; struct _fx_T2SR10Ast__loc_t CMacroPragma; } u; } _fx_N15C_form__cstmt_t_data_t, *_fx_N15C_form__cstmt_t; typedef struct _fx_N13C_pp__assoc_t { int tag; } _fx_N13C_pp__assoc_t; typedef struct _fx_T3SiN13C_pp__assoc_t { fx_str_t t0; int_ t1; struct _fx_N13C_pp__assoc_t t2; } _fx_T3SiN13C_pp__assoc_t; typedef struct { int_ rc; int_ data; } _fx_E4Exit_data_t; typedef struct { int_ rc; fx_str_t data; } _fx_E4Fail_data_t; typedef struct { int_ rc; struct _fx_T2Ta2iS data; } _fx_E22LexerUtils__LexerError_data_t; typedef struct { int_ rc; struct _fx_T2R10Ast__loc_tS data; } _fx_E17Ast__CompileError_data_t; typedef struct { int_ rc; struct _fx_T2R10Ast__loc_tS data; } _fx_E18Parser__ParseError_data_t; static void _fx_free_LS(struct _fx_LS_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LS, fx_free_str); } static int _fx_cons_LS(fx_str_t* hd, struct _fx_LS_data_t* tl, bool addref_tl, struct _fx_LS_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LS, fx_copy_str); } static void _fx_free_N17Options__optval_t(struct _fx_N17Options__optval_t* dst) { switch (dst->tag) { case 3: fx_free_str(&dst->u.OptString); break; default: ; } dst->tag = 0; } static void _fx_copy_N17Options__optval_t(struct _fx_N17Options__optval_t* src, struct _fx_N17Options__optval_t* dst) { dst->tag = src->tag; switch (src->tag) { case 3: fx_copy_str(&src->u.OptString, &dst->u.OptString); break; default: dst->u = src->u; } } static void _fx_free_T2SN17Options__optval_t(struct _fx_T2SN17Options__optval_t* dst) { fx_free_str(&dst->t0); _fx_free_N17Options__optval_t(&dst->t1); } static void _fx_copy_T2SN17Options__optval_t(struct _fx_T2SN17Options__optval_t* src, struct _fx_T2SN17Options__optval_t* dst) { fx_copy_str(&src->t0, &dst->t0); _fx_copy_N17Options__optval_t(&src->t1, &dst->t1); } static void _fx_make_T2SN17Options__optval_t( fx_str_t* t0, struct _fx_N17Options__optval_t* t1, struct _fx_T2SN17Options__optval_t* fx_result) { fx_copy_str(t0, &fx_result->t0); _fx_copy_N17Options__optval_t(t1, &fx_result->t1); } static void _fx_free_LT2SN17Options__optval_t(struct _fx_LT2SN17Options__optval_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2SN17Options__optval_t, _fx_free_T2SN17Options__optval_t); } static int _fx_cons_LT2SN17Options__optval_t( struct _fx_T2SN17Options__optval_t* hd, struct _fx_LT2SN17Options__optval_t_data_t* tl, bool addref_tl, struct _fx_LT2SN17Options__optval_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2SN17Options__optval_t, _fx_copy_T2SN17Options__optval_t); } static void _fx_free_R18Options__options_t(struct _fx_R18Options__options_t* dst) { _fx_free_LS(&dst->app_args); fx_free_str(&dst->app_filename); fx_free_str(&dst->build_dir); fx_free_str(&dst->build_rootdir); fx_free_str(&dst->cflags); fx_free_str(&dst->clibs); fx_free_str(&dst->filename); _fx_free_LS(&dst->include_path); _fx_free_LT2SN17Options__optval_t(&dst->defines); fx_free_str(&dst->output_name); } static void _fx_copy_R18Options__options_t(struct _fx_R18Options__options_t* src, struct _fx_R18Options__options_t* dst) { FX_COPY_PTR(src->app_args, &dst->app_args); fx_copy_str(&src->app_filename, &dst->app_filename); dst->arch64 = src->arch64; dst->force_rebuild = src->force_rebuild; fx_copy_str(&src->build_dir, &dst->build_dir); fx_copy_str(&src->build_rootdir, &dst->build_rootdir); fx_copy_str(&src->cflags, &dst->cflags); fx_copy_str(&src->clibs, &dst->clibs); dst->compile_by_cpp = src->compile_by_cpp; fx_copy_str(&src->filename, &dst->filename); dst->gen_c = src->gen_c; FX_COPY_PTR(src->include_path, &dst->include_path); dst->debug = src->debug; FX_COPY_PTR(src->defines, &dst->defines); dst->optim_iters = src->optim_iters; dst->inline_thresh = src->inline_thresh; dst->enable_openmp = src->enable_openmp; dst->relax = src->relax; dst->use_preamble = src->use_preamble; dst->make_app = src->make_app; dst->optimize_level = src->optimize_level; fx_copy_str(&src->output_name, &dst->output_name); dst->print_ast0 = src->print_ast0; dst->print_ast = src->print_ast; dst->print_k0 = src->print_k0; dst->print_k = src->print_k; dst->print_tokens = src->print_tokens; dst->run_app = src->run_app; dst->verbose = src->verbose; dst->W_unused = src->W_unused; } static void _fx_make_R18Options__options_t( struct _fx_LS_data_t* r_app_args, fx_str_t* r_app_filename, bool r_arch64, bool r_force_rebuild, fx_str_t* r_build_dir, fx_str_t* r_build_rootdir, fx_str_t* r_cflags, fx_str_t* r_clibs, bool r_compile_by_cpp, fx_str_t* r_filename, bool r_gen_c, struct _fx_LS_data_t* r_include_path, bool r_debug, struct _fx_LT2SN17Options__optval_t_data_t* r_defines, int_ r_optim_iters, int_ r_inline_thresh, bool r_enable_openmp, bool r_relax, bool r_use_preamble, bool r_make_app, int_ r_optimize_level, fx_str_t* r_output_name, bool r_print_ast0, bool r_print_ast, bool r_print_k0, bool r_print_k, bool r_print_tokens, bool r_run_app, bool r_verbose, bool r_W_unused, struct _fx_R18Options__options_t* fx_result) { FX_COPY_PTR(r_app_args, &fx_result->app_args); fx_copy_str(r_app_filename, &fx_result->app_filename); fx_result->arch64 = r_arch64; fx_result->force_rebuild = r_force_rebuild; fx_copy_str(r_build_dir, &fx_result->build_dir); fx_copy_str(r_build_rootdir, &fx_result->build_rootdir); fx_copy_str(r_cflags, &fx_result->cflags); fx_copy_str(r_clibs, &fx_result->clibs); fx_result->compile_by_cpp = r_compile_by_cpp; fx_copy_str(r_filename, &fx_result->filename); fx_result->gen_c = r_gen_c; FX_COPY_PTR(r_include_path, &fx_result->include_path); fx_result->debug = r_debug; FX_COPY_PTR(r_defines, &fx_result->defines); fx_result->optim_iters = r_optim_iters; fx_result->inline_thresh = r_inline_thresh; fx_result->enable_openmp = r_enable_openmp; fx_result->relax = r_relax; fx_result->use_preamble = r_use_preamble; fx_result->make_app = r_make_app; fx_result->optimize_level = r_optimize_level; fx_copy_str(r_output_name, &fx_result->output_name); fx_result->print_ast0 = r_print_ast0; fx_result->print_ast = r_print_ast; fx_result->print_k0 = r_print_k0; fx_result->print_k = r_print_k; fx_result->print_tokens = r_print_tokens; fx_result->run_app = r_run_app; fx_result->verbose = r_verbose; fx_result->W_unused = r_W_unused; } static void _fx_free_T2Ta2iS(struct _fx_T2Ta2iS* dst) { fx_free_str(&dst->t1); } static void _fx_copy_T2Ta2iS(struct _fx_T2Ta2iS* src, struct _fx_T2Ta2iS* dst) { dst->t0 = src->t0; fx_copy_str(&src->t1, &dst->t1); } static void _fx_make_T2Ta2iS(struct _fx_Ta2i* t0, fx_str_t* t1, struct _fx_T2Ta2iS* fx_result) { fx_result->t0 = *t0; fx_copy_str(t1, &fx_result->t1); } static int _fx_cons_LN12Ast__scope_t( struct _fx_N12Ast__scope_t* hd, struct _fx_LN12Ast__scope_t_data_t* tl, bool addref_tl, struct _fx_LN12Ast__scope_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN12Ast__scope_t, FX_COPY_SIMPLE_BY_PTR); } static void _fx_free_R16Ast__val_flags_t(struct _fx_R16Ast__val_flags_t* dst) { fx_free_list_simple(&dst->val_flag_global); } static void _fx_copy_R16Ast__val_flags_t(struct _fx_R16Ast__val_flags_t* src, struct _fx_R16Ast__val_flags_t* dst) { dst->val_flag_arg = src->val_flag_arg; dst->val_flag_mutable = src->val_flag_mutable; dst->val_flag_temp = src->val_flag_temp; dst->val_flag_tempref = src->val_flag_tempref; dst->val_flag_private = src->val_flag_private; dst->val_flag_subarray = src->val_flag_subarray; dst->val_flag_instance = src->val_flag_instance; dst->val_flag_method = src->val_flag_method; dst->val_flag_ctor = src->val_flag_ctor; FX_COPY_PTR(src->val_flag_global, &dst->val_flag_global); } static void _fx_make_R16Ast__val_flags_t( bool r_val_flag_arg, bool r_val_flag_mutable, bool r_val_flag_temp, bool r_val_flag_tempref, bool r_val_flag_private, bool r_val_flag_subarray, bool r_val_flag_instance, struct _fx_T2R9Ast__id_ti* r_val_flag_method, int_ r_val_flag_ctor, struct _fx_LN12Ast__scope_t_data_t* r_val_flag_global, struct _fx_R16Ast__val_flags_t* fx_result) { fx_result->val_flag_arg = r_val_flag_arg; fx_result->val_flag_mutable = r_val_flag_mutable; fx_result->val_flag_temp = r_val_flag_temp; fx_result->val_flag_tempref = r_val_flag_tempref; fx_result->val_flag_private = r_val_flag_private; fx_result->val_flag_subarray = r_val_flag_subarray; fx_result->val_flag_instance = r_val_flag_instance; fx_result->val_flag_method = *r_val_flag_method; fx_result->val_flag_ctor = r_val_flag_ctor; FX_COPY_PTR(r_val_flag_global, &fx_result->val_flag_global); } static void _fx_free_R17C_form__cdefval_t(struct _fx_R17C_form__cdefval_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->cv_typ); fx_free_str(&dst->cv_cname); _fx_free_R16Ast__val_flags_t(&dst->cv_flags); } static void _fx_copy_R17C_form__cdefval_t(struct _fx_R17C_form__cdefval_t* src, struct _fx_R17C_form__cdefval_t* dst) { dst->cv_name = src->cv_name; FX_COPY_PTR(src->cv_typ, &dst->cv_typ); fx_copy_str(&src->cv_cname, &dst->cv_cname); _fx_copy_R16Ast__val_flags_t(&src->cv_flags, &dst->cv_flags); dst->cv_loc = src->cv_loc; } static void _fx_make_R17C_form__cdefval_t( struct _fx_R9Ast__id_t* r_cv_name, struct _fx_N14C_form__ctyp_t_data_t* r_cv_typ, fx_str_t* r_cv_cname, struct _fx_R16Ast__val_flags_t* r_cv_flags, struct _fx_R10Ast__loc_t* r_cv_loc, struct _fx_R17C_form__cdefval_t* fx_result) { fx_result->cv_name = *r_cv_name; FX_COPY_PTR(r_cv_typ, &fx_result->cv_typ); fx_copy_str(r_cv_cname, &fx_result->cv_cname); _fx_copy_R16Ast__val_flags_t(r_cv_flags, &fx_result->cv_flags); fx_result->cv_loc = *r_cv_loc; } static void _fx_free_R19C_form__cdeflabel_t(struct _fx_R19C_form__cdeflabel_t* dst) { fx_free_str(&dst->cl_cname); } static void _fx_copy_R19C_form__cdeflabel_t(struct _fx_R19C_form__cdeflabel_t* src, struct _fx_R19C_form__cdeflabel_t* dst) { dst->cl_name = src->cl_name; fx_copy_str(&src->cl_cname, &dst->cl_cname); dst->cl_loc = src->cl_loc; } static void _fx_make_R19C_form__cdeflabel_t( struct _fx_R9Ast__id_t* r_cl_name, fx_str_t* r_cl_cname, struct _fx_R10Ast__loc_t* r_cl_loc, struct _fx_R19C_form__cdeflabel_t* fx_result) { fx_result->cl_name = *r_cl_name; fx_copy_str(r_cl_cname, &fx_result->cl_cname); fx_result->cl_loc = *r_cl_loc; } static void _fx_free_T2R9Ast__id_tN14C_form__ctyp_t(struct _fx_T2R9Ast__id_tN14C_form__ctyp_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tN14C_form__ctyp_t( struct _fx_T2R9Ast__id_tN14C_form__ctyp_t* src, struct _fx_T2R9Ast__id_tN14C_form__ctyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tN14C_form__ctyp_t( struct _fx_R9Ast__id_t* t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_T2R9Ast__id_tN14C_form__ctyp_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_LT2R9Ast__id_tN14C_form__ctyp_t(struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2R9Ast__id_tN14C_form__ctyp_t, _fx_free_T2R9Ast__id_tN14C_form__ctyp_t); } static int _fx_cons_LT2R9Ast__id_tN14C_form__ctyp_t( struct _fx_T2R9Ast__id_tN14C_form__ctyp_t* hd, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* tl, bool addref_tl, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2R9Ast__id_tN14C_form__ctyp_t, _fx_copy_T2R9Ast__id_tN14C_form__ctyp_t); } static void _fx_free_R23C_form__cdefinterface_t(struct _fx_R23C_form__cdefinterface_t* dst) { fx_free_str(&dst->ci_cname); _fx_free_LT2R9Ast__id_tN14C_form__ctyp_t(&dst->ci_all_methods); fx_free_list_simple(&dst->ci_scope); } static void _fx_copy_R23C_form__cdefinterface_t( struct _fx_R23C_form__cdefinterface_t* src, struct _fx_R23C_form__cdefinterface_t* dst) { dst->ci_name = src->ci_name; fx_copy_str(&src->ci_cname, &dst->ci_cname); dst->ci_id = src->ci_id; dst->ci_vtbl = src->ci_vtbl; dst->ci_base = src->ci_base; FX_COPY_PTR(src->ci_all_methods, &dst->ci_all_methods); FX_COPY_PTR(src->ci_scope, &dst->ci_scope); dst->ci_loc = src->ci_loc; } static void _fx_make_R23C_form__cdefinterface_t( struct _fx_R9Ast__id_t* r_ci_name, fx_str_t* r_ci_cname, struct _fx_R9Ast__id_t* r_ci_id, struct _fx_R9Ast__id_t* r_ci_vtbl, struct _fx_R9Ast__id_t* r_ci_base, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* r_ci_all_methods, struct _fx_LN12Ast__scope_t_data_t* r_ci_scope, struct _fx_R10Ast__loc_t* r_ci_loc, struct _fx_R23C_form__cdefinterface_t* fx_result) { fx_result->ci_name = *r_ci_name; fx_copy_str(r_ci_cname, &fx_result->ci_cname); fx_result->ci_id = *r_ci_id; fx_result->ci_vtbl = *r_ci_vtbl; fx_result->ci_base = *r_ci_base; FX_COPY_PTR(r_ci_all_methods, &fx_result->ci_all_methods); FX_COPY_PTR(r_ci_scope, &fx_result->ci_scope); fx_result->ci_loc = *r_ci_loc; } static void _fx_free_rR23C_form__cdefinterface_t(struct _fx_rR23C_form__cdefinterface_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR23C_form__cdefinterface_t, _fx_free_R23C_form__cdefinterface_t); } static int _fx_make_rR23C_form__cdefinterface_t( struct _fx_R23C_form__cdefinterface_t* arg, struct _fx_rR23C_form__cdefinterface_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR23C_form__cdefinterface_t, _fx_copy_R23C_form__cdefinterface_t); } static void _fx_free_LN15C_form__cstmt_t(struct _fx_LN15C_form__cstmt_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LN15C_form__cstmt_t, _fx_free_N15C_form__cstmt_t); } static int _fx_cons_LN15C_form__cstmt_t( struct _fx_N15C_form__cstmt_t_data_t* hd, struct _fx_LN15C_form__cstmt_t_data_t* tl, bool addref_tl, struct _fx_LN15C_form__cstmt_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN15C_form__cstmt_t, FX_COPY_PTR); } static int _fx_cons_LN19C_form__carg_attr_t( struct _fx_N19C_form__carg_attr_t* hd, struct _fx_LN19C_form__carg_attr_t_data_t* tl, bool addref_tl, struct _fx_LN19C_form__carg_attr_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN19C_form__carg_attr_t, FX_COPY_SIMPLE_BY_PTR); } static void _fx_free_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->t1); fx_free_list_simple(&dst->t2); } static void _fx_copy_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* src, struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); FX_COPY_PTR(src->t2, &dst->t2); } static void _fx_make_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_R9Ast__id_t* t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_LN19C_form__carg_attr_t_data_t* t2, struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); FX_COPY_PTR(t2, &fx_result->t2); } static void _fx_free_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t, _fx_free_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t); } static int _fx_cons_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* hd, struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t* tl, bool addref_tl, struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t, _fx_copy_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t); } static void _fx_free_R17C_form__cdeffun_t(struct _fx_R17C_form__cdeffun_t* dst) { fx_free_str(&dst->cf_cname); _fx_free_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t(&dst->cf_args); _fx_free_N14C_form__ctyp_t(&dst->cf_rt); _fx_free_LN15C_form__cstmt_t(&dst->cf_body); fx_free_list_simple(&dst->cf_scope); } static void _fx_copy_R17C_form__cdeffun_t(struct _fx_R17C_form__cdeffun_t* src, struct _fx_R17C_form__cdeffun_t* dst) { dst->cf_name = src->cf_name; fx_copy_str(&src->cf_cname, &dst->cf_cname); FX_COPY_PTR(src->cf_args, &dst->cf_args); FX_COPY_PTR(src->cf_rt, &dst->cf_rt); FX_COPY_PTR(src->cf_body, &dst->cf_body); dst->cf_flags = src->cf_flags; FX_COPY_PTR(src->cf_scope, &dst->cf_scope); dst->cf_loc = src->cf_loc; } static void _fx_make_R17C_form__cdeffun_t( struct _fx_R9Ast__id_t* r_cf_name, fx_str_t* r_cf_cname, struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t* r_cf_args, struct _fx_N14C_form__ctyp_t_data_t* r_cf_rt, struct _fx_LN15C_form__cstmt_t_data_t* r_cf_body, struct _fx_R16Ast__fun_flags_t* r_cf_flags, struct _fx_LN12Ast__scope_t_data_t* r_cf_scope, struct _fx_R10Ast__loc_t* r_cf_loc, struct _fx_R17C_form__cdeffun_t* fx_result) { fx_result->cf_name = *r_cf_name; fx_copy_str(r_cf_cname, &fx_result->cf_cname); FX_COPY_PTR(r_cf_args, &fx_result->cf_args); FX_COPY_PTR(r_cf_rt, &fx_result->cf_rt); FX_COPY_PTR(r_cf_body, &fx_result->cf_body); fx_result->cf_flags = *r_cf_flags; FX_COPY_PTR(r_cf_scope, &fx_result->cf_scope); fx_result->cf_loc = *r_cf_loc; } static void _fx_free_rR17C_form__cdeffun_t(struct _fx_rR17C_form__cdeffun_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR17C_form__cdeffun_t, _fx_free_R17C_form__cdeffun_t); } static int _fx_make_rR17C_form__cdeffun_t( struct _fx_R17C_form__cdeffun_t* arg, struct _fx_rR17C_form__cdeffun_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR17C_form__cdeffun_t, _fx_copy_R17C_form__cdeffun_t); } static int _fx_cons_LR9Ast__id_t( struct _fx_R9Ast__id_t* hd, struct _fx_LR9Ast__id_t_data_t* tl, bool addref_tl, struct _fx_LR9Ast__id_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LR9Ast__id_t, FX_COPY_SIMPLE_BY_PTR); } static void _fx_free_R17C_form__ctprops_t(struct _fx_R17C_form__ctprops_t* dst) { fx_free_list_simple(&dst->ctp_make); } static void _fx_copy_R17C_form__ctprops_t(struct _fx_R17C_form__ctprops_t* src, struct _fx_R17C_form__ctprops_t* dst) { dst->ctp_scalar = src->ctp_scalar; dst->ctp_complex = src->ctp_complex; dst->ctp_ptr = src->ctp_ptr; dst->ctp_pass_by_ref = src->ctp_pass_by_ref; FX_COPY_PTR(src->ctp_make, &dst->ctp_make); dst->ctp_free = src->ctp_free; dst->ctp_copy = src->ctp_copy; } static void _fx_make_R17C_form__ctprops_t( bool r_ctp_scalar, bool r_ctp_complex, bool r_ctp_ptr, bool r_ctp_pass_by_ref, struct _fx_LR9Ast__id_t_data_t* r_ctp_make, struct _fx_Ta2R9Ast__id_t* r_ctp_free, struct _fx_Ta2R9Ast__id_t* r_ctp_copy, struct _fx_R17C_form__ctprops_t* fx_result) { fx_result->ctp_scalar = r_ctp_scalar; fx_result->ctp_complex = r_ctp_complex; fx_result->ctp_ptr = r_ctp_ptr; fx_result->ctp_pass_by_ref = r_ctp_pass_by_ref; FX_COPY_PTR(r_ctp_make, &fx_result->ctp_make); fx_result->ctp_free = *r_ctp_free; fx_result->ctp_copy = *r_ctp_copy; } static void _fx_free_R17C_form__cdeftyp_t(struct _fx_R17C_form__cdeftyp_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->ct_typ); fx_free_str(&dst->ct_cname); _fx_free_R17C_form__ctprops_t(&dst->ct_props); fx_free_list_simple(&dst->ct_ifaces); fx_free_list_simple(&dst->ct_scope); } static void _fx_copy_R17C_form__cdeftyp_t(struct _fx_R17C_form__cdeftyp_t* src, struct _fx_R17C_form__cdeftyp_t* dst) { dst->ct_name = src->ct_name; FX_COPY_PTR(src->ct_typ, &dst->ct_typ); fx_copy_str(&src->ct_cname, &dst->ct_cname); _fx_copy_R17C_form__ctprops_t(&src->ct_props, &dst->ct_props); dst->ct_data_start = src->ct_data_start; dst->ct_enum = src->ct_enum; FX_COPY_PTR(src->ct_ifaces, &dst->ct_ifaces); dst->ct_ifaces_id = src->ct_ifaces_id; FX_COPY_PTR(src->ct_scope, &dst->ct_scope); dst->ct_loc = src->ct_loc; } static void _fx_make_R17C_form__cdeftyp_t( struct _fx_R9Ast__id_t* r_ct_name, struct _fx_N14C_form__ctyp_t_data_t* r_ct_typ, fx_str_t* r_ct_cname, struct _fx_R17C_form__ctprops_t* r_ct_props, int_ r_ct_data_start, struct _fx_R9Ast__id_t* r_ct_enum, struct _fx_LR9Ast__id_t_data_t* r_ct_ifaces, struct _fx_R9Ast__id_t* r_ct_ifaces_id, struct _fx_LN12Ast__scope_t_data_t* r_ct_scope, struct _fx_R10Ast__loc_t* r_ct_loc, struct _fx_R17C_form__cdeftyp_t* fx_result) { fx_result->ct_name = *r_ct_name; FX_COPY_PTR(r_ct_typ, &fx_result->ct_typ); fx_copy_str(r_ct_cname, &fx_result->ct_cname); _fx_copy_R17C_form__ctprops_t(r_ct_props, &fx_result->ct_props); fx_result->ct_data_start = r_ct_data_start; fx_result->ct_enum = *r_ct_enum; FX_COPY_PTR(r_ct_ifaces, &fx_result->ct_ifaces); fx_result->ct_ifaces_id = *r_ct_ifaces_id; FX_COPY_PTR(r_ct_scope, &fx_result->ct_scope); fx_result->ct_loc = *r_ct_loc; } static void _fx_free_rR17C_form__cdeftyp_t(struct _fx_rR17C_form__cdeftyp_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR17C_form__cdeftyp_t, _fx_free_R17C_form__cdeftyp_t); } static int _fx_make_rR17C_form__cdeftyp_t( struct _fx_R17C_form__cdeftyp_t* arg, struct _fx_rR17C_form__cdeftyp_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR17C_form__cdeftyp_t, _fx_copy_R17C_form__cdeftyp_t); } static void _fx_free_Nt6option1N14C_form__cexp_t(struct _fx_Nt6option1N14C_form__cexp_t* dst) { switch (dst->tag) { case 2: _fx_free_N14C_form__cexp_t(&dst->u.Some); break; default: ; } dst->tag = 0; } static void _fx_copy_Nt6option1N14C_form__cexp_t( struct _fx_Nt6option1N14C_form__cexp_t* src, struct _fx_Nt6option1N14C_form__cexp_t* dst) { dst->tag = src->tag; switch (src->tag) { case 2: FX_COPY_PTR(src->u.Some, &dst->u.Some); break; default: dst->u = src->u; } } static void _fx_free_T2R9Ast__id_tNt6option1N14C_form__cexp_t(struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* dst) { _fx_free_Nt6option1N14C_form__cexp_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tNt6option1N14C_form__cexp_t( struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* src, struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* dst) { dst->t0 = src->t0; _fx_copy_Nt6option1N14C_form__cexp_t(&src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tNt6option1N14C_form__cexp_t( struct _fx_R9Ast__id_t* t0, struct _fx_Nt6option1N14C_form__cexp_t* t1, struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* fx_result) { fx_result->t0 = *t0; _fx_copy_Nt6option1N14C_form__cexp_t(t1, &fx_result->t1); } static void _fx_free_LT2R9Ast__id_tNt6option1N14C_form__cexp_t( struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t, _fx_free_T2R9Ast__id_tNt6option1N14C_form__cexp_t); } static int _fx_cons_LT2R9Ast__id_tNt6option1N14C_form__cexp_t( struct _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* hd, struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t* tl, bool addref_tl, struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t, _fx_copy_T2R9Ast__id_tNt6option1N14C_form__cexp_t); } static void _fx_free_R18C_form__cdefenum_t(struct _fx_R18C_form__cdefenum_t* dst) { _fx_free_LT2R9Ast__id_tNt6option1N14C_form__cexp_t(&dst->cenum_members); fx_free_str(&dst->cenum_cname); fx_free_list_simple(&dst->cenum_scope); } static void _fx_copy_R18C_form__cdefenum_t(struct _fx_R18C_form__cdefenum_t* src, struct _fx_R18C_form__cdefenum_t* dst) { dst->cenum_name = src->cenum_name; FX_COPY_PTR(src->cenum_members, &dst->cenum_members); fx_copy_str(&src->cenum_cname, &dst->cenum_cname); FX_COPY_PTR(src->cenum_scope, &dst->cenum_scope); dst->cenum_loc = src->cenum_loc; } static void _fx_make_R18C_form__cdefenum_t( struct _fx_R9Ast__id_t* r_cenum_name, struct _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t_data_t* r_cenum_members, fx_str_t* r_cenum_cname, struct _fx_LN12Ast__scope_t_data_t* r_cenum_scope, struct _fx_R10Ast__loc_t* r_cenum_loc, struct _fx_R18C_form__cdefenum_t* fx_result) { fx_result->cenum_name = *r_cenum_name; FX_COPY_PTR(r_cenum_members, &fx_result->cenum_members); fx_copy_str(r_cenum_cname, &fx_result->cenum_cname); FX_COPY_PTR(r_cenum_scope, &fx_result->cenum_scope); fx_result->cenum_loc = *r_cenum_loc; } static void _fx_free_rR18C_form__cdefenum_t(struct _fx_rR18C_form__cdefenum_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR18C_form__cdefenum_t, _fx_free_R18C_form__cdefenum_t); } static int _fx_make_rR18C_form__cdefenum_t( struct _fx_R18C_form__cdefenum_t* arg, struct _fx_rR18C_form__cdefenum_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR18C_form__cdefenum_t, _fx_copy_R18C_form__cdefenum_t); } static void _fx_free_R19C_form__cdefmacro_t(struct _fx_R19C_form__cdefmacro_t* dst) { fx_free_str(&dst->cm_cname); fx_free_list_simple(&dst->cm_args); _fx_free_LN15C_form__cstmt_t(&dst->cm_body); fx_free_list_simple(&dst->cm_scope); } static void _fx_copy_R19C_form__cdefmacro_t(struct _fx_R19C_form__cdefmacro_t* src, struct _fx_R19C_form__cdefmacro_t* dst) { dst->cm_name = src->cm_name; fx_copy_str(&src->cm_cname, &dst->cm_cname); FX_COPY_PTR(src->cm_args, &dst->cm_args); FX_COPY_PTR(src->cm_body, &dst->cm_body); FX_COPY_PTR(src->cm_scope, &dst->cm_scope); dst->cm_loc = src->cm_loc; } static void _fx_make_R19C_form__cdefmacro_t( struct _fx_R9Ast__id_t* r_cm_name, fx_str_t* r_cm_cname, struct _fx_LR9Ast__id_t_data_t* r_cm_args, struct _fx_LN15C_form__cstmt_t_data_t* r_cm_body, struct _fx_LN12Ast__scope_t_data_t* r_cm_scope, struct _fx_R10Ast__loc_t* r_cm_loc, struct _fx_R19C_form__cdefmacro_t* fx_result) { fx_result->cm_name = *r_cm_name; fx_copy_str(r_cm_cname, &fx_result->cm_cname); FX_COPY_PTR(r_cm_args, &fx_result->cm_args); FX_COPY_PTR(r_cm_body, &fx_result->cm_body); FX_COPY_PTR(r_cm_scope, &fx_result->cm_scope); fx_result->cm_loc = *r_cm_loc; } static void _fx_free_rR19C_form__cdefmacro_t(struct _fx_rR19C_form__cdefmacro_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR19C_form__cdefmacro_t, _fx_free_R19C_form__cdefmacro_t); } static int _fx_make_rR19C_form__cdefmacro_t( struct _fx_R19C_form__cdefmacro_t* arg, struct _fx_rR19C_form__cdefmacro_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR19C_form__cdefmacro_t, _fx_copy_R19C_form__cdefmacro_t); } static void _fx_free_R17C_form__cdefexn_t(struct _fx_R17C_form__cdefexn_t* dst) { fx_free_str(&dst->cexn_cname); fx_free_str(&dst->cexn_base_cname); _fx_free_N14C_form__ctyp_t(&dst->cexn_typ); fx_free_list_simple(&dst->cexn_scope); } static void _fx_copy_R17C_form__cdefexn_t(struct _fx_R17C_form__cdefexn_t* src, struct _fx_R17C_form__cdefexn_t* dst) { dst->cexn_name = src->cexn_name; fx_copy_str(&src->cexn_cname, &dst->cexn_cname); fx_copy_str(&src->cexn_base_cname, &dst->cexn_base_cname); FX_COPY_PTR(src->cexn_typ, &dst->cexn_typ); dst->cexn_std = src->cexn_std; dst->cexn_tag = src->cexn_tag; dst->cexn_data = src->cexn_data; dst->cexn_info = src->cexn_info; dst->cexn_make = src->cexn_make; FX_COPY_PTR(src->cexn_scope, &dst->cexn_scope); dst->cexn_loc = src->cexn_loc; } static void _fx_make_R17C_form__cdefexn_t( struct _fx_R9Ast__id_t* r_cexn_name, fx_str_t* r_cexn_cname, fx_str_t* r_cexn_base_cname, struct _fx_N14C_form__ctyp_t_data_t* r_cexn_typ, bool r_cexn_std, struct _fx_R9Ast__id_t* r_cexn_tag, struct _fx_R9Ast__id_t* r_cexn_data, struct _fx_R9Ast__id_t* r_cexn_info, struct _fx_R9Ast__id_t* r_cexn_make, struct _fx_LN12Ast__scope_t_data_t* r_cexn_scope, struct _fx_R10Ast__loc_t* r_cexn_loc, struct _fx_R17C_form__cdefexn_t* fx_result) { fx_result->cexn_name = *r_cexn_name; fx_copy_str(r_cexn_cname, &fx_result->cexn_cname); fx_copy_str(r_cexn_base_cname, &fx_result->cexn_base_cname); FX_COPY_PTR(r_cexn_typ, &fx_result->cexn_typ); fx_result->cexn_std = r_cexn_std; fx_result->cexn_tag = *r_cexn_tag; fx_result->cexn_data = *r_cexn_data; fx_result->cexn_info = *r_cexn_info; fx_result->cexn_make = *r_cexn_make; FX_COPY_PTR(r_cexn_scope, &fx_result->cexn_scope); fx_result->cexn_loc = *r_cexn_loc; } static void _fx_free_rR17C_form__cdefexn_t(struct _fx_rR17C_form__cdefexn_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR17C_form__cdefexn_t, _fx_free_R17C_form__cdefexn_t); } static int _fx_make_rR17C_form__cdefexn_t( struct _fx_R17C_form__cdefexn_t* arg, struct _fx_rR17C_form__cdefexn_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR17C_form__cdefexn_t, _fx_copy_R17C_form__cdefexn_t); } static void _fx_free_N15C_form__cinfo_t(struct _fx_N15C_form__cinfo_t* dst) { switch (dst->tag) { case 2: _fx_free_R17C_form__cdefval_t(&dst->u.CVal); break; case 3: _fx_free_rR17C_form__cdeffun_t(&dst->u.CFun); break; case 4: _fx_free_rR17C_form__cdeftyp_t(&dst->u.CTyp); break; case 5: _fx_free_rR17C_form__cdefexn_t(&dst->u.CExn); break; case 6: _fx_free_rR23C_form__cdefinterface_t(&dst->u.CInterface); break; case 7: _fx_free_rR18C_form__cdefenum_t(&dst->u.CEnum); break; case 8: _fx_free_R19C_form__cdeflabel_t(&dst->u.CLabel); break; case 9: _fx_free_rR19C_form__cdefmacro_t(&dst->u.CMacro); break; default: ; } dst->tag = 0; } static void _fx_copy_N15C_form__cinfo_t(struct _fx_N15C_form__cinfo_t* src, struct _fx_N15C_form__cinfo_t* dst) { dst->tag = src->tag; switch (src->tag) { case 2: _fx_copy_R17C_form__cdefval_t(&src->u.CVal, &dst->u.CVal); break; case 3: FX_COPY_PTR(src->u.CFun, &dst->u.CFun); break; case 4: FX_COPY_PTR(src->u.CTyp, &dst->u.CTyp); break; case 5: FX_COPY_PTR(src->u.CExn, &dst->u.CExn); break; case 6: FX_COPY_PTR(src->u.CInterface, &dst->u.CInterface); break; case 7: FX_COPY_PTR(src->u.CEnum, &dst->u.CEnum); break; case 8: _fx_copy_R19C_form__cdeflabel_t(&src->u.CLabel, &dst->u.CLabel); break; case 9: FX_COPY_PTR(src->u.CMacro, &dst->u.CMacro); break; default: dst->u = src->u; } } static void _fx_free_T2R9Ast__id_tN14K_form__ktyp_t(struct _fx_T2R9Ast__id_tN14K_form__ktyp_t* dst) { _fx_free_N14K_form__ktyp_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tN14K_form__ktyp_t( struct _fx_T2R9Ast__id_tN14K_form__ktyp_t* src, struct _fx_T2R9Ast__id_tN14K_form__ktyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tN14K_form__ktyp_t( struct _fx_R9Ast__id_t* t0, struct _fx_N14K_form__ktyp_t_data_t* t1, struct _fx_T2R9Ast__id_tN14K_form__ktyp_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_LT2R9Ast__id_tN14K_form__ktyp_t(struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2R9Ast__id_tN14K_form__ktyp_t, _fx_free_T2R9Ast__id_tN14K_form__ktyp_t); } static int _fx_cons_LT2R9Ast__id_tN14K_form__ktyp_t( struct _fx_T2R9Ast__id_tN14K_form__ktyp_t* hd, struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t* tl, bool addref_tl, struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2R9Ast__id_tN14K_form__ktyp_t, _fx_copy_T2R9Ast__id_tN14K_form__ktyp_t); } static void _fx_free_LN14K_form__ktyp_t(struct _fx_LN14K_form__ktyp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LN14K_form__ktyp_t, _fx_free_N14K_form__ktyp_t); } static int _fx_cons_LN14K_form__ktyp_t( struct _fx_N14K_form__ktyp_t_data_t* hd, struct _fx_LN14K_form__ktyp_t_data_t* tl, bool addref_tl, struct _fx_LN14K_form__ktyp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN14K_form__ktyp_t, FX_COPY_PTR); } static void _fx_free_T2R10Ast__loc_tS(struct _fx_T2R10Ast__loc_tS* dst) { fx_free_str(&dst->t1); } static void _fx_copy_T2R10Ast__loc_tS(struct _fx_T2R10Ast__loc_tS* src, struct _fx_T2R10Ast__loc_tS* dst) { dst->t0 = src->t0; fx_copy_str(&src->t1, &dst->t1); } static void _fx_make_T2R10Ast__loc_tS(struct _fx_R10Ast__loc_t* t0, fx_str_t* t1, struct _fx_T2R10Ast__loc_tS* fx_result) { fx_result->t0 = *t0; fx_copy_str(t1, &fx_result->t1); } static void _fx_free_N11PP__pptok_t(struct _fx_N11PP__pptok_t* dst) { switch (dst->tag) { case 1: fx_free_str(&dst->u.PPString); break; default: ; } dst->tag = 0; } static void _fx_copy_N11PP__pptok_t(struct _fx_N11PP__pptok_t* src, struct _fx_N11PP__pptok_t* dst) { dst->tag = src->tag; switch (src->tag) { case 1: fx_copy_str(&src->u.PPString, &dst->u.PPString); break; default: dst->u = src->u; } } static void _fx_free_T2N11PP__pptok_ti(struct _fx_T2N11PP__pptok_ti* dst) { _fx_free_N11PP__pptok_t(&dst->t0); } static void _fx_copy_T2N11PP__pptok_ti(struct _fx_T2N11PP__pptok_ti* src, struct _fx_T2N11PP__pptok_ti* dst) { _fx_copy_N11PP__pptok_t(&src->t0, &dst->t0); dst->t1 = src->t1; } static void _fx_make_T2N11PP__pptok_ti(struct _fx_N11PP__pptok_t* t0, int_ t1, struct _fx_T2N11PP__pptok_ti* fx_result) { _fx_copy_N11PP__pptok_t(t0, &fx_result->t0); fx_result->t1 = t1; } static void _fx_free_R11PP__state_t(struct _fx_R11PP__state_t* dst) { fx_free_arr(&dst->q); fx_free_arr(&dst->stack); fx_free_arr(&dst->pp_stack); } static void _fx_copy_R11PP__state_t(struct _fx_R11PP__state_t* src, struct _fx_R11PP__state_t* dst) { dst->space = src->space; dst->left = src->left; dst->right = src->right; dst->top = src->top; dst->bottom = src->bottom; dst->lefttotal = src->lefttotal; dst->righttotal = src->righttotal; fx_copy_arr(&src->q, &dst->q); fx_copy_arr(&src->stack, &dst->stack); fx_copy_arr(&src->pp_stack, &dst->pp_stack); dst->pp_top = src->pp_top; dst->emptystack = src->emptystack; } static void _fx_make_R11PP__state_t( int_ r_space, int_ r_left, int_ r_right, int_ r_top, int_ r_bottom, int_ r_lefttotal, int_ r_righttotal, fx_arr_t* r_q, fx_arr_t* r_stack, fx_arr_t* r_pp_stack, int_ r_pp_top, bool r_emptystack, struct _fx_R11PP__state_t* fx_result) { fx_result->space = r_space; fx_result->left = r_left; fx_result->right = r_right; fx_result->top = r_top; fx_result->bottom = r_bottom; fx_result->lefttotal = r_lefttotal; fx_result->righttotal = r_righttotal; fx_copy_arr(r_q, &fx_result->q); fx_copy_arr(r_stack, &fx_result->stack); fx_copy_arr(r_pp_stack, &fx_result->pp_stack); fx_result->pp_top = r_pp_top; fx_result->emptystack = r_emptystack; } static void _fx_free_rR11PP__state_t(struct _fx_rR11PP__state_t_data_t** dst) { FX_FREE_REF_IMPL(_fx_rR11PP__state_t, _fx_free_R11PP__state_t); } static int _fx_make_rR11PP__state_t(struct _fx_R11PP__state_t* arg, struct _fx_rR11PP__state_t_data_t** fx_result) { FX_MAKE_REF_IMPL(_fx_rR11PP__state_t, _fx_copy_R11PP__state_t); } static void _fx_free_R5PP__t(struct _fx_R5PP__t* dst) { fx_free_fp(&dst->print_f); fx_free_fp(&dst->get_f); _fx_free_rR11PP__state_t(&dst->r); } static void _fx_copy_R5PP__t(struct _fx_R5PP__t* src, struct _fx_R5PP__t* dst) { dst->margin = src->margin; dst->default_indent = src->default_indent; FX_COPY_FP(&src->print_f, &dst->print_f); FX_COPY_FP(&src->get_f, &dst->get_f); FX_COPY_PTR(src->r, &dst->r); } static void _fx_make_R5PP__t( int_ r_margin, int_ r_default_indent, struct _fx_FPv1S* r_print_f, struct _fx_FPLS0* r_get_f, struct _fx_rR11PP__state_t_data_t* r_r, struct _fx_R5PP__t* fx_result) { fx_result->margin = r_margin; fx_result->default_indent = r_default_indent; FX_COPY_FP(r_print_f, &fx_result->print_f); FX_COPY_FP(r_get_f, &fx_result->get_f); FX_COPY_PTR(r_r, &fx_result->r); } static void _fx_free_N14K_form__klit_t(struct _fx_N14K_form__klit_t* dst) { switch (dst->tag) { case 5: fx_free_str(&dst->u.KLitString); break; case 8: _fx_free_N14K_form__ktyp_t(&dst->u.KLitNil); break; default: ; } dst->tag = 0; } static void _fx_copy_N14K_form__klit_t(struct _fx_N14K_form__klit_t* src, struct _fx_N14K_form__klit_t* dst) { dst->tag = src->tag; switch (src->tag) { case 5: fx_copy_str(&src->u.KLitString, &dst->u.KLitString); break; case 8: FX_COPY_PTR(src->u.KLitNil, &dst->u.KLitNil); break; default: dst->u = src->u; } } static void _fx_free_T2LN14K_form__ktyp_tN14K_form__ktyp_t(struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t* dst) { _fx_free_LN14K_form__ktyp_t(&dst->t0); _fx_free_N14K_form__ktyp_t(&dst->t1); } static void _fx_copy_T2LN14K_form__ktyp_tN14K_form__ktyp_t( struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t* src, struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2LN14K_form__ktyp_tN14K_form__ktyp_t( struct _fx_LN14K_form__ktyp_t_data_t* t0, struct _fx_N14K_form__ktyp_t_data_t* t1, struct _fx_T2LN14K_form__ktyp_tN14K_form__ktyp_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t(struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t* dst) { _fx_free_LT2R9Ast__id_tN14K_form__ktyp_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t( struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t* src, struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t( struct _fx_R9Ast__id_t* t0, struct _fx_LT2R9Ast__id_tN14K_form__ktyp_t_data_t* t1, struct _fx_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_T2iN14K_form__ktyp_t(struct _fx_T2iN14K_form__ktyp_t* dst) { _fx_free_N14K_form__ktyp_t(&dst->t1); } static void _fx_copy_T2iN14K_form__ktyp_t(struct _fx_T2iN14K_form__ktyp_t* src, struct _fx_T2iN14K_form__ktyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2iN14K_form__ktyp_t( int_ t0, struct _fx_N14K_form__ktyp_t_data_t* t1, struct _fx_T2iN14K_form__ktyp_t* fx_result) { fx_result->t0 = t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_N14K_form__ktyp_t(struct _fx_N14K_form__ktyp_t_data_t** dst) { if (*dst && FX_DECREF((*dst)->rc) == 1) { switch ((*dst)->tag) { case 11: _fx_free_T2LN14K_form__ktyp_tN14K_form__ktyp_t(&(*dst)->u.KTypFun); break; case 12: _fx_free_LN14K_form__ktyp_t(&(*dst)->u.KTypTuple); break; case 13: _fx_free_T2R9Ast__id_tLT2R9Ast__id_tN14K_form__ktyp_t(&(*dst)->u.KTypRecord); break; case 15: _fx_free_T2iN14K_form__ktyp_t(&(*dst)->u.KTypArray); break; case 16: _fx_free_N14K_form__ktyp_t(&(*dst)->u.KTypVector); break; case 17: _fx_free_N14K_form__ktyp_t(&(*dst)->u.KTypList); break; case 18: _fx_free_N14K_form__ktyp_t(&(*dst)->u.KTypRef); break; default: ; } fx_free(*dst); } *dst = 0; } static void _fx_free_Nt6option1N14C_form__ctyp_t(struct _fx_Nt6option1N14C_form__ctyp_t* dst) { switch (dst->tag) { case 2: _fx_free_N14C_form__ctyp_t(&dst->u.Some); break; default: ; } dst->tag = 0; } static void _fx_copy_Nt6option1N14C_form__ctyp_t( struct _fx_Nt6option1N14C_form__ctyp_t* src, struct _fx_Nt6option1N14C_form__ctyp_t* dst) { dst->tag = src->tag; switch (src->tag) { case 2: FX_COPY_PTR(src->u.Some, &dst->u.Some); break; default: dst->u = src->u; } } static void _fx_free_T2SR10Ast__loc_t(struct _fx_T2SR10Ast__loc_t* dst) { fx_free_str(&dst->t0); } static void _fx_copy_T2SR10Ast__loc_t(struct _fx_T2SR10Ast__loc_t* src, struct _fx_T2SR10Ast__loc_t* dst) { fx_copy_str(&src->t0, &dst->t0); dst->t1 = src->t1; } static void _fx_make_T2SR10Ast__loc_t(fx_str_t* t0, struct _fx_R10Ast__loc_t* t1, struct _fx_T2SR10Ast__loc_t* fx_result) { fx_copy_str(t0, &fx_result->t0); fx_result->t1 = *t1; } static void _fx_free_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t( struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* dst) { _fx_free_LT2R9Ast__id_tN14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t( struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* src, struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t( struct _fx_Nt6option1R9Ast__id_t* t0, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* t1, struct _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_LN14C_form__ctyp_t(struct _fx_LN14C_form__ctyp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LN14C_form__ctyp_t, _fx_free_N14C_form__ctyp_t); } static int _fx_cons_LN14C_form__ctyp_t( struct _fx_N14C_form__ctyp_t_data_t* hd, struct _fx_LN14C_form__ctyp_t_data_t* tl, bool addref_tl, struct _fx_LN14C_form__ctyp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN14C_form__ctyp_t, FX_COPY_PTR); } static void _fx_free_T2LN14C_form__ctyp_tN14C_form__ctyp_t(struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t* dst) { _fx_free_LN14C_form__ctyp_t(&dst->t0); _fx_free_N14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T2LN14C_form__ctyp_tN14C_form__ctyp_t( struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t* src, struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2LN14C_form__ctyp_tN14C_form__ctyp_t( struct _fx_LN14C_form__ctyp_t_data_t* t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); } static int _fx_cons_LN19C_form__ctyp_attr_t( struct _fx_N19C_form__ctyp_attr_t* hd, struct _fx_LN19C_form__ctyp_attr_t_data_t* tl, bool addref_tl, struct _fx_LN19C_form__ctyp_attr_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN19C_form__ctyp_attr_t, FX_COPY_SIMPLE_BY_PTR); } static void _fx_free_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t(struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* dst) { fx_free_list_simple(&dst->t0); _fx_free_N14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t( struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* src, struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t( struct _fx_LN19C_form__ctyp_attr_t_data_t* t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_T2iN14C_form__ctyp_t(struct _fx_T2iN14C_form__ctyp_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T2iN14C_form__ctyp_t(struct _fx_T2iN14C_form__ctyp_t* src, struct _fx_T2iN14C_form__ctyp_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2iN14C_form__ctyp_t( int_ t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_T2iN14C_form__ctyp_t* fx_result) { fx_result->t0 = t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_N14C_form__ctyp_t(struct _fx_N14C_form__ctyp_t_data_t** dst) { if (*dst && FX_DECREF((*dst)->rc) == 1) { switch ((*dst)->tag) { case 13: _fx_free_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t(&(*dst)->u.CTypStruct); break; case 14: _fx_free_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t(&(*dst)->u.CTypUnion); break; case 15: _fx_free_T2LN14C_form__ctyp_tN14C_form__ctyp_t(&(*dst)->u.CTypFunRawPtr); break; case 16: _fx_free_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t(&(*dst)->u.CTypRawPtr); break; case 17: _fx_free_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t(&(*dst)->u.CTypRawArray); break; case 18: _fx_free_T2iN14C_form__ctyp_t(&(*dst)->u.CTypArray); break; case 19: _fx_free_N14C_form__ctyp_t(&(*dst)->u.CTypVector); break; default: ; } fx_free(*dst); } *dst = 0; } static void _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->t0); } static void _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); dst->t1 = src->t1; } static void _fx_make_T2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__ctyp_t_data_t* t0, struct _fx_R10Ast__loc_t* t1, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); fx_result->t1 = *t1; } static void _fx_free_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { dst->t0 = src->t0; _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_R9Ast__id_t* t0, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t1, struct _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { fx_result->t0 = *t0; _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t1, &fx_result->t1); } static void _fx_free_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14K_form__klit_t(&dst->t0); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t1); } static void _fx_copy_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_copy_N14K_form__klit_t(&src->t0, &dst->t0); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t1, &dst->t1); } static void _fx_make_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14K_form__klit_t* t0, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t1, struct _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { _fx_copy_N14K_form__klit_t(t0, &fx_result->t0); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t1, &fx_result->t1); } static void _fx_free_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t1); _fx_free_N14C_form__cexp_t(&dst->t2); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t3); } static void _fx_copy_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); FX_COPY_PTR(src->t2, &dst->t2); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t3, &dst->t3); } static void _fx_make_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N17C_form__cbinary_t* t0, struct _fx_N14C_form__cexp_t_data_t* t1, struct _fx_N14C_form__cexp_t_data_t* t2, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t3, struct _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); FX_COPY_PTR(t2, &fx_result->t2); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t3, &fx_result->t3); } static void _fx_free_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t1); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t2); } static void _fx_copy_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t2, &dst->t2); } static void _fx_make_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N16C_form__cunary_t* t0, struct _fx_N14C_form__cexp_t_data_t* t1, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t2, struct _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t2, &fx_result->t2); } static void _fx_free_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t2); } static void _fx_copy_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); dst->t1 = src->t1; _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t2, &dst->t2); } static void _fx_make_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_R9Ast__id_t* t1, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t2, struct _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); fx_result->t1 = *t1; _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t2, &fx_result->t2); } static void _fx_free_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_N14C_form__ctyp_t(&dst->t1); } static void _fx_copy_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); dst->t2 = src->t2; } static void _fx_make_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_N14C_form__ctyp_t_data_t* t1, struct _fx_R10Ast__loc_t* t2, struct _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); fx_result->t2 = *t2; } static void _fx_free_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_N14C_form__cexp_t(&dst->t1); _fx_free_N14C_form__cexp_t(&dst->t2); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t3); } static void _fx_copy_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); FX_COPY_PTR(src->t2, &dst->t2); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t3, &dst->t3); } static void _fx_make_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_N14C_form__cexp_t_data_t* t1, struct _fx_N14C_form__cexp_t_data_t* t2, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t3, struct _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); FX_COPY_PTR(t2, &fx_result->t2); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t3, &fx_result->t3); } static void _fx_free_LN14C_form__cexp_t(struct _fx_LN14C_form__cexp_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LN14C_form__cexp_t, _fx_free_N14C_form__cexp_t); } static int _fx_cons_LN14C_form__cexp_t( struct _fx_N14C_form__cexp_t_data_t* hd, struct _fx_LN14C_form__cexp_t_data_t* tl, bool addref_tl, struct _fx_LN14C_form__cexp_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LN14C_form__cexp_t, FX_COPY_PTR); } static void _fx_free_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_LN14C_form__cexp_t(&dst->t1); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t2); } static void _fx_copy_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t2, &dst->t2); } static void _fx_make_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_LN14C_form__cexp_t_data_t* t1, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t2, struct _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t2, &fx_result->t2); } static void _fx_free_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { _fx_free_LN14C_form__cexp_t(&dst->t0); _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&dst->t1); } static void _fx_copy_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* src, struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(&src->t1, &dst->t1); } static void _fx_make_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_LN14C_form__cexp_t_data_t* t0, struct _fx_T2N14C_form__ctyp_tR10Ast__loc_t* t1, struct _fx_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); _fx_copy_T2N14C_form__ctyp_tR10Ast__loc_t(t1, &fx_result->t1); } static void _fx_free_N14C_form__cexp_t(struct _fx_N14C_form__cexp_t_data_t** dst) { if (*dst && FX_DECREF((*dst)->rc) == 1) { switch ((*dst)->tag) { case 1: _fx_free_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpIdent); break; case 2: _fx_free_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpLit); break; case 3: _fx_free_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t( &(*dst)->u.CExpBinary); break; case 4: _fx_free_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpUnary); break; case 5: _fx_free_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpMem); break; case 6: _fx_free_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpArrow); break; case 7: _fx_free_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpCast); break; case 8: _fx_free_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpTernary); break; case 9: _fx_free_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpCall); break; case 10: _fx_free_T2LN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpInit); break; case 11: _fx_free_T2N14C_form__ctyp_tR10Ast__loc_t(&(*dst)->u.CExpTyp); break; case 12: _fx_free_T2SR10Ast__loc_t(&(*dst)->u.CExpCCode); break; default: ; } fx_free(*dst); } *dst = 0; } static void _fx_free_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t(struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t* dst) { _fx_free_Nt6option1N14C_form__cexp_t(&dst->t0); } static void _fx_copy_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t( struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t* src, struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t* dst) { _fx_copy_Nt6option1N14C_form__cexp_t(&src->t0, &dst->t0); dst->t1 = src->t1; } static void _fx_make_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t( struct _fx_Nt6option1N14C_form__cexp_t* t0, struct _fx_R10Ast__loc_t* t1, struct _fx_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t* fx_result) { _fx_copy_Nt6option1N14C_form__cexp_t(t0, &fx_result->t0); fx_result->t1 = *t1; } static void _fx_free_T2LN15C_form__cstmt_tR10Ast__loc_t(struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_LN15C_form__cstmt_t(&dst->t0); } static void _fx_copy_T2LN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); dst->t1 = src->t1; } static void _fx_make_T2LN15C_form__cstmt_tR10Ast__loc_t( struct _fx_LN15C_form__cstmt_t_data_t* t0, struct _fx_R10Ast__loc_t* t1, struct _fx_T2LN15C_form__cstmt_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); fx_result->t1 = *t1; } static void _fx_free_T2R9Ast__id_tN15C_form__cstmt_t(struct _fx_T2R9Ast__id_tN15C_form__cstmt_t* dst) { _fx_free_N15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T2R9Ast__id_tN15C_form__cstmt_t( struct _fx_T2R9Ast__id_tN15C_form__cstmt_t* src, struct _fx_T2R9Ast__id_tN15C_form__cstmt_t* dst) { dst->t0 = src->t0; FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2R9Ast__id_tN15C_form__cstmt_t( struct _fx_R9Ast__id_t* t0, struct _fx_N15C_form__cstmt_t_data_t* t1, struct _fx_T2R9Ast__id_tN15C_form__cstmt_t* fx_result) { fx_result->t0 = *t0; FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_N15C_form__cstmt_t(&dst->t1); _fx_free_N15C_form__cstmt_t(&dst->t2); } static void _fx_copy_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); FX_COPY_PTR(src->t2, &dst->t2); dst->t3 = src->t3; } static void _fx_make_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_N15C_form__cstmt_t_data_t* t1, struct _fx_N15C_form__cstmt_t_data_t* t2, struct _fx_R10Ast__loc_t* t3, struct _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); FX_COPY_PTR(t2, &fx_result->t2); fx_result->t3 = *t3; } static void _fx_free_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_Nt6option1N14C_form__ctyp_t(&dst->t0); _fx_free_LN14C_form__cexp_t(&dst->t1); _fx_free_Nt6option1N14C_form__cexp_t(&dst->t2); _fx_free_LN14C_form__cexp_t(&dst->t3); _fx_free_N15C_form__cstmt_t(&dst->t4); } static void _fx_copy_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_copy_Nt6option1N14C_form__ctyp_t(&src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); _fx_copy_Nt6option1N14C_form__cexp_t(&src->t2, &dst->t2); FX_COPY_PTR(src->t3, &dst->t3); FX_COPY_PTR(src->t4, &dst->t4); dst->t5 = src->t5; } static void _fx_make_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_Nt6option1N14C_form__ctyp_t* t0, struct _fx_LN14C_form__cexp_t_data_t* t1, struct _fx_Nt6option1N14C_form__cexp_t* t2, struct _fx_LN14C_form__cexp_t_data_t* t3, struct _fx_N15C_form__cstmt_t_data_t* t4, struct _fx_R10Ast__loc_t* t5, struct _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* fx_result) { _fx_copy_Nt6option1N14C_form__ctyp_t(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); _fx_copy_Nt6option1N14C_form__cexp_t(t2, &fx_result->t2); FX_COPY_PTR(t3, &fx_result->t3); FX_COPY_PTR(t4, &fx_result->t4); fx_result->t5 = *t5; } static void _fx_free_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_N15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); dst->t2 = src->t2; } static void _fx_make_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_N15C_form__cstmt_t_data_t* t1, struct _fx_R10Ast__loc_t* t2, struct _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); fx_result->t2 = *t2; } static void _fx_free_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t( struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t* dst) { _fx_free_N15C_form__cstmt_t(&dst->t0); _fx_free_N14C_form__cexp_t(&dst->t1); } static void _fx_copy_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t( struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t* src, struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); dst->t2 = src->t2; } static void _fx_make_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t( struct _fx_N15C_form__cstmt_t_data_t* t0, struct _fx_N14C_form__cexp_t_data_t* t1, struct _fx_R10Ast__loc_t* t2, struct _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); fx_result->t2 = *t2; } static void _fx_free_T2LN14C_form__cexp_tLN15C_form__cstmt_t(struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* dst) { _fx_free_LN14C_form__cexp_t(&dst->t0); _fx_free_LN15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T2LN14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* src, struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2LN14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_LN14C_form__cexp_t_data_t* t0, struct _fx_LN15C_form__cstmt_t_data_t* t1, struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_LT2LN14C_form__cexp_tLN15C_form__cstmt_t(struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t, _fx_free_T2LN14C_form__cexp_tLN15C_form__cstmt_t); } static int _fx_cons_LT2LN14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* hd, struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t* tl, bool addref_tl, struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t, _fx_copy_T2LN14C_form__cexp_tLN15C_form__cstmt_t); } static void _fx_free_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_LT2LN14C_form__cexp_tLN15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); dst->t2 = src->t2; } static void _fx_make_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t_data_t* t1, struct _fx_R10Ast__loc_t* t2, struct _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); fx_result->t2 = *t2; } static void _fx_free_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t( struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t* dst) { _fx_free_N14C_form__ctyp_t(&dst->t0); _fx_free_Nt6option1N14C_form__cexp_t(&dst->t2); } static void _fx_copy_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t( struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t* src, struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); dst->t1 = src->t1; _fx_copy_Nt6option1N14C_form__cexp_t(&src->t2, &dst->t2); dst->t3 = src->t3; } static void _fx_make_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t( struct _fx_N14C_form__ctyp_t_data_t* t0, struct _fx_R9Ast__id_t* t1, struct _fx_Nt6option1N14C_form__cexp_t* t2, struct _fx_R10Ast__loc_t* t3, struct _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); fx_result->t1 = *t1; _fx_copy_Nt6option1N14C_form__cexp_t(t2, &fx_result->t2); fx_result->t3 = *t3; } static void _fx_free_T2N14C_form__cexp_tLN15C_form__cstmt_t(struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* dst) { _fx_free_N14C_form__cexp_t(&dst->t0); _fx_free_LN15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T2N14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* src, struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); } static void _fx_make_T2N14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_N14C_form__cexp_t_data_t* t0, struct _fx_LN15C_form__cstmt_t_data_t* t1, struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); } static void _fx_free_LT2N14C_form__cexp_tLN15C_form__cstmt_t(struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t** dst) { FX_FREE_LIST_IMPL(_fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t, _fx_free_T2N14C_form__cexp_tLN15C_form__cstmt_t); } static int _fx_cons_LT2N14C_form__cexp_tLN15C_form__cstmt_t( struct _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* hd, struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t* tl, bool addref_tl, struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t** fx_result) { FX_MAKE_LIST_IMPL(_fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t, _fx_copy_T2N14C_form__cexp_tLN15C_form__cstmt_t); } static void _fx_free_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t* dst) { _fx_free_LT2N14C_form__cexp_tLN15C_form__cstmt_t(&dst->t0); _fx_free_LN15C_form__cstmt_t(&dst->t1); } static void _fx_copy_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t* src, struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t* dst) { FX_COPY_PTR(src->t0, &dst->t0); FX_COPY_PTR(src->t1, &dst->t1); dst->t2 = src->t2; } static void _fx_make_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t( struct _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t_data_t* t0, struct _fx_LN15C_form__cstmt_t_data_t* t1, struct _fx_R10Ast__loc_t* t2, struct _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t* fx_result) { FX_COPY_PTR(t0, &fx_result->t0); FX_COPY_PTR(t1, &fx_result->t1); fx_result->t2 = *t2; } static void _fx_free_N15C_form__cstmt_t(struct _fx_N15C_form__cstmt_t_data_t** dst) { if (*dst && FX_DECREF((*dst)->rc) == 1) { switch ((*dst)->tag) { case 2: _fx_free_T2SR10Ast__loc_t(&(*dst)->u.CComment); break; case 3: _fx_free_N14C_form__cexp_t(&(*dst)->u.CExp); break; case 6: _fx_free_T2Nt6option1N14C_form__cexp_tR10Ast__loc_t(&(*dst)->u.CStmtReturn); break; case 7: _fx_free_T2LN15C_form__cstmt_tR10Ast__loc_t(&(*dst)->u.CStmtBlock); break; case 8: _fx_free_T2R9Ast__id_tN15C_form__cstmt_t(&(*dst)->u.CStmtSync); break; case 9: _fx_free_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t(&(*dst)->u.CStmtIf); break; case 12: _fx_free_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t( &(*dst)->u.CStmtFor); break; case 13: _fx_free_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t(&(*dst)->u.CStmtWhile); break; case 14: _fx_free_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t(&(*dst)->u.CStmtDoWhile); break; case 15: _fx_free_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t(&(*dst)->u.CStmtSwitch); break; case 16: _fx_free_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t(&(*dst)->u.CDefVal); break; case 17: _fx_free_rR17C_form__cdeffun_t(&(*dst)->u.CDefFun); break; case 18: _fx_free_rR17C_form__cdeftyp_t(&(*dst)->u.CDefTyp); break; case 21: _fx_free_rR18C_form__cdefenum_t(&(*dst)->u.CDefEnum); break; case 22: _fx_free_rR23C_form__cdefinterface_t(&(*dst)->u.CDefInterface); break; case 23: _fx_free_rR19C_form__cdefmacro_t(&(*dst)->u.CMacroDef); break; case 25: _fx_free_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t(&(*dst)->u.CMacroIf); break; case 26: _fx_free_T2SR10Ast__loc_t(&(*dst)->u.CMacroInclude); break; case 27: _fx_free_T2SR10Ast__loc_t(&(*dst)->u.CMacroPragma); break; default: ; } fx_free(*dst); } *dst = 0; } static void _fx_free_T3SiN13C_pp__assoc_t(struct _fx_T3SiN13C_pp__assoc_t* dst) { fx_free_str(&dst->t0); } static void _fx_copy_T3SiN13C_pp__assoc_t(struct _fx_T3SiN13C_pp__assoc_t* src, struct _fx_T3SiN13C_pp__assoc_t* dst) { fx_copy_str(&src->t0, &dst->t0); dst->t1 = src->t1; dst->t2 = src->t2; } static void _fx_make_T3SiN13C_pp__assoc_t( fx_str_t* t0, int_ t1, struct _fx_N13C_pp__assoc_t* t2, struct _fx_T3SiN13C_pp__assoc_t* fx_result) { fx_copy_str(t0, &fx_result->t0); fx_result->t1 = t1; fx_result->t2 = *t2; } _fx_Nt6option1R9Ast__id_t _fx_g10C_pp__None = { 1 }; _fx_N19C_form__ctyp_attr_t _fx_g15C_pp__CTypConst = { 1 }; _fx_N19C_form__ctyp_attr_t _fx_g18C_pp__CTypVolatile = { 2 }; _fx_N19C_form__ctyp_attr_t _fx_g16C_pp__CTypStatic = { 3 }; _fx_N13C_pp__assoc_t _fx_g15C_pp__AssocLeft = { 1 }; _fx_N13C_pp__assoc_t _fx_g16C_pp__AssocRight = { 2 }; FX_EXTERN_C int _fx_M3AstFM6__eq__B2RM4id_tRM4id_t( struct _fx_R9Ast__id_t* a_0, struct _fx_R9Ast__id_t* b_0, bool* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t( struct _fx_R9Ast__id_t* n_0, struct _fx_R10Ast__loc_t* loc_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM3strv2RM1tS(struct _fx_R5PP__t* pp_0, fx_str_t* s_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM5beginv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M6C_formFM9ctyp2str_S2N14C_form__ctyp_tR10Ast__loc_t( struct _fx_N14C_form__ctyp_t_data_t* t_0, struct _fx_R10Ast__loc_t* loc_0, fx_str_t* fx_result, void* fx_fv); static int _fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M3AstFM11compile_errE2RM5loc_tS( struct _fx_R10Ast__loc_t* loc_0, fx_str_t* msg_0, fx_exn_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM5spacev1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); static int _fx_M4C_ppFM10pr_id_opt_v4BNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( bool add_space_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM3cutv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM3endv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); static int _fx_M4C_ppFM9pr_structv7SNt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_tSNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( fx_str_t* prefix_0, struct _fx_Nt6option1R9Ast__id_t* n_opt_0, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* elems_0, fx_str_t* suffix_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M6C_formFM6cinfo_N15C_form__cinfo_t2R9Ast__id_tR10Ast__loc_t( struct _fx_R9Ast__id_t* i_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_N15C_form__cinfo_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM7newlinev1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM8newlineuv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_F3ordi1C(char_ c_0, int_* fx_result, void* fx_fv); FX_EXTERN_C int _fx_F6stringS1i(int_ a, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M6StringFM5splitLS3SCB( fx_str_t* s_0, char_ c_0, bool allow_empty_0, struct _fx_LS_data_t** fx_result, void* fx_fv); FX_EXTERN_C int _fx_M6StringFM7escapedS2SB(fx_str_t* s_0, bool quotes_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C bool _fx_M6StringFM8endswithB2SC(fx_str_t* s, char_ suffix, void* fx_fv); FX_EXTERN_C int _fx_M6K_formFM8klit2strS3N14K_form__klit_tBR10Ast__loc_t( struct _fx_N14K_form__klit_t* lit_0, bool cmode_0, struct _fx_R10Ast__loc_t* loc_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M4C_ppFM8pp_elistv2R5PP__tLN14C_form__cexp_t( struct _fx_R5PP__t* pp_0, struct _fx_LN14C_form__cexp_t_data_t* el_0, void* fx_fv); FX_EXTERN_C int _fx_M6StringFM5stripS1S(fx_str_t* s, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM6beginvv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM6break0v1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM6beginvv2RM1ti(struct _fx_R5PP__t* pp_0, int_ indent_0, void* fx_fv); FX_EXTERN_C int _fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t( struct _fx_R5PP__t* pp_0, struct _fx_N15C_form__cstmt_t_data_t* s_0, void* fx_fv); FX_EXTERN_C_VAL(struct _fx_R18Options__options_t _fx_g12Options__opt) FX_EXTERN_C_VAL(struct _fx_R9Ast__id_t _fx_g9Ast__noid) FX_EXTERN_C int _fx_M3AstFM2ppS1RM4id_t(struct _fx_R9Ast__id_t* i_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M6StringFM7replaceS3SSS( fx_str_t* s, fx_str_t* substr, fx_str_t* new_substr, fx_str_t* fx_result, void* fx_fv); static int _fx_M4C_ppFM16print_cascade_ifv5SN14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR5PP__t( fx_str_t* prefix_0, struct _fx_N14C_form__cexp_t_data_t* e_0, struct _fx_N15C_form__cstmt_t_data_t* s1_0, struct _fx_N15C_form__cstmt_t_data_t* s2_0, struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM6breakuv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_F7__mul__S2Ci(char_ c, int_ n, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M6C_formFM13get_idc_cnameS2R9Ast__id_tR10Ast__loc_t( struct _fx_R9Ast__id_t* i_0, struct _fx_R10Ast__loc_t* loc_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM21pprint_to_string_listRM1t2ii( int_ margin_0, int_ default_indent_0, struct _fx_R5PP__t* fx_result, void* fx_fv); FX_EXTERN_C int _fx_M2PPFM5flushv1RM1t(struct _fx_R5PP__t* pp_0, void* fx_fv); FX_EXTERN_C int _fx_F12join_embraceS4SSSLS( fx_str_t* begin_0, fx_str_t* end_0, fx_str_t* sep_0, struct _fx_LS_data_t* strs_0, fx_str_t* fx_result, void* fx_fv); FX_EXTERN_C void _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t( struct _fx_R9Ast__id_t* arg0, struct _fx_Nt6option1R9Ast__id_t* fx_result) { fx_result->tag = 2; fx_result->u.Some = *arg0; } FX_EXTERN_C int _fx_M4C_ppFM6__ne__B2R9Ast__id_tR9Ast__id_t( struct _fx_R9Ast__id_t* a_0, struct _fx_R9Ast__id_t* b_0, bool* fx_result, void* fx_fv) { int fx_status = 0; bool res_0; FX_CALL(_fx_M3AstFM6__eq__B2RM4id_tRM4id_t(a_0, b_0, &res_0, 0), _fx_cleanup); *fx_result = !res_0; _fx_cleanup: ; return fx_status; } FX_EXTERN_C int_ _fx_M4C_ppFM6lengthi1LN15C_form__cstmt_t(struct _fx_LN15C_form__cstmt_t_data_t* l, void* fx_fv) { return fx_list_length(l); } FX_EXTERN_C int_ _fx_M4C_ppFM6lengthi1LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t( struct _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t_data_t* l, void* fx_fv) { return fx_list_length(l); } FX_EXTERN_C int_ _fx_M4C_ppFM6lengthi1LS(struct _fx_LS_data_t* l, void* fx_fv) { return fx_list_length(l); } FX_EXTERN_C int_ _fx_M4C_ppFM6lengthi1LN14C_form__ctyp_t(struct _fx_LN14C_form__ctyp_t_data_t* l, void* fx_fv) { return fx_list_length(l); } FX_EXTERN_C int _fx_M4C_ppFM6stringS1S(fx_str_t* a_0, fx_str_t* fx_result, void* fx_fv) { int fx_status = 0; fx_copy_str(a_0, fx_result); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8length1_i1LN15C_form__cstmt_t( struct _fx_LN15C_form__cstmt_t_data_t* l_0, int_* fx_result, void* fx_fv) { int fx_status = 0; *fx_result = _fx_M4C_ppFM6lengthi1LN15C_form__cstmt_t(l_0, 0); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8length1_i1LS(struct _fx_LS_data_t* l_0, int_* fx_result, void* fx_fv) { int fx_status = 0; *fx_result = _fx_M4C_ppFM6lengthi1LS(l_0, 0); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8length1_i1LN14C_form__ctyp_t( struct _fx_LN14C_form__ctyp_t_data_t* l_0, int_* fx_result, void* fx_fv) { int fx_status = 0; *fx_result = _fx_M4C_ppFM6lengthi1LN14C_form__ctyp_t(l_0, 0); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t( struct _fx_LN19C_form__ctyp_attr_t_data_t* l_0, struct _fx_N19C_form__ctyp_attr_t* a_0, bool* fx_result, void* fx_fv) { int fx_status = 0; bool __fold_result___0 = false; _fx_LN19C_form__ctyp_attr_t lst_0 = l_0; for (; lst_0; lst_0 = lst_0->tl) { _fx_N19C_form__ctyp_attr_t* b_0 = &lst_0->hd; if (a_0->tag == b_0->tag) { __fold_result___0 = true; FX_BREAK(_fx_catch_0); } _fx_catch_0: ; FX_CHECK_BREAK(); FX_CHECK_EXN(_fx_cleanup); } *fx_result = __fold_result___0; _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM10binop2str_T3SiN13C_pp__assoc_t1N17C_form__cbinary_t( struct _fx_N17C_form__cbinary_t* bop_0, struct _fx_T3SiN13C_pp__assoc_t* fx_result, void* fx_fv) { int fx_status = 0; int tag_0 = bop_0->tag; if (tag_0 == 14) { fx_str_t slit_0 = FX_MAKE_STR(""); _fx_make_T3SiN13C_pp__assoc_t(&slit_0, 1400, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 3) { fx_str_t slit_1 = FX_MAKE_STR("*"); _fx_make_T3SiN13C_pp__assoc_t(&slit_1, 1200, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 4) { fx_str_t slit_2 = FX_MAKE_STR("/"); _fx_make_T3SiN13C_pp__assoc_t(&slit_2, 1200, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 5) { fx_str_t slit_3 = FX_MAKE_STR("%"); _fx_make_T3SiN13C_pp__assoc_t(&slit_3, 1200, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 1) { fx_str_t slit_4 = FX_MAKE_STR("+"); _fx_make_T3SiN13C_pp__assoc_t(&slit_4, 1100, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 2) { fx_str_t slit_5 = FX_MAKE_STR("-"); _fx_make_T3SiN13C_pp__assoc_t(&slit_5, 1100, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 6) { fx_str_t slit_6 = FX_MAKE_STR("<<"); _fx_make_T3SiN13C_pp__assoc_t(&slit_6, 1000, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 7) { fx_str_t slit_7 = FX_MAKE_STR(">>"); _fx_make_T3SiN13C_pp__assoc_t(&slit_7, 1000, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 3) { fx_str_t slit_8 = FX_MAKE_STR("<"); _fx_make_T3SiN13C_pp__assoc_t(&slit_8, 900, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 4) { fx_str_t slit_9 = FX_MAKE_STR("<="); _fx_make_T3SiN13C_pp__assoc_t(&slit_9, 900, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 6) { fx_str_t slit_10 = FX_MAKE_STR(">"); _fx_make_T3SiN13C_pp__assoc_t(&slit_10, 900, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 5) { fx_str_t slit_11 = FX_MAKE_STR(">="); _fx_make_T3SiN13C_pp__assoc_t(&slit_11, 900, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 1) { fx_str_t slit_12 = FX_MAKE_STR("=="); _fx_make_T3SiN13C_pp__assoc_t(&slit_12, 800, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 13) { if (bop_0->u.COpCmp.tag == 2) { fx_str_t slit_13 = FX_MAKE_STR("!="); _fx_make_T3SiN13C_pp__assoc_t(&slit_13, 800, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } } if (tag_0 == 8) { fx_str_t slit_14 = FX_MAKE_STR("&"); _fx_make_T3SiN13C_pp__assoc_t(&slit_14, 700, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 10) { fx_str_t slit_15 = FX_MAKE_STR("^"); _fx_make_T3SiN13C_pp__assoc_t(&slit_15, 600, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 9) { fx_str_t slit_16 = FX_MAKE_STR("|"); _fx_make_T3SiN13C_pp__assoc_t(&slit_16, 500, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 11) { fx_str_t slit_17 = FX_MAKE_STR("&&"); _fx_make_T3SiN13C_pp__assoc_t(&slit_17, 400, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 12) { fx_str_t slit_18 = FX_MAKE_STR("||"); _fx_make_T3SiN13C_pp__assoc_t(&slit_18, 300, &_fx_g15C_pp__AssocLeft, fx_result); goto _fx_endmatch_0; } if (tag_0 == 15) { fx_str_t slit_19 = FX_MAKE_STR("="); _fx_make_T3SiN13C_pp__assoc_t(&slit_19, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 16) { fx_str_t slit_20 = FX_MAKE_STR("+="); _fx_make_T3SiN13C_pp__assoc_t(&slit_20, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 17) { fx_str_t slit_21 = FX_MAKE_STR("-="); _fx_make_T3SiN13C_pp__assoc_t(&slit_21, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 18) { fx_str_t slit_22 = FX_MAKE_STR("*="); _fx_make_T3SiN13C_pp__assoc_t(&slit_22, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 19) { fx_str_t slit_23 = FX_MAKE_STR("/="); _fx_make_T3SiN13C_pp__assoc_t(&slit_23, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 20) { fx_str_t slit_24 = FX_MAKE_STR("%="); _fx_make_T3SiN13C_pp__assoc_t(&slit_24, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 21) { fx_str_t slit_25 = FX_MAKE_STR("<<="); _fx_make_T3SiN13C_pp__assoc_t(&slit_25, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 22) { fx_str_t slit_26 = FX_MAKE_STR(">>="); _fx_make_T3SiN13C_pp__assoc_t(&slit_26, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 23) { fx_str_t slit_27 = FX_MAKE_STR("&="); _fx_make_T3SiN13C_pp__assoc_t(&slit_27, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 24) { fx_str_t slit_28 = FX_MAKE_STR("|="); _fx_make_T3SiN13C_pp__assoc_t(&slit_28, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } if (tag_0 == 25) { fx_str_t slit_29 = FX_MAKE_STR("^="); _fx_make_T3SiN13C_pp__assoc_t(&slit_29, 100, &_fx_g16C_pp__AssocRight, fx_result); goto _fx_endmatch_0; } FX_FAST_THROW(FX_EXN_NoMatchError, _fx_cleanup); _fx_endmatch_0: ; _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM9unop2str_T3SiN13C_pp__assoc_t1N16C_form__cunary_t( struct _fx_N16C_form__cunary_t* uop_0, struct _fx_T3SiN13C_pp__assoc_t* fx_result, void* fx_fv) { int fx_status = 0; int tag_0 = uop_0->tag; if (tag_0 == 1) { fx_str_t slit_0 = FX_MAKE_STR("+"); _fx_make_T3SiN13C_pp__assoc_t(&slit_0, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 2) { fx_str_t slit_1 = FX_MAKE_STR("-"); _fx_make_T3SiN13C_pp__assoc_t(&slit_1, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 3) { fx_str_t slit_2 = FX_MAKE_STR("~"); _fx_make_T3SiN13C_pp__assoc_t(&slit_2, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 4) { fx_str_t slit_3 = FX_MAKE_STR("!"); _fx_make_T3SiN13C_pp__assoc_t(&slit_3, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 5) { fx_str_t slit_4 = FX_MAKE_STR("*"); _fx_make_T3SiN13C_pp__assoc_t(&slit_4, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 6) { fx_str_t slit_5 = FX_MAKE_STR("&"); _fx_make_T3SiN13C_pp__assoc_t(&slit_5, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 7) { fx_str_t slit_6 = FX_MAKE_STR("++"); _fx_make_T3SiN13C_pp__assoc_t(&slit_6, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 8) { fx_str_t slit_7 = FX_MAKE_STR("--"); _fx_make_T3SiN13C_pp__assoc_t(&slit_7, 1300, &_fx_g16C_pp__AssocRight, fx_result); } else if (tag_0 == 9) { fx_str_t slit_8 = FX_MAKE_STR("++"); _fx_make_T3SiN13C_pp__assoc_t(&slit_8, 1400, &_fx_g15C_pp__AssocLeft, fx_result); } else if (tag_0 == 10) { fx_str_t slit_9 = FX_MAKE_STR("--"); _fx_make_T3SiN13C_pp__assoc_t(&slit_9, 1400, &_fx_g15C_pp__AssocLeft, fx_result); } else { FX_FAST_THROW(FX_EXN_NoMatchError, _fx_cleanup); } _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t( struct _fx_R5PP__t* pp_0, struct _fx_R9Ast__id_t* n_0, struct _fx_R10Ast__loc_t* loc_0, void* fx_fv) { fx_str_t v_0 = {0}; int fx_status = 0; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(n_0, loc_0, &v_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_cleanup); _fx_cleanup: ; FX_FREE_STR(&v_0); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t( struct _fx_R5PP__t* pp_0, fx_str_t* prefix0_0, fx_str_t* suffix0_0, struct _fx_N14C_form__ctyp_t_data_t* t_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, bool fwd_mode_0, struct _fx_R10Ast__loc_t* loc_0, void* fx_fv) { int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_cleanup); int tag_0 = FX_REC_VARIANT_TAG(t_0); bool res_0; if (tag_0 == 1) { res_0 = true; } else if (tag_0 == 2) { res_0 = true; } else if (tag_0 == 3) { res_0 = true; } else if (tag_0 == 4) { res_0 = true; } else if (tag_0 == 5) { res_0 = true; } else if (tag_0 == 6) { res_0 = true; } else if (tag_0 == 11) { res_0 = true; } else if (tag_0 == 9) { res_0 = true; } else if (tag_0 == 8) { res_0 = true; } else if (tag_0 == 12) { res_0 = true; } else if (tag_0 == 10) { res_0 = true; } else if (tag_0 == 18) { res_0 = true; } else if (tag_0 == 19) { res_0 = true; } else { res_0 = false; } FX_CHECK_EXN(_fx_cleanup); if (res_0) { fx_str_t v_0 = {0}; FX_CALL(_fx_M6C_formFM9ctyp2str_S2N14C_form__ctyp_tR10Ast__loc_t(t_0, loc_0, &v_0, 0), _fx_catch_0); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_catch_0); FX_CALL(_fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(id_opt_0, loc_0, pp_0, 0), _fx_catch_0); _fx_catch_0: ; FX_FREE_STR(&v_0); goto _fx_endmatch_3; } if (tag_0 == 7) { fx_str_t slit_0 = FX_MAKE_STR("void"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_catch_2); if (id_opt_0->tag == 2) { fx_str_t v_1 = {0}; fx_str_t v_2 = {0}; fx_str_t v_3 = {0}; fx_exn_t v_4 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&id_opt_0->u.Some, loc_0, &v_1, 0), _fx_catch_1); FX_CALL(_fx_M4C_ppFM6stringS1S(&v_1, &v_2, 0), _fx_catch_1); fx_str_t slit_1 = FX_MAKE_STR("c_pp.ml: void cannot be used with id \'"); fx_str_t slit_2 = FX_MAKE_STR("\'"); { const fx_str_t strs_0[] = { slit_1, v_2, slit_2 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 3, &v_3), _fx_catch_1); } FX_CALL(_fx_M3AstFM11compile_errE2RM5loc_tS(loc_0, &v_3, &v_4, 0), _fx_catch_1); FX_THROW(&v_4, false, _fx_catch_1); _fx_catch_1: ; fx_free_exn(&v_4); FX_FREE_STR(&v_3); FX_FREE_STR(&v_2); FX_FREE_STR(&v_1); } FX_CHECK_EXN(_fx_catch_2); _fx_catch_2: ; goto _fx_endmatch_3; } if (tag_0 == 15) { _fx_T2LN14C_form__ctyp_tN14C_form__ctyp_t* vcase_0 = &t_0->u.CTypFunRawPtr; _fx_LN14C_form__ctyp_t args_0 = vcase_0->t0; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_7); fx_str_t slit_3 = FX_MAKE_STR(""); fx_str_t slit_4 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_3, &slit_4, vcase_0->t1, &_fx_g10C_pp__None, true, loc_0, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_7); fx_str_t slit_5 = FX_MAKE_STR("(*"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_5, 0), _fx_catch_7); FX_CALL(_fx_M4C_ppFM10pr_id_opt_v4BNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(false, id_opt_0, loc_0, pp_0, 0), _fx_catch_7); fx_str_t slit_6 = FX_MAKE_STR(")("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_6, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_7); if (args_0 == 0) { fx_str_t slit_7 = FX_MAKE_STR("void"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_7, 0), _fx_catch_3); _fx_catch_3: ; goto _fx_endmatch_0; } if (args_0 != 0) { if (args_0->tl == 0) { fx_str_t slit_8 = FX_MAKE_STR(""); fx_str_t slit_9 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_8, &slit_9, args_0->hd, &_fx_g10C_pp__None, true, loc_0, 0), _fx_catch_4); _fx_catch_4: ; goto _fx_endmatch_0; } } _fx_LN14C_form__ctyp_t args_1 = 0; int_ nargs_0; FX_CALL(_fx_M4C_ppFM8length1_i1LN14C_form__ctyp_t(args_0, &nargs_0, 0), _fx_catch_6); int_ i_0 = 0; FX_COPY_PTR(args_0, &args_1); _fx_LN14C_form__ctyp_t lst_0 = args_1; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { fx_str_t v_5 = {0}; _fx_N14C_form__ctyp_t ti_0 = lst_0->hd; bool last_0 = i_0 == nargs_0 - 1; if (last_0) { fx_str_t slit_10 = FX_MAKE_STR(""); fx_copy_str(&slit_10, &v_5); } else { fx_str_t slit_11 = FX_MAKE_STR(","); fx_copy_str(&slit_11, &v_5); } fx_str_t slit_12 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_12, &v_5, ti_0, &_fx_g10C_pp__None, true, loc_0, 0), _fx_catch_5); if (!last_0) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_5); } _fx_catch_5: ; FX_FREE_STR(&v_5); FX_CHECK_EXN(_fx_catch_6); } _fx_catch_6: ; if (args_1) { _fx_free_LN14C_form__ctyp_t(&args_1); } _fx_endmatch_0: ; FX_CHECK_EXN(_fx_catch_7); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_7); fx_str_t slit_13 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_13, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_7); _fx_catch_7: ; goto _fx_endmatch_3; } if (tag_0 == 13) { fx_str_t v_6 = {0}; _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* vcase_1 = &t_0->u.CTypStruct; fx_str_t slit_14 = FX_MAKE_STR("struct"); { const fx_str_t strs_1[] = { *prefix0_0, slit_14 }; FX_CALL(fx_strjoin(0, 0, 0, strs_1, 2, &v_6), _fx_catch_8); } fx_str_t slit_15 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pr_structv7SNt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_tSNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( &v_6, &vcase_1->t0, vcase_1->t1, &slit_15, id_opt_0, loc_0, pp_0, 0), _fx_catch_8); _fx_catch_8: ; FX_FREE_STR(&v_6); goto _fx_endmatch_3; } if (tag_0 == 16) { _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* vcase_2 = &t_0->u.CTypRawPtr; if (vcase_2->t0 == 0) { _fx_N14C_form__ctyp_t v_7 = vcase_2->t1; if (FX_REC_VARIANT_TAG(v_7) == 13) { fx_str_t suffix_0 = {0}; fx_str_t v_8 = {0}; _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* vcase_3 = &v_7->u.CTypStruct; _fx_Nt6option1R9Ast__id_t* n_opt_0 = &vcase_3->t0; if (n_opt_0->tag == 2) { fx_str_t v_9 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&n_opt_0->u.Some, loc_0, &v_9, 0), _fx_catch_9); fx_str_t slit_16 = FX_MAKE_STR(", *"); { const fx_str_t strs_2[] = { v_9, slit_16 }; FX_CALL(fx_strjoin(0, 0, 0, strs_2, 2, &suffix_0), _fx_catch_9); } _fx_catch_9: ; FX_FREE_STR(&v_9); } else { fx_str_t slit_17 = FX_MAKE_STR("*"); fx_copy_str(&slit_17, &suffix_0); } FX_CHECK_EXN(_fx_catch_10); fx_str_t slit_18 = FX_MAKE_STR("struct"); { const fx_str_t strs_3[] = { *prefix0_0, slit_18 }; FX_CALL(fx_strjoin(0, 0, 0, strs_3, 2, &v_8), _fx_catch_10); } FX_CALL( _fx_M4C_ppFM9pr_structv7SNt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_tSNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( &v_8, n_opt_0, vcase_3->t1, &suffix_0, id_opt_0, loc_0, pp_0, 0), _fx_catch_10); _fx_catch_10: ; FX_FREE_STR(&v_8); FX_FREE_STR(&suffix_0); goto _fx_endmatch_3; } } } if (tag_0 == 14) { fx_str_t v_10 = {0}; _fx_T2Nt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_t* vcase_4 = &t_0->u.CTypUnion; fx_str_t slit_19 = FX_MAKE_STR("union"); { const fx_str_t strs_4[] = { *prefix0_0, slit_19 }; FX_CALL(fx_strjoin(0, 0, 0, strs_4, 2, &v_10), _fx_catch_11); } fx_str_t slit_20 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pr_structv7SNt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_tSNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( &v_10, &vcase_4->t0, vcase_4->t1, &slit_20, id_opt_0, loc_0, pp_0, 0), _fx_catch_11); _fx_catch_11: ; FX_FREE_STR(&v_10); goto _fx_endmatch_3; } if (tag_0 == 16) { _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* vcase_5 = &t_0->u.CTypRawPtr; _fx_LN19C_form__ctyp_attr_t attrs_0 = vcase_5->t0; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_12); bool v_11; FX_CALL(_fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t(attrs_0, &_fx_g16C_pp__CTypStatic, &v_11, 0), _fx_catch_12); if (v_11) { fx_str_t slit_21 = FX_MAKE_STR("static "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_21, 0), _fx_catch_12); } bool v_12; FX_CALL(_fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t(attrs_0, &_fx_g18C_pp__CTypVolatile, &v_12, 0), _fx_catch_12); if (v_12) { fx_str_t slit_22 = FX_MAKE_STR("volatile "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_22, 0), _fx_catch_12); } fx_str_t slit_23 = FX_MAKE_STR(""); fx_str_t slit_24 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_23, &slit_24, vcase_5->t1, &_fx_g10C_pp__None, fwd_mode_0, loc_0, 0), _fx_catch_12); fx_str_t slit_25 = FX_MAKE_STR("*"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_25, 0), _fx_catch_12); FX_CALL(_fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(id_opt_0, loc_0, pp_0, 0), _fx_catch_12); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_12); _fx_catch_12: ; goto _fx_endmatch_3; } if (tag_0 == 17) { _fx_T2LN19C_form__ctyp_attr_tN14C_form__ctyp_t* vcase_6 = &t_0->u.CTypRawArray; _fx_LN19C_form__ctyp_attr_t attrs_1 = vcase_6->t0; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_13); bool v_13; FX_CALL(_fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t(attrs_1, &_fx_g16C_pp__CTypStatic, &v_13, 0), _fx_catch_13); if (v_13) { fx_str_t slit_26 = FX_MAKE_STR("static "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_26, 0), _fx_catch_13); } bool v_14; FX_CALL(_fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t(attrs_1, &_fx_g18C_pp__CTypVolatile, &v_14, 0), _fx_catch_13); if (v_14) { fx_str_t slit_27 = FX_MAKE_STR("volatile "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_27, 0), _fx_catch_13); } bool v_15; FX_CALL(_fx_M4C_ppFM3memB2LN19C_form__ctyp_attr_tN19C_form__ctyp_attr_t(attrs_1, &_fx_g15C_pp__CTypConst, &v_15, 0), _fx_catch_13); if (v_15) { fx_str_t slit_28 = FX_MAKE_STR("const "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_28, 0), _fx_catch_13); } fx_str_t slit_29 = FX_MAKE_STR(""); fx_str_t slit_30 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_29, &slit_30, vcase_6->t1, &_fx_g10C_pp__None, fwd_mode_0, loc_0, 0), _fx_catch_13); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_13); FX_CALL(_fx_M4C_ppFM10pr_id_opt_v4BNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(false, id_opt_0, loc_0, pp_0, 0), _fx_catch_13); fx_str_t slit_31 = FX_MAKE_STR("[]"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_31, 0), _fx_catch_13); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_13); _fx_catch_13: ; goto _fx_endmatch_3; } if (tag_0 == 20) { _fx_R9Ast__id_t* n_0 = &t_0->u.CTypName; if (fwd_mode_0 == false) { FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, n_0, loc_0, 0), _fx_catch_14); _fx_catch_14: ; goto _fx_endmatch_2; } if (fwd_mode_0 == true) { if (n_0->m == 0) { FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, n_0, loc_0, 0), _fx_catch_15); _fx_catch_15: ; goto _fx_endmatch_2; } } _fx_N15C_form__cinfo_t v_16 = {0}; _fx_R17C_form__cdeftyp_t v_17 = {0}; _fx_R17C_form__cdeftyp_t v_18 = {0}; FX_CALL(_fx_M6C_formFM6cinfo_N15C_form__cinfo_t2R9Ast__id_tR10Ast__loc_t(n_0, loc_0, &v_16, 0), _fx_catch_20); int tag_1 = v_16.tag; if (tag_1 == 4) { _fx_copy_R17C_form__cdeftyp_t(&v_16.u.CTyp->data, &v_17); _fx_N14C_form__ctyp_t v_19 = v_17.ct_typ; if (FX_REC_VARIANT_TAG(v_19) == 16) { _fx_N14C_form__ctyp_t v_20 = v_19->u.CTypRawPtr.t1; if (FX_REC_VARIANT_TAG(v_20) == 13) { _fx_Nt6option1R9Ast__id_t* v_21 = &v_20->u.CTypStruct.t0; if (v_21->tag == 2) { fx_str_t slit_32 = FX_MAKE_STR("struct "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_32, 0), _fx_catch_16); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &v_21->u.Some, loc_0, 0), _fx_catch_16); fx_str_t slit_33 = FX_MAKE_STR("*"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_33, 0), _fx_catch_16); _fx_catch_16: ; goto _fx_endmatch_1; } } } } if (tag_1 == 4) { _fx_copy_R17C_form__cdeftyp_t(&v_16.u.CTyp->data, &v_18); _fx_N14C_form__ctyp_t v_22 = v_18.ct_typ; if (FX_REC_VARIANT_TAG(v_22) == 13) { _fx_Nt6option1R9Ast__id_t* v_23 = &v_22->u.CTypStruct.t0; if (v_23->tag == 2) { fx_str_t slit_34 = FX_MAKE_STR("struct "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_34, 0), _fx_catch_17); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &v_23->u.Some, loc_0, 0), _fx_catch_17); _fx_catch_17: ; goto _fx_endmatch_1; } } } if (tag_1 == 6) { _fx_R23C_form__cdefinterface_t v_24 = {0}; fx_str_t v_25 = {0}; fx_str_t v_26 = {0}; _fx_copy_R23C_form__cdefinterface_t(&v_16.u.CInterface->data, &v_24); FX_CALL(_fx_M4C_ppFM6stringS1S(&v_24.ci_cname, &v_25, 0), _fx_catch_18); fx_str_t slit_35 = FX_MAKE_STR("struct "); { const fx_str_t strs_5[] = { slit_35, v_25 }; FX_CALL(fx_strjoin(0, 0, 0, strs_5, 2, &v_26), _fx_catch_18); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_26, 0), _fx_catch_18); _fx_catch_18: ; FX_FREE_STR(&v_26); FX_FREE_STR(&v_25); _fx_free_R23C_form__cdefinterface_t(&v_24); goto _fx_endmatch_1; } if (FX_STR_LENGTH(*prefix0_0) != 0) { FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, prefix0_0, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_19); } FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, n_0, loc_0, 0), _fx_catch_19); _fx_catch_19: ; _fx_endmatch_1: ; FX_CHECK_EXN(_fx_catch_20); _fx_catch_20: ; _fx_free_R17C_form__cdeftyp_t(&v_18); _fx_free_R17C_form__cdeftyp_t(&v_17); _fx_free_N15C_form__cinfo_t(&v_16); _fx_endmatch_2: ; FX_CHECK_EXN(_fx_catch_21); FX_CALL(_fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(id_opt_0, loc_0, pp_0, 0), _fx_catch_21); _fx_catch_21: ; goto _fx_endmatch_3; } if (tag_0 == 21) { fx_str_t slit_36 = FX_MAKE_STR("/*<label>*/"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_36, 0), _fx_catch_22); FX_CALL(_fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(id_opt_0, loc_0, pp_0, 0), _fx_catch_22); _fx_catch_22: ; goto _fx_endmatch_3; } if (tag_0 == 22) { fx_str_t slit_37 = FX_MAKE_STR("void"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_37, 0), _fx_catch_23); FX_CALL(_fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t(id_opt_0, loc_0, pp_0, 0), _fx_catch_23); _fx_catch_23: ; goto _fx_endmatch_3; } FX_FAST_THROW(FX_EXN_NoMatchError, _fx_cleanup); _fx_endmatch_3: ; FX_CHECK_EXN(_fx_cleanup); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, suffix0_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_cleanup); _fx_cleanup: ; return fx_status; } static int _fx_M4C_ppFM10pr_id_opt_v4BNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( bool add_space_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv) { int fx_status = 0; if (id_opt_0->tag == 2) { fx_str_t v_0 = {0}; if (add_space_0) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_0); } FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&id_opt_0->u.Some, loc_0, &v_0, 0), _fx_catch_0); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_catch_0); _fx_catch_0: ; FX_FREE_STR(&v_0); } return fx_status; } static int _fx_M4C_ppFM9pr_id_optv3Nt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv) { int fx_status = 0; if (id_opt_0->tag == 2) { fx_str_t v_0 = {0}; FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_0); FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&id_opt_0->u.Some, loc_0, &v_0, 0), _fx_catch_0); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_catch_0); _fx_catch_0: ; FX_FREE_STR(&v_0); } return fx_status; } static int _fx_M4C_ppFM9pr_structv7SNt6option1R9Ast__id_tLT2R9Ast__id_tN14C_form__ctyp_tSNt6option1R9Ast__id_tR10Ast__loc_tR5PP__t( fx_str_t* prefix_0, struct _fx_Nt6option1R9Ast__id_t* n_opt_0, struct _fx_LT2R9Ast__id_tN14C_form__ctyp_t_data_t* elems_0, fx_str_t* suffix_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, struct _fx_R5PP__t* pp_0, void* fx_fv) { fx_str_t v_0 = {0}; fx_str_t v_1 = {0}; int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); fx_str_t slit_0 = FX_MAKE_STR(" "); { const fx_str_t strs_0[] = { *prefix_0, slit_0 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 2, &v_0), _fx_cleanup); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_cleanup); if (n_opt_0->tag == 2) { fx_str_t v_2 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&n_opt_0->u.Some, loc_0, &v_2, 0), _fx_catch_0); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_2, 0), _fx_catch_0); fx_str_t slit_1 = FX_MAKE_STR(" "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_1, 0), _fx_catch_0); _fx_catch_0: ; FX_FREE_STR(&v_2); } FX_CHECK_EXN(_fx_cleanup); fx_str_t slit_2 = FX_MAKE_STR("{"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_2, 0), _fx_cleanup); _fx_LT2R9Ast__id_tN14C_form__ctyp_t lst_0 = elems_0; for (; lst_0; lst_0 = lst_0->tl) { _fx_N14C_form__ctyp_t ti_0 = 0; _fx_T2R9Ast__id_tN14C_form__ctyp_t* __pat___0 = &lst_0->hd; _fx_R9Ast__id_t ni_0 = __pat___0->t0; FX_COPY_PTR(__pat___0->t1, &ti_0); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_1); int tag_0 = FX_REC_VARIANT_TAG(ti_0); bool need_nested_box_0; bool res_0; if (tag_0 == 13) { res_0 = true; goto _fx_endmatch_0; } if (tag_0 == 14) { res_0 = true; goto _fx_endmatch_0; } if (tag_0 == 16) { if (FX_REC_VARIANT_TAG(ti_0->u.CTypRawPtr.t1) == 13) { res_0 = true; goto _fx_endmatch_0; } } res_0 = false; _fx_endmatch_0: ; FX_CHECK_EXN(_fx_catch_1); if (res_0) { need_nested_box_0 = false; goto _fx_endmatch_1; } need_nested_box_0 = true; _fx_endmatch_1: ; FX_CHECK_EXN(_fx_catch_1); if (need_nested_box_0) { FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_1); } _fx_Nt6option1R9Ast__id_t v_3; _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t(&ni_0, &v_3); fx_str_t slit_3 = FX_MAKE_STR(""); fx_str_t slit_4 = FX_MAKE_STR(";"); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_3, &slit_4, ti_0, &v_3, true, loc_0, 0), _fx_catch_1); if (need_nested_box_0) { FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_1); } _fx_catch_1: ; if (ti_0) { _fx_free_N14C_form__ctyp_t(&ti_0); } FX_CHECK_EXN(_fx_cleanup); } FX_CALL(_fx_M2PPFM8newlineuv1RM1t(pp_0, 0), _fx_cleanup); fx_str_t slit_5 = FX_MAKE_STR("} "); { const fx_str_t strs_1[] = { slit_5, *suffix_0 }; FX_CALL(fx_strjoin(0, 0, 0, strs_1, 2, &v_1), _fx_cleanup); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_1, 0), _fx_cleanup); if (id_opt_0->tag == 2) { fx_str_t v_4 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(&id_opt_0->u.Some, loc_0, &v_4, 0), _fx_catch_2); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_4, 0), _fx_catch_2); _fx_catch_2: ; FX_FREE_STR(&v_4); } _fx_cleanup: ; FX_FREE_STR(&v_0); FX_FREE_STR(&v_1); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8pp_ctyp_v4R5PP__tN14C_form__ctyp_tNt6option1R9Ast__id_tR10Ast__loc_t( struct _fx_R5PP__t* pp_0, struct _fx_N14C_form__ctyp_t_data_t* t_0, struct _fx_Nt6option1R9Ast__id_t* id_opt_0, struct _fx_R10Ast__loc_t* loc_0, void* fx_fv) { int fx_status = 0; fx_str_t slit_0 = FX_MAKE_STR(""); fx_str_t slit_1 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_0, &slit_1, t_0, id_opt_0, false, loc_0, 0), _fx_cleanup); _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti( struct _fx_R5PP__t* pp_0, struct _fx_N14C_form__cexp_t_data_t* e_0, int_ pr_0, void* fx_fv) { int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); int tag_0 = FX_REC_VARIANT_TAG(e_0); if (tag_0 == 1) { _fx_T2R9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_0 = &e_0->u.CExpIdent; FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_0->t0, &vcase_0->t1.t1, 0), _fx_catch_0); _fx_catch_0: ; goto _fx_endmatch_1; } if (tag_0 == 2) { _fx_T2N14K_form__klit_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_1 = &e_0->u.CExpLit; _fx_N14K_form__klit_t* l_0 = &vcase_1->t0; int tag_1 = l_0->tag; if (tag_1 == 8) { fx_str_t slit_0 = FX_MAKE_STR("0"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_catch_1); _fx_catch_1: ; } else if (tag_1 == 6) { fx_str_t v_0 = {0}; fx_str_t v_1 = {0}; int_ res_0; FX_CALL(_fx_F3ordi1C(l_0->u.KLitChar, &res_0, 0), _fx_catch_2); FX_CALL(_fx_F6stringS1i(res_0, &v_0, 0), _fx_catch_2); fx_str_t slit_1 = FX_MAKE_STR("(char_)"); { const fx_str_t strs_0[] = { slit_1, v_0 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 2, &v_1), _fx_catch_2); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_1, 0), _fx_catch_2); _fx_catch_2: ; FX_FREE_STR(&v_1); FX_FREE_STR(&v_0); } else if (tag_1 == 5) { _fx_LS sl_0 = 0; fx_str_t v_2 = {0}; fx_str_t* s0_0 = &l_0->u.KLitString; FX_CALL(_fx_M6StringFM5splitLS3SCB(s0_0, (char_)10, true, &sl_0, 0), _fx_catch_4); if (sl_0 == 0) { FX_CALL(_fx_M6StringFM7escapedS2SB(s0_0, true, &v_2, 0), _fx_catch_4); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_2, 0), _fx_catch_4); } else { int_ n_0; FX_CALL(_fx_M4C_ppFM8length1_i1LS(sl_0, &n_0, 0), _fx_catch_4); int_ i_0 = 0; _fx_LS lst_0 = sl_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { fx_str_t s_0 = {0}; fx_str_t s_1 = {0}; fx_str_t v_3 = {0}; fx_str_t* s_2 = &lst_0->hd; bool v_4; if (i_0 < n_0 - 1) { v_4 = true; } else { v_4 = _fx_M6StringFM8endswithB2SC(s0_0, (char_)10, 0); } if (v_4) { fx_str_t slit_2 = FX_MAKE_STR("\n"); { const fx_str_t strs_1[] = { *s_2, slit_2 }; FX_CALL(fx_strjoin(0, 0, 0, strs_1, 2, &s_0), _fx_catch_3); } } else { fx_copy_str(s_2, &s_0); } FX_CALL(_fx_M6StringFM7escapedS2SB(&s_0, true, &s_1, 0), _fx_catch_3); if (i_0 == 0) { FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &s_1, 0), _fx_catch_3); } else { FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_3); fx_str_t slit_3 = FX_MAKE_STR("U"); { const fx_str_t strs_2[] = { slit_3, s_1 }; FX_CALL(fx_strjoin(0, 0, 0, strs_2, 2, &v_3), _fx_catch_3); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_3, 0), _fx_catch_3); } _fx_catch_3: ; FX_FREE_STR(&v_3); FX_FREE_STR(&s_1); FX_FREE_STR(&s_0); FX_CHECK_EXN(_fx_catch_4); } } _fx_catch_4: ; FX_FREE_STR(&v_2); if (sl_0) { _fx_free_LS(&sl_0); } } else { fx_str_t v_5 = {0}; FX_CALL(_fx_M6K_formFM8klit2strS3N14K_form__klit_tBR10Ast__loc_t(l_0, true, &vcase_1->t1.t1, &v_5, 0), _fx_catch_5); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_5, 0), _fx_catch_5); _fx_catch_5: ; FX_FREE_STR(&v_5); } FX_CHECK_EXN(_fx_catch_6); _fx_catch_6: ; goto _fx_endmatch_1; } if (tag_0 == 3) { _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_2 = &e_0->u.CExpBinary; _fx_N17C_form__cbinary_t* bop_0 = &vcase_2->t0; if (bop_0->tag == 14) { _fx_T3SiN13C_pp__assoc_t v_6 = {0}; FX_CALL(_fx_M4C_ppFM10binop2str_T3SiN13C_pp__assoc_t1N17C_form__cbinary_t(bop_0, &v_6, 0), _fx_catch_7); int_ pr0_0 = v_6.t1; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_7); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_2->t1, pr0_0, 0), _fx_catch_7); fx_str_t slit_4 = FX_MAKE_STR("["); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_4, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_7); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_2->t2, 0, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_7); fx_str_t slit_5 = FX_MAKE_STR("]"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_5, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_7); _fx_catch_7: ; _fx_free_T3SiN13C_pp__assoc_t(&v_6); goto _fx_endmatch_1; } } if (tag_0 == 3) { _fx_T3SiN13C_pp__assoc_t v_7 = {0}; fx_str_t bop_str_0 = {0}; _fx_T4N17C_form__cbinary_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_3 = &e_0->u.CExpBinary; _fx_N17C_form__cbinary_t* bop_1 = &vcase_3->t0; FX_CALL(_fx_M4C_ppFM10binop2str_T3SiN13C_pp__assoc_t1N17C_form__cbinary_t(bop_1, &v_7, 0), _fx_catch_8); fx_copy_str(&v_7.t0, &bop_str_0); int_ pr0_1 = v_7.t1; _fx_N13C_pp__assoc_t assoc_0 = v_7.t2; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_8); if (pr0_1 < pr_0) { fx_str_t slit_6 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_6, 0), _fx_catch_8); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_8); } bool is_shift_0; if (bop_1->tag == 6) { is_shift_0 = true; } else { is_shift_0 = bop_1->tag == 7; } int_ a_pr_0; if (is_shift_0) { a_pr_0 = 1350; } else if (assoc_0.tag == 1) { a_pr_0 = pr0_1; } else { a_pr_0 = pr0_1 + 1; } int_ b_pr_0; if (is_shift_0) { b_pr_0 = 1350; } else if (assoc_0.tag == 2) { b_pr_0 = pr0_1; } else { b_pr_0 = pr0_1 + 1; } FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_3->t1, a_pr_0, 0), _fx_catch_8); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_8); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &bop_str_0, 0), _fx_catch_8); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_8); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_3->t2, b_pr_0, 0), _fx_catch_8); if (pr0_1 < pr_0) { FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_8); fx_str_t slit_7 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_7, 0), _fx_catch_8); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_8); _fx_catch_8: ; FX_FREE_STR(&bop_str_0); _fx_free_T3SiN13C_pp__assoc_t(&v_7); goto _fx_endmatch_1; } if (tag_0 == 4) { _fx_T3SiN13C_pp__assoc_t v_8 = {0}; fx_str_t uop_str_0 = {0}; _fx_T3N16C_form__cunary_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_4 = &e_0->u.CExpUnary; _fx_N14C_form__cexp_t e_1 = vcase_4->t1; _fx_N16C_form__cunary_t* uop_0 = &vcase_4->t0; FX_CALL(_fx_M4C_ppFM9unop2str_T3SiN13C_pp__assoc_t1N16C_form__cunary_t(uop_0, &v_8, 0), _fx_catch_11); fx_copy_str(&v_8.t0, &uop_str_0); int_ pr0_2 = v_8.t1; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_11); if (pr0_2 < pr_0) { fx_str_t slit_8 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_8, 0), _fx_catch_11); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_11); } int tag_2 = uop_0->tag; bool res_1; if (tag_2 == 9) { res_1 = true; } else if (tag_2 == 10) { res_1 = true; } else { res_1 = false; } FX_CHECK_EXN(_fx_catch_11); if (res_1) { FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_1, pr0_2, 0), _fx_catch_9); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &uop_str_0, 0), _fx_catch_9); _fx_catch_9: ; goto _fx_endmatch_0; } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &uop_str_0, 0), _fx_catch_10); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_1, pr0_2, 0), _fx_catch_10); _fx_catch_10: ; _fx_endmatch_0: ; FX_CHECK_EXN(_fx_catch_11); if (pr0_2 < pr_0) { FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_11); fx_str_t slit_9 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_9, 0), _fx_catch_11); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_11); _fx_catch_11: ; FX_FREE_STR(&uop_str_0); _fx_free_T3SiN13C_pp__assoc_t(&v_8); goto _fx_endmatch_1; } if (tag_0 == 5) { _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_5 = &e_0->u.CExpMem; FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_5->t0, 1400, 0), _fx_catch_12); fx_str_t slit_10 = FX_MAKE_STR("."); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_10, 0), _fx_catch_12); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_5->t1, &vcase_5->t2.t1, 0), _fx_catch_12); _fx_catch_12: ; goto _fx_endmatch_1; } if (tag_0 == 6) { _fx_T3N14C_form__cexp_tR9Ast__id_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_6 = &e_0->u.CExpArrow; FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_6->t0, 1400, 0), _fx_catch_13); fx_str_t slit_11 = FX_MAKE_STR("->"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_11, 0), _fx_catch_13); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_6->t1, &vcase_6->t2.t1, 0), _fx_catch_13); _fx_catch_13: ; goto _fx_endmatch_1; } if (tag_0 == 7) { _fx_T3N14C_form__cexp_tN14C_form__ctyp_tR10Ast__loc_t* vcase_7 = &e_0->u.CExpCast; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_14); fx_str_t slit_12 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_12, 0), _fx_catch_14); FX_CALL( _fx_M4C_ppFM8pp_ctyp_v4R5PP__tN14C_form__ctyp_tNt6option1R9Ast__id_tR10Ast__loc_t(pp_0, vcase_7->t1, &_fx_g10C_pp__None, &vcase_7->t2, 0), _fx_catch_14); fx_str_t slit_13 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_13, 0), _fx_catch_14); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_14); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_7->t0, 1301, 0), _fx_catch_14); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_14); _fx_catch_14: ; goto _fx_endmatch_1; } if (tag_0 == 8) { _fx_T4N14C_form__cexp_tN14C_form__cexp_tN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_8 = &e_0->u.CExpTernary; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_15); if (200 < pr_0) { fx_str_t slit_14 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_14, 0), _fx_catch_15); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_15); } FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_8->t0, 0, 0), _fx_catch_15); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_15); fx_str_t slit_15 = FX_MAKE_STR("?"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_15, 0), _fx_catch_15); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_15); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_8->t1, 0, 0), _fx_catch_15); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_15); fx_str_t slit_16 = FX_MAKE_STR(":"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_16, 0), _fx_catch_15); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_15); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_8->t2, 0, 0), _fx_catch_15); if (200 < pr_0) { FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_15); fx_str_t slit_17 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_17, 0), _fx_catch_15); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_15); _fx_catch_15: ; goto _fx_endmatch_1; } if (tag_0 == 9) { _fx_T3N14C_form__cexp_tLN14C_form__cexp_tT2N14C_form__ctyp_tR10Ast__loc_t* vcase_9 = &e_0->u.CExpCall; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_16); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_9->t0, 1400, 0), _fx_catch_16); fx_str_t slit_18 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_18, 0), _fx_catch_16); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_16); FX_CALL(_fx_M4C_ppFM8pp_elistv2R5PP__tLN14C_form__cexp_t(pp_0, vcase_9->t1, 0), _fx_catch_16); fx_str_t slit_19 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_19, 0), _fx_catch_16); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_16); _fx_catch_16: ; goto _fx_endmatch_1; } if (tag_0 == 10) { _fx_LN14C_form__cexp_t eseq_0 = 0; _fx_LN14C_form__cexp_t eseq_1 = e_0->u.CExpInit.t0; if (eseq_1 != 0) { FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_18); fx_str_t slit_20 = FX_MAKE_STR("{"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_20, 0), _fx_catch_18); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_18); int_ i_1 = 0; FX_COPY_PTR(eseq_1, &eseq_0); _fx_LN14C_form__cexp_t lst_1 = eseq_0; for (; lst_1; lst_1 = lst_1->tl, i_1 += 1) { _fx_N14C_form__cexp_t e_2 = lst_1->hd; if (i_1 > 0) { fx_str_t slit_21 = FX_MAKE_STR(","); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_21, 0), _fx_catch_17); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_17); } FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_2, 0, 0), _fx_catch_17); _fx_catch_17: ; FX_CHECK_EXN(_fx_catch_18); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_18); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_18); fx_str_t slit_22 = FX_MAKE_STR("}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_22, 0), _fx_catch_18); } else { fx_str_t slit_23 = FX_MAKE_STR("{0}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_23, 0), _fx_catch_18); } _fx_catch_18: ; if (eseq_0) { _fx_free_LN14C_form__cexp_t(&eseq_0); } goto _fx_endmatch_1; } if (tag_0 == 11) { _fx_T2N14C_form__ctyp_tR10Ast__loc_t* vcase_10 = &e_0->u.CExpTyp; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_19); FX_CALL( _fx_M4C_ppFM8pp_ctyp_v4R5PP__tN14C_form__ctyp_tNt6option1R9Ast__id_tR10Ast__loc_t(pp_0, vcase_10->t0, &_fx_g10C_pp__None, &vcase_10->t1, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_19); _fx_catch_19: ; goto _fx_endmatch_1; } if (tag_0 == 12) { fx_str_t v_9 = {0}; fx_str_t v_10 = {0}; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_20); FX_CALL(_fx_M6StringFM5stripS1S(&e_0->u.CExpCCode.t0, &v_9, 0), _fx_catch_20); fx_str_t slit_24 = FX_MAKE_STR("\n"); fx_str_t slit_25 = FX_MAKE_STR("\n"); { const fx_str_t strs_3[] = { slit_24, v_9, slit_25 }; FX_CALL(fx_strjoin(0, 0, 0, strs_3, 3, &v_10), _fx_catch_20); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_10, 0), _fx_catch_20); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_20); _fx_catch_20: ; FX_FREE_STR(&v_10); FX_FREE_STR(&v_9); goto _fx_endmatch_1; } FX_FAST_THROW(FX_EXN_NoMatchError, _fx_cleanup); _fx_endmatch_1: ; _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM8pp_elistv2R5PP__tLN14C_form__cexp_t( struct _fx_R5PP__t* pp_0, struct _fx_LN14C_form__cexp_t_data_t* el_0, void* fx_fv) { int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); int_ i_0 = 0; _fx_LN14C_form__cexp_t lst_0 = el_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { _fx_N14C_form__cexp_t e_0 = lst_0->hd; if (i_0 > 0) { fx_str_t slit_0 = FX_MAKE_STR(","); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_catch_0); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_0); } FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_0, 0, 0), _fx_catch_0); _fx_catch_0: ; FX_CHECK_EXN(_fx_cleanup); } _fx_cleanup: ; return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM14pprint_fun_hdrv5R5PP__tR9Ast__id_tBR10Ast__loc_tB( struct _fx_R5PP__t* pp_0, struct _fx_R9Ast__id_t* fname_0, bool semicolon_0, struct _fx_R10Ast__loc_t* loc_0, bool fwd_mode_0, void* fx_fv) { _fx_N15C_form__cinfo_t v_0 = {0}; _fx_R17C_form__cdeffun_t v_1 = {0}; fx_str_t cf_cname_0 = {0}; _fx_N14C_form__ctyp_t cf_rt_0 = 0; _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t cf_args_0 = 0; fx_str_t v_2 = {0}; fx_str_t v_3 = {0}; int fx_status = 0; FX_CALL(_fx_M6C_formFM6cinfo_N15C_form__cinfo_t2R9Ast__id_tR10Ast__loc_t(fname_0, loc_0, &v_0, 0), _fx_cleanup); if (v_0.tag == 3) { _fx_copy_R17C_form__cdeffun_t(&v_0.u.CFun->data, &v_1); } else { fx_str_t v_4 = {0}; fx_str_t v_5 = {0}; fx_exn_t v_6 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(fname_0, loc_0, &v_4, 0), _fx_catch_0); fx_str_t slit_0 = FX_MAKE_STR("the forward declaration of "); fx_str_t slit_1 = FX_MAKE_STR(" does not reference a function"); { const fx_str_t strs_0[] = { slit_0, v_4, slit_1 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 3, &v_5), _fx_catch_0); } FX_CALL(_fx_M3AstFM11compile_errE2RM5loc_tS(loc_0, &v_5, &v_6, 0), _fx_catch_0); FX_THROW(&v_6, false, _fx_catch_0); _fx_catch_0: ; fx_free_exn(&v_6); FX_FREE_STR(&v_5); FX_FREE_STR(&v_4); } FX_CHECK_EXN(_fx_cleanup); _fx_R10Ast__loc_t cf_loc_0 = v_1.cf_loc; _fx_R16Ast__fun_flags_t cf_flags_0 = v_1.cf_flags; fx_copy_str(&v_1.cf_cname, &cf_cname_0); FX_COPY_PTR(v_1.cf_rt, &cf_rt_0); FX_COPY_PTR(v_1.cf_args, &cf_args_0); FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_cleanup); if (cf_flags_0.fun_flag_private) { fx_str_t slit_2 = FX_MAKE_STR("static "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_2, 0), _fx_cleanup); } else { fx_str_t slit_3 = FX_MAKE_STR("FX_EXTERN_C "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_3, 0), _fx_cleanup); } fx_str_t slit_4 = FX_MAKE_STR(""); fx_str_t slit_5 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_4, &slit_5, cf_rt_0, &_fx_g10C_pp__None, false, &cf_loc_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &cf_cname_0, 0), _fx_cleanup); fx_str_t slit_6 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_6, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_cleanup); if (cf_args_0 == 0) { fx_str_t slit_7 = FX_MAKE_STR("void"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_7, 0), _fx_catch_1); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_1); _fx_catch_1: ; } else { int_ nargs_0 = _fx_M4C_ppFM6lengthi1LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t(cf_args_0, 0); int_ i_0 = 0; _fx_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t lst_0 = cf_args_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { _fx_N14C_form__ctyp_t t_0 = 0; fx_str_t v_7 = {0}; _fx_T3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t* __pat___0 = &lst_0->hd; _fx_R9Ast__id_t n_0 = __pat___0->t0; FX_COPY_PTR(__pat___0->t1, &t_0); bool last_0 = i_0 == nargs_0 - 1; if (last_0) { fx_str_t slit_8 = FX_MAKE_STR(""); fx_copy_str(&slit_8, &v_7); } else { fx_str_t slit_9 = FX_MAKE_STR(","); fx_copy_str(&slit_9, &v_7); } _fx_Nt6option1R9Ast__id_t v_8; _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t(&n_0, &v_8); fx_str_t slit_10 = FX_MAKE_STR(""); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_10, &v_7, t_0, &v_8, true, &cf_loc_0, 0), _fx_catch_2); if (!last_0) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_2); } _fx_catch_2: ; FX_FREE_STR(&v_7); if (t_0) { _fx_free_N14C_form__ctyp_t(&t_0); } FX_CHECK_EXN(_fx_catch_3); } _fx_catch_3: ; } FX_CHECK_EXN(_fx_cleanup); if (semicolon_0) { fx_str_t slit_11 = FX_MAKE_STR(";"); fx_copy_str(&slit_11, &v_2); } else { fx_str_t slit_12 = FX_MAKE_STR(""); fx_copy_str(&slit_12, &v_2); } fx_str_t slit_13 = FX_MAKE_STR(")"); { const fx_str_t strs_1[] = { slit_13, v_2 }; FX_CALL(fx_strjoin(0, 0, 0, strs_1, 2, &v_3), _fx_cleanup); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_3, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_cleanup); _fx_cleanup: ; _fx_free_N15C_form__cinfo_t(&v_0); _fx_free_R17C_form__cdeffun_t(&v_1); FX_FREE_STR(&cf_cname_0); if (cf_rt_0) { _fx_free_N14C_form__ctyp_t(&cf_rt_0); } if (cf_args_0) { _fx_free_LT3R9Ast__id_tN14C_form__ctyp_tLN19C_form__carg_attr_t(&cf_args_0); } FX_FREE_STR(&v_2); FX_FREE_STR(&v_3); return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t( struct _fx_R5PP__t* pp_0, struct _fx_N15C_form__cstmt_t_data_t* s_0, void* fx_fv) { _fx_LN15C_form__cstmt_t sl_0 = 0; int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); int tag_0 = FX_REC_VARIANT_TAG(s_0); if (tag_0 == 7) { FX_COPY_PTR(s_0->u.CStmtBlock.t0, &sl_0); } else if (tag_0 != 1) { FX_CALL(_fx_cons_LN15C_form__cstmt_t(s_0, 0, true, &sl_0), _fx_catch_0); _fx_catch_0: ; } FX_CHECK_EXN(_fx_cleanup); fx_str_t slit_0 = FX_MAKE_STR("{"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM6beginvv2RM1ti(pp_0, 0, 0), _fx_cleanup); int_ i_0 = 0; _fx_LN15C_form__cstmt_t lst_0 = sl_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { _fx_N15C_form__cstmt_t s_1 = lst_0->hd; if (i_0 > 0) { FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_1); } FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_1, 0), _fx_catch_1); _fx_catch_1: ; FX_CHECK_EXN(_fx_cleanup); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_cleanup); fx_str_t slit_1 = FX_MAKE_STR("}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_1, 0), _fx_cleanup); _fx_cleanup: ; if (sl_0) { _fx_free_LN15C_form__cstmt_t(&sl_0); } return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM21pprint_cstmt_as_blockv2R5PP__tN15C_form__cstmt_t( struct _fx_R5PP__t* pp_0, struct _fx_N15C_form__cstmt_t_data_t* s_0, void* fx_fv) { _fx_LN15C_form__cstmt_t sl_0 = 0; int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); int tag_0 = FX_REC_VARIANT_TAG(s_0); if (tag_0 == 7) { FX_COPY_PTR(s_0->u.CStmtBlock.t0, &sl_0); } else if (tag_0 != 1) { FX_CALL(_fx_cons_LN15C_form__cstmt_t(s_0, 0, true, &sl_0), _fx_catch_0); _fx_catch_0: ; } FX_CHECK_EXN(_fx_cleanup); if (sl_0 == 0) { fx_str_t slit_0 = FX_MAKE_STR("{}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_catch_1); _fx_catch_1: ; } else { FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_catch_3); fx_str_t slit_1 = FX_MAKE_STR("{"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_1, 0), _fx_catch_3); int_ i_0 = 0; _fx_LN15C_form__cstmt_t lst_0 = sl_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { _fx_N15C_form__cstmt_t s_1 = lst_0->hd; FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_2); FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_1, 0), _fx_catch_2); _fx_catch_2: ; FX_CHECK_EXN(_fx_catch_3); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_3); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_3); fx_str_t slit_2 = FX_MAKE_STR("}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_2, 0), _fx_catch_3); _fx_catch_3: ; } _fx_cleanup: ; if (sl_0) { _fx_free_LN15C_form__cstmt_t(&sl_0); } return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t( struct _fx_R5PP__t* pp_0, struct _fx_N15C_form__cstmt_t_data_t* s_0, void* fx_fv) { int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); int tag_0 = FX_REC_VARIANT_TAG(s_0); if (tag_0 == 1) { fx_str_t slit_0 = FX_MAKE_STR("{}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_0, 0), _fx_catch_0); _fx_catch_0: ; } else if (tag_0 == 2) { FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &s_0->u.CComment.t0, 0), _fx_catch_1); _fx_catch_1: ; } else if (tag_0 == 3) { _fx_N14C_form__cexp_t e_0 = s_0->u.CExp; FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_0, 0, 0), _fx_catch_3); if (FX_REC_VARIANT_TAG(e_0) != 12) { fx_str_t slit_1 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_1, 0), _fx_catch_2); _fx_catch_2: ; } FX_CHECK_EXN(_fx_catch_3); _fx_catch_3: ; } else if (tag_0 == 4) { fx_str_t slit_2 = FX_MAKE_STR("break;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_2, 0), _fx_catch_4); _fx_catch_4: ; } else if (tag_0 == 5) { fx_str_t slit_3 = FX_MAKE_STR("continue;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_3, 0), _fx_catch_5); _fx_catch_5: ; } else if (tag_0 == 6) { _fx_Nt6option1N14C_form__cexp_t* e_opt_0 = &s_0->u.CStmtReturn.t0; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_7); fx_str_t slit_4 = FX_MAKE_STR("return"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_4, 0), _fx_catch_7); if (e_opt_0->tag == 2) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_6); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_opt_0->u.Some, 0, 0), _fx_catch_6); _fx_catch_6: ; } FX_CHECK_EXN(_fx_catch_7); fx_str_t slit_5 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_5, 0), _fx_catch_7); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_7); _fx_catch_7: ; } else if (tag_0 == 7) { FX_CALL(_fx_M4C_ppFM21pprint_cstmt_as_blockv2R5PP__tN15C_form__cstmt_t(pp_0, s_0, 0), _fx_catch_8); _fx_catch_8: ; } else if (tag_0 == 8) { fx_str_t v_0 = {0}; fx_str_t nstr_0 = {0}; fx_str_t v_1 = {0}; fx_str_t v_2 = {0}; _fx_T2R9Ast__id_tN15C_form__cstmt_t* vcase_0 = &s_0->u.CStmtSync; _fx_R9Ast__id_t* n_0 = &vcase_0->t0; if (_fx_g12Options__opt.enable_openmp) { FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_9); fx_str_t slit_6 = FX_MAKE_STR("#pragma omp critical"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_6, 0), _fx_catch_9); bool res_0; FX_CALL(_fx_M4C_ppFM6__ne__B2R9Ast__id_tR9Ast__id_t(n_0, &_fx_g9Ast__noid, &res_0, 0), _fx_catch_9); if (res_0) { FX_CALL(_fx_M3AstFM2ppS1RM4id_t(n_0, &v_0, 0), _fx_catch_9); fx_str_t slit_7 = FX_MAKE_STR("."); fx_str_t slit_8 = FX_MAKE_STR("__"); FX_CALL(_fx_M6StringFM7replaceS3SSS(&v_0, &slit_7, &slit_8, &nstr_0, 0), _fx_catch_9); FX_CALL(_fx_M4C_ppFM6stringS1S(&nstr_0, &v_1, 0), _fx_catch_9); fx_str_t slit_9 = FX_MAKE_STR(" ("); fx_str_t slit_10 = FX_MAKE_STR(")"); { const fx_str_t strs_0[] = { slit_9, v_1, slit_10 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 3, &v_2), _fx_catch_9); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_2, 0), _fx_catch_9); } FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_9); } FX_CALL(_fx_M4C_ppFM21pprint_cstmt_as_blockv2R5PP__tN15C_form__cstmt_t(pp_0, vcase_0->t1, 0), _fx_catch_9); _fx_catch_9: ; FX_FREE_STR(&v_2); FX_FREE_STR(&v_1); FX_FREE_STR(&nstr_0); FX_FREE_STR(&v_0); } else if (tag_0 == 9) { _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* vcase_1 = &s_0->u.CStmtIf; fx_str_t slit_11 = FX_MAKE_STR("if"); FX_CALL( _fx_M4C_ppFM16print_cascade_ifv5SN14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR5PP__t(&slit_11, vcase_1->t0, vcase_1->t1, vcase_1->t2, pp_0, 0), _fx_catch_10); _fx_catch_10: ; } else if (tag_0 == 10) { _fx_T2R9Ast__id_tR10Ast__loc_t* vcase_2 = &s_0->u.CStmtGoto; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_11); fx_str_t slit_12 = FX_MAKE_STR("goto"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_12, 0), _fx_catch_11); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_11); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_2->t0, &vcase_2->t1, 0), _fx_catch_11); fx_str_t slit_13 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_13, 0), _fx_catch_11); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_11); _fx_catch_11: ; } else if (tag_0 == 11) { _fx_T2R9Ast__id_tR10Ast__loc_t* vcase_3 = &s_0->u.CStmtLabel; FX_CALL(_fx_M2PPFM6breakuv1RM1t(pp_0, 0), _fx_catch_12); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_3->t0, &vcase_3->t1, 0), _fx_catch_12); fx_str_t slit_14 = FX_MAKE_STR(": ;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_14, 0), _fx_catch_12); _fx_catch_12: ; } else if (tag_0 == 12) { _fx_T6Nt6option1N14C_form__ctyp_tLN14C_form__cexp_tNt6option1N14C_form__cexp_tLN14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* vcase_4 = &s_0->u.CStmtFor; _fx_LN14C_form__cexp_t e3_0 = vcase_4->t3; _fx_Nt6option1N14C_form__cexp_t* e2_opt_0 = &vcase_4->t2; _fx_LN14C_form__cexp_t e1_0 = vcase_4->t1; _fx_Nt6option1N14C_form__ctyp_t* t_opt_0 = &vcase_4->t0; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_17); fx_str_t slit_15 = FX_MAKE_STR("for ("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_15, 0), _fx_catch_17); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_17); if (e1_0 != 0) { if (t_opt_0->tag == 2) { FX_CALL( _fx_M4C_ppFM8pp_ctyp_v4R5PP__tN14C_form__ctyp_tNt6option1R9Ast__id_tR10Ast__loc_t(pp_0, t_opt_0->u.Some, &_fx_g10C_pp__None, &vcase_4->t5, 0), _fx_catch_13); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_13); _fx_catch_13: ; } FX_CHECK_EXN(_fx_catch_14); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_14); FX_CALL(_fx_M4C_ppFM8pp_elistv2R5PP__tLN14C_form__cexp_t(pp_0, e1_0, 0), _fx_catch_14); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_14); _fx_catch_14: ; } FX_CHECK_EXN(_fx_catch_17); fx_str_t slit_16 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_16, 0), _fx_catch_17); if (e2_opt_0->tag == 2) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_15); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e2_opt_0->u.Some, 0, 0), _fx_catch_15); _fx_catch_15: ; } FX_CHECK_EXN(_fx_catch_17); fx_str_t slit_17 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_17, 0), _fx_catch_17); if (e3_0 != 0) { FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_16); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_16); FX_CALL(_fx_M4C_ppFM8pp_elistv2R5PP__tLN14C_form__cexp_t(pp_0, e3_0, 0), _fx_catch_16); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_16); _fx_catch_16: ; } FX_CHECK_EXN(_fx_catch_17); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_17); fx_str_t slit_18 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_18, 0), _fx_catch_17); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_17); FX_CALL(_fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t(pp_0, vcase_4->t4, 0), _fx_catch_17); _fx_catch_17: ; } else if (tag_0 == 13) { _fx_T3N14C_form__cexp_tN15C_form__cstmt_tR10Ast__loc_t* vcase_5 = &s_0->u.CStmtWhile; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_18); fx_str_t slit_19 = FX_MAKE_STR("while ("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_19, 0), _fx_catch_18); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_18); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_5->t0, 0, 0), _fx_catch_18); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_18); fx_str_t slit_20 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_20, 0), _fx_catch_18); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_18); FX_CALL(_fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t(pp_0, vcase_5->t1, 0), _fx_catch_18); _fx_catch_18: ; } else if (tag_0 == 14) { _fx_T3N15C_form__cstmt_tN14C_form__cexp_tR10Ast__loc_t* vcase_6 = &s_0->u.CStmtDoWhile; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_19); fx_str_t slit_21 = FX_MAKE_STR("do"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_21, 0), _fx_catch_19); FX_CALL(_fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t(pp_0, vcase_6->t0, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_19); fx_str_t slit_22 = FX_MAKE_STR("while ("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_22, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_19); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_6->t1, 0, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_19); fx_str_t slit_23 = FX_MAKE_STR(");"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_23, 0), _fx_catch_19); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_19); _fx_catch_19: ; } else if (tag_0 == 15) { _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t cases_0 = 0; _fx_T3N14C_form__cexp_tLT2LN14C_form__cexp_tLN15C_form__cstmt_tR10Ast__loc_t* vcase_7 = &s_0->u.CStmtSwitch; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_25); fx_str_t slit_24 = FX_MAKE_STR("switch ("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_24, 0), _fx_catch_25); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_25); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, vcase_7->t0, 0, 0), _fx_catch_25); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_25); fx_str_t slit_25 = FX_MAKE_STR(") {"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_25, 0), _fx_catch_25); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_25); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_25); FX_COPY_PTR(vcase_7->t1, &cases_0); _fx_LT2LN14C_form__cexp_tLN15C_form__cstmt_t lst_0 = cases_0; for (; lst_0; lst_0 = lst_0->tl) { _fx_LN14C_form__cexp_t labels_0 = 0; _fx_LN15C_form__cstmt_t code_0 = 0; fx_str_t v_3 = {0}; fx_str_t v_4 = {0}; _fx_T2LN14C_form__cexp_tLN15C_form__cstmt_t* __pat___0 = &lst_0->hd; FX_COPY_PTR(__pat___0->t0, &labels_0); FX_COPY_PTR(__pat___0->t1, &code_0); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_24); bool isdefault_0; if (labels_0 == 0) { fx_str_t slit_26 = FX_MAKE_STR("default:"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_26, 0), _fx_catch_20); isdefault_0 = true; _fx_catch_20: ; } else { _fx_LN14C_form__cexp_t lst_1 = labels_0; for (; lst_1; lst_1 = lst_1->tl) { _fx_N14C_form__cexp_t l_0 = lst_1->hd; fx_str_t slit_27 = FX_MAKE_STR("case "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_27, 0), _fx_catch_21); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, l_0, 0, 0), _fx_catch_21); fx_str_t slit_28 = FX_MAKE_STR(":"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_28, 0), _fx_catch_21); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_21); _fx_catch_21: ; FX_CHECK_EXN(_fx_catch_22); } isdefault_0 = false; _fx_catch_22: ; } FX_CHECK_EXN(_fx_catch_24); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_24); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_24); FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_catch_24); int_ v_5; FX_CALL(_fx_M4C_ppFM8length1_i1LN15C_form__cstmt_t(code_0, &v_5, 0), _fx_catch_24); int_ t_0; if (isdefault_0) { t_0 = 0; } else { t_0 = 1; } int_ codelen_0 = v_5 + t_0; int_ i_0 = 0; _fx_LN15C_form__cstmt_t lst_2 = code_0; for (; lst_2; lst_2 = lst_2->tl, i_0 += 1) { _fx_N15C_form__cstmt_t s_1 = lst_2->hd; if (i_0 == 0) { fx_str_t slit_29 = FX_MAKE_STR(" "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_29, 0), _fx_catch_23); } FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_1, 0), _fx_catch_23); if (i_0 < codelen_0 - 1) { FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_23); } _fx_catch_23: ; FX_CHECK_EXN(_fx_catch_24); } if (isdefault_0) { if (code_0 == 0) { FX_CALL(_fx_F7__mul__S2Ci((char_)32, 3, &v_3, 0), _fx_catch_24); fx_str_t slit_30 = FX_MAKE_STR(";"); { const fx_str_t strs_1[] = { v_3, slit_30 }; FX_CALL(fx_strjoin(0, 0, 0, strs_1, 2, &v_4), _fx_catch_24); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_4, 0), _fx_catch_24); } } else { fx_str_t slit_31 = FX_MAKE_STR("break;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_31, 0), _fx_catch_24); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_24); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_24); _fx_catch_24: ; FX_FREE_STR(&v_4); FX_FREE_STR(&v_3); if (code_0) { _fx_free_LN15C_form__cstmt_t(&code_0); } if (labels_0) { _fx_free_LN14C_form__cexp_t(&labels_0); } FX_CHECK_EXN(_fx_catch_25); } fx_str_t slit_32 = FX_MAKE_STR("}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_32, 0), _fx_catch_25); _fx_catch_25: ; if (cases_0) { _fx_free_LT2LN14C_form__cexp_tLN15C_form__cstmt_t(&cases_0); } } else if (tag_0 == 16) { _fx_N15C_form__cinfo_t v_6 = {0}; _fx_T4N14C_form__ctyp_tR9Ast__id_tNt6option1N14C_form__cexp_tR10Ast__loc_t* vcase_8 = &s_0->u.CDefVal; _fx_R10Ast__loc_t* loc_0 = &vcase_8->t3; _fx_Nt6option1N14C_form__cexp_t* e_opt_1 = &vcase_8->t2; _fx_R9Ast__id_t* n_1 = &vcase_8->t1; FX_CALL(_fx_M6C_formFM6cinfo_N15C_form__cinfo_t2R9Ast__id_tR10Ast__loc_t(n_1, loc_0, &v_6, 0), _fx_catch_27); bool is_private_0; if (v_6.tag == 2) { is_private_0 = v_6.u.CVal.cv_flags.val_flag_private; } else { is_private_0 = false; } FX_CHECK_EXN(_fx_catch_27); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_27); if (is_private_0) { fx_str_t slit_33 = FX_MAKE_STR("static"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_33, 0), _fx_catch_27); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_27); } _fx_Nt6option1R9Ast__id_t v_7; _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t(n_1, &v_7); FX_CALL( _fx_M4C_ppFM8pp_ctyp_v4R5PP__tN14C_form__ctyp_tNt6option1R9Ast__id_tR10Ast__loc_t(pp_0, vcase_8->t0, &v_7, loc_0, 0), _fx_catch_27); if (e_opt_1->tag == 2) { fx_str_t slit_34 = FX_MAKE_STR(" ="); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_34, 0), _fx_catch_26); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_26); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_opt_1->u.Some, 0, 0), _fx_catch_26); _fx_catch_26: ; } FX_CHECK_EXN(_fx_catch_27); fx_str_t slit_35 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_35, 0), _fx_catch_27); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_27); _fx_catch_27: ; _fx_free_N15C_form__cinfo_t(&v_6); } else if (tag_0 == 17) { _fx_LN15C_form__cstmt_t cf_body_0 = 0; _fx_R17C_form__cdeffun_t* v_8 = &s_0->u.CDefFun->data; _fx_R10Ast__loc_t cf_loc_0 = v_8->cf_loc; FX_COPY_PTR(v_8->cf_body, &cf_body_0); _fx_R9Ast__id_t cf_name_0 = v_8->cf_name; FX_CALL(_fx_M4C_ppFM14pprint_fun_hdrv5R5PP__tR9Ast__id_tBR10Ast__loc_tB(pp_0, &cf_name_0, false, &cf_loc_0, false, 0), _fx_catch_29); FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_catch_29); fx_str_t slit_36 = FX_MAKE_STR("{"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_36, 0), _fx_catch_29); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_29); int_ i_1 = 0; _fx_LN15C_form__cstmt_t lst_3 = cf_body_0; for (; lst_3; lst_3 = lst_3->tl, i_1 += 1) { _fx_N15C_form__cstmt_t s_2 = lst_3->hd; if (i_1 > 0) { FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_28); } FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_2, 0), _fx_catch_28); _fx_catch_28: ; FX_CHECK_EXN(_fx_catch_29); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_29); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_29); fx_str_t slit_37 = FX_MAKE_STR("}"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_37, 0), _fx_catch_29); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_29); _fx_catch_29: ; if (cf_body_0) { _fx_free_LN15C_form__cstmt_t(&cf_body_0); } } else if (tag_0 == 19) { _fx_N15C_form__cinfo_t v_9 = {0}; _fx_T2R9Ast__id_tR10Ast__loc_t* vcase_9 = &s_0->u.CDefForwardSym; _fx_R10Ast__loc_t* cf_loc_1 = &vcase_9->t1; _fx_R9Ast__id_t* cf_name_1 = &vcase_9->t0; FX_CALL(_fx_M6C_formFM6cinfo_N15C_form__cinfo_t2R9Ast__id_tR10Ast__loc_t(cf_name_1, cf_loc_1, &v_9, 0), _fx_catch_33); int tag_1 = v_9.tag; if (tag_1 == 3) { FX_CALL(_fx_M4C_ppFM14pprint_fun_hdrv5R5PP__tR9Ast__id_tBR10Ast__loc_tB(pp_0, cf_name_1, true, cf_loc_1, true, 0), _fx_catch_30); _fx_catch_30: ; } else if (tag_1 == 2) { FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_31); fx_str_t slit_38 = FX_MAKE_STR("FX_EXTERN_C_VAL("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_38, 0), _fx_catch_31); FX_CALL(_fx_M2PPFM3cutv1RM1t(pp_0, 0), _fx_catch_31); _fx_Nt6option1R9Ast__id_t v_10; _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t(cf_name_1, &v_10); fx_str_t slit_39 = FX_MAKE_STR(""); fx_str_t slit_40 = FX_MAKE_STR(")"); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_39, &slit_40, v_9.u.CVal.cv_typ, &v_10, true, cf_loc_1, 0), _fx_catch_31); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_31); _fx_catch_31: ; } else { fx_str_t v_11 = {0}; fx_str_t v_12 = {0}; fx_str_t v_13 = {0}; fx_exn_t v_14 = {0}; FX_CALL(_fx_M6C_formFM7idc2strS2R9Ast__id_tR10Ast__loc_t(cf_name_1, cf_loc_1, &v_11, 0), _fx_catch_32); FX_CALL(_fx_M4C_ppFM6stringS1S(&v_11, &v_12, 0), _fx_catch_32); fx_str_t slit_41 = FX_MAKE_STR("the forward declaration of "); fx_str_t slit_42 = FX_MAKE_STR(" does not reference a function or a value"); { const fx_str_t strs_2[] = { slit_41, v_12, slit_42 }; FX_CALL(fx_strjoin(0, 0, 0, strs_2, 3, &v_13), _fx_catch_32); } FX_CALL(_fx_M3AstFM11compile_errE2RM5loc_tS(cf_loc_1, &v_13, &v_14, 0), _fx_catch_32); FX_THROW(&v_14, false, _fx_catch_32); _fx_catch_32: ; fx_free_exn(&v_14); FX_FREE_STR(&v_13); FX_FREE_STR(&v_12); FX_FREE_STR(&v_11); } FX_CHECK_EXN(_fx_catch_33); _fx_catch_33: ; _fx_free_N15C_form__cinfo_t(&v_9); } else if (tag_0 == 18) { _fx_N14C_form__ctyp_t ct_typ_0 = 0; _fx_R17C_form__cdeftyp_t* v_15 = &s_0->u.CDefTyp->data; _fx_R10Ast__loc_t ct_loc_0 = v_15->ct_loc; FX_COPY_PTR(v_15->ct_typ, &ct_typ_0); _fx_R9Ast__id_t ct_name_0 = v_15->ct_name; _fx_Nt6option1R9Ast__id_t v_16; _fx_M4C_ppFM4SomeNt6option1R9Ast__id_t1R9Ast__id_t(&ct_name_0, &v_16); fx_str_t slit_43 = FX_MAKE_STR("typedef "); fx_str_t slit_44 = FX_MAKE_STR(";"); FX_CALL( _fx_M4C_ppFM9pp_ctyp__v7R5PP__tSSN14C_form__ctyp_tNt6option1R9Ast__id_tBR10Ast__loc_t(pp_0, &slit_43, &slit_44, ct_typ_0, &v_16, true, &ct_loc_0, 0), _fx_catch_34); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_34); _fx_catch_34: ; if (ct_typ_0) { _fx_free_N14C_form__ctyp_t(&ct_typ_0); } } else if (tag_0 == 20) { _fx_T2R9Ast__id_tR10Ast__loc_t* vcase_10 = &s_0->u.CDefForwardTyp; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_35); fx_str_t slit_45 = FX_MAKE_STR("struct "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_45, 0), _fx_catch_35); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_10->t0, &vcase_10->t1, 0), _fx_catch_35); fx_str_t slit_46 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_46, 0), _fx_catch_35); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_35); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_35); _fx_catch_35: ; } else if (tag_0 == 21) { _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t cenum_members_0 = 0; fx_str_t cenum_cname_0 = {0}; _fx_R18C_form__cdefenum_t* v_17 = &s_0->u.CDefEnum->data; _fx_R10Ast__loc_t cenum_loc_0 = v_17->cenum_loc; FX_COPY_PTR(v_17->cenum_members, &cenum_members_0); fx_copy_str(&v_17->cenum_cname, &cenum_cname_0); fx_str_t slit_47 = FX_MAKE_STR("typedef enum {"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_47, 0), _fx_catch_38); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_38); FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_catch_38); int_ i_2 = 0; _fx_LT2R9Ast__id_tNt6option1N14C_form__cexp_t lst_4 = cenum_members_0; for (; lst_4; lst_4 = lst_4->tl, i_2 += 1) { _fx_Nt6option1N14C_form__cexp_t e_opt_2 = {0}; _fx_T2R9Ast__id_tNt6option1N14C_form__cexp_t* __pat___1 = &lst_4->hd; _fx_R9Ast__id_t n_2 = __pat___1->t0; _fx_copy_Nt6option1N14C_form__cexp_t(&__pat___1->t1, &e_opt_2); if (i_2 == 0) { fx_str_t slit_48 = FX_MAKE_STR(" "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_48, 0), _fx_catch_37); } else { fx_str_t slit_49 = FX_MAKE_STR(","); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_49, 0), _fx_catch_37); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_37); } FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &n_2, &cenum_loc_0, 0), _fx_catch_37); if (e_opt_2.tag == 2) { fx_str_t slit_50 = FX_MAKE_STR("="); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_50, 0), _fx_catch_36); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_opt_2.u.Some, 0, 0), _fx_catch_36); _fx_catch_36: ; } FX_CHECK_EXN(_fx_catch_37); _fx_catch_37: ; _fx_free_Nt6option1N14C_form__cexp_t(&e_opt_2); FX_CHECK_EXN(_fx_catch_38); } FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_38); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_38); fx_str_t slit_51 = FX_MAKE_STR("} "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_51, 0), _fx_catch_38); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &cenum_cname_0, 0), _fx_catch_38); fx_str_t slit_52 = FX_MAKE_STR(";"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_52, 0), _fx_catch_38); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_38); _fx_catch_38: ; FX_FREE_STR(&cenum_cname_0); if (cenum_members_0) { _fx_free_LT2R9Ast__id_tNt6option1N14C_form__cexp_t(&cenum_members_0); } } else if (tag_0 == 22) { fx_str_t ci_cname_0 = {0}; fx_str_t v_18 = {0}; fx_str_t v_19 = {0}; fx_str_t vtbl_cname_0 = {0}; fx_str_t v_20 = {0}; fx_str_t v_21 = {0}; _fx_R23C_form__cdefinterface_t* v_22 = &s_0->u.CDefInterface->data; _fx_R10Ast__loc_t ci_loc_0 = v_22->ci_loc; _fx_R9Ast__id_t ci_vtbl_0 = v_22->ci_vtbl; fx_copy_str(&v_22->ci_cname, &ci_cname_0); FX_CALL(_fx_M2PPFM6beginvv1RM1t(pp_0, 0), _fx_catch_39); FX_CALL(_fx_M4C_ppFM6stringS1S(&ci_cname_0, &v_18, 0), _fx_catch_39); fx_str_t slit_53 = FX_MAKE_STR("typedef struct "); fx_str_t slit_54 = FX_MAKE_STR(" {"); { const fx_str_t strs_3[] = { slit_53, v_18, slit_54 }; FX_CALL(fx_strjoin(0, 0, 0, strs_3, 3, &v_19), _fx_catch_39); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_19, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_39); FX_CALL(_fx_M6C_formFM13get_idc_cnameS2R9Ast__id_tR10Ast__loc_t(&ci_vtbl_0, &ci_loc_0, &vtbl_cname_0, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &vtbl_cname_0, 0), _fx_catch_39); fx_str_t slit_55 = FX_MAKE_STR("* vtbl;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_55, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_39); fx_str_t slit_56 = FX_MAKE_STR("fx_object_t* obj;"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_56, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_39); FX_CALL(_fx_M4C_ppFM6stringS1S(&ci_cname_0, &v_20, 0), _fx_catch_39); fx_str_t slit_57 = FX_MAKE_STR("} "); fx_str_t slit_58 = FX_MAKE_STR(";"); { const fx_str_t strs_4[] = { slit_57, v_20, slit_58 }; FX_CALL(fx_strjoin(0, 0, 0, strs_4, 3, &v_21), _fx_catch_39); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_21, 0), _fx_catch_39); FX_CALL(_fx_M2PPFM7newlinev1RM1t(pp_0, 0), _fx_catch_39); _fx_catch_39: ; FX_FREE_STR(&v_21); FX_FREE_STR(&v_20); FX_FREE_STR(&vtbl_cname_0); FX_FREE_STR(&v_19); FX_FREE_STR(&v_18); FX_FREE_STR(&ci_cname_0); } else if (tag_0 == 23) { _fx_LN15C_form__cstmt_t cm_body_0 = 0; _fx_LR9Ast__id_t cm_args_0 = 0; fx_str_t cm_cname_0 = {0}; _fx_R19C_form__cdefmacro_t* v_23 = &s_0->u.CMacroDef->data; _fx_R10Ast__loc_t cm_loc_0 = v_23->cm_loc; FX_COPY_PTR(v_23->cm_body, &cm_body_0); FX_COPY_PTR(v_23->cm_args, &cm_args_0); fx_copy_str(&v_23->cm_cname, &cm_cname_0); fx_str_t slit_59 = FX_MAKE_STR("#define "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_59, 0), _fx_catch_44); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &cm_cname_0, 0), _fx_catch_44); if (cm_args_0 != 0) { fx_str_t slit_60 = FX_MAKE_STR("("); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_60, 0), _fx_catch_41); int_ i_3 = 0; _fx_LR9Ast__id_t lst_5 = cm_args_0; for (; lst_5; lst_5 = lst_5->tl, i_3 += 1) { _fx_R9Ast__id_t* a_0 = &lst_5->hd; if (i_3 > 0) { fx_str_t slit_61 = FX_MAKE_STR(", "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_61, 0), _fx_catch_40); } FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, a_0, &cm_loc_0, 0), _fx_catch_40); _fx_catch_40: ; FX_CHECK_EXN(_fx_catch_41); } fx_str_t slit_62 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_62, 0), _fx_catch_41); _fx_catch_41: ; } FX_CHECK_EXN(_fx_catch_44); if (cm_body_0 != 0) { _fx_LN15C_form__cstmt_t lst_6 = cm_body_0; for (; lst_6; lst_6 = lst_6->tl) { _fx_N15C_form__cstmt_t s_3 = lst_6->hd; FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_42); fx_str_t slit_63 = FX_MAKE_STR("\\"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_63, 0), _fx_catch_42); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_42); fx_str_t slit_64 = FX_MAKE_STR(" "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_64, 0), _fx_catch_42); FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_3, 0), _fx_catch_42); _fx_catch_42: ; FX_CHECK_EXN(_fx_catch_43); } _fx_catch_43: ; } FX_CHECK_EXN(_fx_catch_44); _fx_catch_44: ; FX_FREE_STR(&cm_cname_0); FX_FREE_LIST_SIMPLE(&cm_args_0); if (cm_body_0) { _fx_free_LN15C_form__cstmt_t(&cm_body_0); } } else if (tag_0 == 24) { _fx_T2R9Ast__id_tR10Ast__loc_t* vcase_11 = &s_0->u.CMacroUndef; FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_45); fx_str_t slit_65 = FX_MAKE_STR("#undef "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_65, 0), _fx_catch_45); FX_CALL(_fx_M4C_ppFM5pp_idv3R5PP__tR9Ast__id_tR10Ast__loc_t(pp_0, &vcase_11->t0, &vcase_11->t1, 0), _fx_catch_45); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_45); _fx_catch_45: ; } else if (tag_0 == 25) { _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t cs_l_0 = 0; _fx_T3LT2N14C_form__cexp_tLN15C_form__cstmt_tLN15C_form__cstmt_tR10Ast__loc_t* vcase_12 = &s_0->u.CMacroIf; _fx_LN15C_form__cstmt_t else_l_0 = vcase_12->t1; int_ i_4 = 0; FX_COPY_PTR(vcase_12->t0, &cs_l_0); _fx_LT2N14C_form__cexp_tLN15C_form__cstmt_t lst_7 = cs_l_0; for (; lst_7; lst_7 = lst_7->tl, i_4 += 1) { _fx_N14C_form__cexp_t c_0 = 0; _fx_LN15C_form__cstmt_t sl_0 = 0; fx_str_t v_24 = {0}; _fx_T2N14C_form__cexp_tLN15C_form__cstmt_t* __pat___2 = &lst_7->hd; FX_COPY_PTR(__pat___2->t0, &c_0); FX_COPY_PTR(__pat___2->t1, &sl_0); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_47); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_47); if (i_4 == 0) { fx_str_t slit_66 = FX_MAKE_STR("#if "); fx_copy_str(&slit_66, &v_24); } else { fx_str_t slit_67 = FX_MAKE_STR("#elif "); fx_copy_str(&slit_67, &v_24); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_24, 0), _fx_catch_47); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, c_0, 0, 0), _fx_catch_47); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_47); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_47); _fx_LN15C_form__cstmt_t lst_8 = sl_0; for (; lst_8; lst_8 = lst_8->tl) { _fx_N15C_form__cstmt_t s_4 = lst_8->hd; FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_4, 0), _fx_catch_46); _fx_catch_46: ; FX_CHECK_EXN(_fx_catch_47); } _fx_catch_47: ; FX_FREE_STR(&v_24); if (sl_0) { _fx_free_LN15C_form__cstmt_t(&sl_0); } if (c_0) { _fx_free_N14C_form__cexp_t(&c_0); } FX_CHECK_EXN(_fx_catch_50); } if (else_l_0 != 0) { _fx_LN15C_form__cstmt_t else_l_1 = 0; FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_49); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_49); fx_str_t slit_68 = FX_MAKE_STR("#else"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_68, 0), _fx_catch_49); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_49); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_49); FX_COPY_PTR(else_l_0, &else_l_1); _fx_LN15C_form__cstmt_t lst_9 = else_l_1; for (; lst_9; lst_9 = lst_9->tl) { _fx_N15C_form__cstmt_t s_5 = lst_9->hd; FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(pp_0, s_5, 0), _fx_catch_48); _fx_catch_48: ; FX_CHECK_EXN(_fx_catch_49); } _fx_catch_49: ; if (else_l_1) { _fx_free_LN15C_form__cstmt_t(&else_l_1); } } FX_CHECK_EXN(_fx_catch_50); FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_50); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_50); fx_str_t slit_69 = FX_MAKE_STR("#endif"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_69, 0), _fx_catch_50); _fx_catch_50: ; if (cs_l_0) { _fx_free_LT2N14C_form__cexp_tLN15C_form__cstmt_t(&cs_l_0); } } else if (tag_0 == 26) { FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_51); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_51); fx_str_t slit_70 = FX_MAKE_STR("#include "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_70, 0), _fx_catch_51); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &s_0->u.CMacroInclude.t0, 0), _fx_catch_51); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_51); _fx_catch_51: ; } else if (tag_0 == 27) { FX_CALL(_fx_M2PPFM6break0v1RM1t(pp_0, 0), _fx_catch_52); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_52); fx_str_t slit_71 = FX_MAKE_STR("#pragma "); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_71, 0), _fx_catch_52); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &s_0->u.CMacroPragma.t0, 0), _fx_catch_52); FX_CALL(_fx_M2PPFM3endv1RM1t(pp_0, 0), _fx_catch_52); _fx_catch_52: ; } else { FX_FAST_THROW(FX_EXN_NoMatchError, _fx_cleanup); } _fx_cleanup: ; return fx_status; } static int _fx_M4C_ppFM16print_cascade_ifv5SN14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR5PP__t( fx_str_t* prefix_0, struct _fx_N14C_form__cexp_t_data_t* e_0, struct _fx_N15C_form__cstmt_t_data_t* s1_0, struct _fx_N15C_form__cstmt_t_data_t* s2_0, struct _fx_R5PP__t* pp_0, void* fx_fv) { fx_str_t prefix_1 = {0}; _fx_N14C_form__cexp_t e_1 = 0; _fx_N15C_form__cstmt_t s1_1 = 0; _fx_N15C_form__cstmt_t s2_1 = 0; int fx_status = 0; FX_CALL(fx_check_stack(), _fx_cleanup); fx_copy_str(prefix_0, &prefix_1); FX_COPY_PTR(e_0, &e_1); FX_COPY_PTR(s1_0, &s1_1); FX_COPY_PTR(s2_0, &s2_1); for (;;) { fx_str_t prefix_2 = {0}; _fx_N14C_form__cexp_t e_2 = 0; _fx_N15C_form__cstmt_t s1_2 = 0; _fx_N15C_form__cstmt_t s2_2 = 0; fx_str_t v_0 = {0}; fx_copy_str(&prefix_1, &prefix_2); FX_COPY_PTR(e_1, &e_2); FX_COPY_PTR(s1_1, &s1_2); FX_COPY_PTR(s2_1, &s2_2); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_3); fx_str_t slit_0 = FX_MAKE_STR(" ("); { const fx_str_t strs_0[] = { prefix_2, slit_0 }; FX_CALL(fx_strjoin(0, 0, 0, strs_0, 2, &v_0), _fx_catch_3); } FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &v_0, 0), _fx_catch_3); FX_CALL(_fx_M4C_ppFM8pp_cexp_v3R5PP__tN14C_form__cexp_ti(pp_0, e_2, 0, 0), _fx_catch_3); fx_str_t slit_1 = FX_MAKE_STR(")"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_1, 0), _fx_catch_3); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_3); FX_CALL(_fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t(pp_0, s1_2, 0), _fx_catch_3); int tag_0 = FX_REC_VARIANT_TAG(s2_2); bool res_0; if (tag_0 == 1) { res_0 = true; goto _fx_endmatch_0; } if (tag_0 == 7) { if (s2_2->u.CStmtBlock.t0 == 0) { res_0 = true; goto _fx_endmatch_0; } } res_0 = false; _fx_endmatch_0: ; FX_CHECK_EXN(_fx_catch_3); if (res_0) { FX_BREAK(_fx_catch_0); _fx_catch_0: ; goto _fx_endmatch_1; } if (tag_0 == 9) { _fx_T4N14C_form__cexp_tN15C_form__cstmt_tN15C_form__cstmt_tR10Ast__loc_t* vcase_0 = &s2_2->u.CStmtIf; FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_1); fx_str_t slit_2 = FX_MAKE_STR("else if"); FX_FREE_STR(&prefix_1); fx_copy_str(&slit_2, &prefix_1); _fx_N14C_form__cexp_t* e__0 = &vcase_0->t0; _fx_free_N14C_form__cexp_t(&e_1); FX_COPY_PTR(*e__0, &e_1); _fx_N15C_form__cstmt_t* s1__0 = &vcase_0->t1; _fx_free_N15C_form__cstmt_t(&s1_1); FX_COPY_PTR(*s1__0, &s1_1); _fx_N15C_form__cstmt_t* s2__0 = &vcase_0->t2; _fx_free_N15C_form__cstmt_t(&s2_1); FX_COPY_PTR(*s2__0, &s2_1); _fx_catch_1: ; goto _fx_endmatch_1; } FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_2); FX_CALL(_fx_M2PPFM5beginv1RM1t(pp_0, 0), _fx_catch_2); fx_str_t slit_3 = FX_MAKE_STR("else"); FX_CALL(_fx_M2PPFM3strv2RM1tS(pp_0, &slit_3, 0), _fx_catch_2); FX_CALL(_fx_M2PPFM5spacev1RM1t(pp_0, 0), _fx_catch_2); FX_CALL(_fx_M4C_ppFM26pprint_cstmt_or_block_cboxv2R5PP__tN15C_form__cstmt_t(pp_0, s2_2, 0), _fx_catch_2); FX_BREAK(_fx_catch_2); _fx_catch_2: ; _fx_endmatch_1: ; FX_CHECK_EXN(_fx_catch_3); _fx_catch_3: ; FX_FREE_STR(&v_0); if (s2_2) { _fx_free_N15C_form__cstmt_t(&s2_2); } if (s1_2) { _fx_free_N15C_form__cstmt_t(&s1_2); } if (e_2) { _fx_free_N14C_form__cexp_t(&e_2); } FX_FREE_STR(&prefix_2); FX_CHECK_BREAK(); FX_CHECK_EXN(_fx_cleanup); } _fx_cleanup: ; FX_FREE_STR(&prefix_1); if (e_1) { _fx_free_N14C_form__cexp_t(&e_1); } if (s1_1) { _fx_free_N15C_form__cstmt_t(&s1_1); } if (s2_1) { _fx_free_N15C_form__cstmt_t(&s2_1); } return fx_status; } FX_EXTERN_C int _fx_M4C_ppFM20pprint_top_to_stringS1LN15C_form__cstmt_t( struct _fx_LN15C_form__cstmt_t_data_t* code_0, fx_str_t* fx_result, void* fx_fv) { _fx_R5PP__t pp_0 = {0}; _fx_LS all_lines_0 = 0; int fx_status = 0; FX_CALL(_fx_M2PPFM21pprint_to_string_listRM1t2ii(128, 3, &pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM6beginvv2RM1ti(&pp_0, 0, 0), _fx_cleanup); int_ i_0 = 0; _fx_LN15C_form__cstmt_t lst_0 = code_0; for (; lst_0; lst_0 = lst_0->tl, i_0 += 1) { _fx_N15C_form__cstmt_t s_0 = lst_0->hd; if (i_0 != 0) { FX_CALL(_fx_M2PPFM6break0v1RM1t(&pp_0, 0), _fx_catch_0); } FX_CALL(_fx_M4C_ppFM9pp_cstmt_v2R5PP__tN15C_form__cstmt_t(&pp_0, s_0, 0), _fx_catch_0); _fx_catch_0: ; FX_CHECK_EXN(_fx_cleanup); } FX_CALL(_fx_M2PPFM7newlinev1RM1t(&pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM3endv1RM1t(&pp_0, 0), _fx_cleanup); FX_CALL(_fx_M2PPFM5flushv1RM1t(&pp_0, 0), _fx_cleanup); _fx_FPLS0* f_0 = &pp_0.get_f; FX_CALL(f_0->fp(&all_lines_0, f_0->fcv), _fx_cleanup); fx_str_t slit_0 = FX_MAKE_STR(""); fx_str_t slit_1 = FX_MAKE_STR("\n"); fx_str_t slit_2 = FX_MAKE_STR("\n"); FX_CALL(_fx_F12join_embraceS4SSSLS(&slit_0, &slit_1, &slit_2, all_lines_0, fx_result, 0), _fx_cleanup); _fx_cleanup: ; _fx_free_R5PP__t(&pp_0); if (all_lines_0) { _fx_free_LS(&all_lines_0); } return fx_status; } FX_EXTERN_C int fx_init_C_pp(void) { int fx_status = 0; return fx_status; } FX_EXTERN_C void fx_deinit_C_pp(void) { }
GB_binop__bor_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bor_int16) // A.*B function (eWiseMult): GB (_AemultB_01__bor_int16) // A.*B function (eWiseMult): GB (_AemultB_02__bor_int16) // A.*B function (eWiseMult): GB (_AemultB_03__bor_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bor_int16) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bor_int16) // C+=b function (dense accum): GB (_Cdense_accumb__bor_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bor_int16) // C=scalar+B GB (_bind1st__bor_int16) // C=scalar+B' GB (_bind1st_tran__bor_int16) // C=A+scalar GB (_bind2nd__bor_int16) // C=A'+scalar GB (_bind2nd_tran__bor_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij) | (bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) | (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BOR || GxB_NO_INT16 || GxB_NO_BOR_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bor_int16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bor_int16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bor_int16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *restrict Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bor_int16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bor_int16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bor_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bor_int16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bor_int16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bor_int16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = GBX (Bx, p, false) ; Cx [p] = (x) | (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bor_int16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) | (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) | (aij) ; \ } GrB_Info GB (_bind1st_tran__bor_int16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) | (y) ; \ } GrB_Info GB (_bind2nd_tran__bor_int16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
lbp.c
#include <stdlib.h> // for malloc #include <math.h> #include <string.h> // for memset #include "private/iocore_private.h" // for getopt #include "private/cvcore_private.h" // count the 0->1 and 1->0 flips in the code static int lbp_numflip(int code, int neighbors) { int numflip = 0; int current = code%2; // get the last bit for (int j=1; j <= neighbors; j++) { int parity = (code >> (j%neighbors)) % 2; // slide the input and get the last bit if (parity != current) { numflip++; } current = parity; } return numflip; } static uint32_t *lbp_lookup(int neighbors, int max_flip, uint32_t *hist_max) { int i; int LookUpSize = pow(2,neighbors); uint32_t *look_up = (uint32_t*) calloc( LookUpSize,sizeof(uint32_t) ); if(look_up == NULL) { return NULL; } uint32_t uniform_id = 0; // create look up table, if it is noise, bin it to last for(i=0; i < LookUpSize; i++) { if( lbp_numflip(i, neighbors) > max_flip) { look_up[i] = UINT32_MAX; } else { look_up[i] = uniform_id++; } } for(i=0; i < LookUpSize; i++) { if( look_up[i] == UINT32_MAX ) { look_up[i] = uniform_id; } } // this will be neighbors*(neighbors-1) + 3 *hist_max = uniform_id+1; // done return look_up; } // creates a default LBP model uint32_t lbp_parameters(uint32_t width, uint32_t height, uint32_t channels, char options[], struct lbp_parameters_t *model) { // fill the default values model->radius = 1; model->neighbors = 8; model->uniform = 1; model->b_size[0] = 4; model->b_size[1] = 4; model->win_width = width; model->win_height = height; // get the user given parameters getopt(uint32_t, options, "radius", &model->radius); getopt(uint32_t, options, "neighbors", &model->neighbors); // uniform (8,2), default value tells not to use uniform lbp getopt(uint32_t, options, "uniform", &model->uniform); getopt(uint32_t, options, "block", model->b_size); // number of neighbors must be between 1-16 if(model->neighbors > 16 || model->neighbors < 1) { model->neighbors = max_2(min_2(model->neighbors, 16), 1); message(WARNING, "number of neighbors must be between 1-16"); } int cell_in_col = (width -2*model->radius) / model->b_size[1]; int cell_in_row = (height-2*model->radius) / model->b_size[0]; /// if uniform mode is on, compute the uniform struct lbp_t model->hist_bin_size = pow(2, model->neighbors); if(model->uniform != model->neighbors) { /// create the uniform lbp look up table model->table = lbp_lookup(model->neighbors, model->uniform, &model->hist_bin_size); if(model->table == NULL) { message(ERROR, "not enough memory"); return 0; } } model->feature_size = model->hist_bin_size*cell_in_col*cell_in_row; // return the created model return model->feature_size; } // "radius:1 neighbors:8 uniform:0 " struct feature_t *lbp_create(uint32_t width, uint32_t height, uint32_t channels, char options[]) { // create a feature model for the output struct feature_t *model = (struct feature_t*) malloc(sizeof(struct feature_t)); check_memory(model, NULL); // fill the algorithm name model->algorithm = CV_LBP; model->image_width = width; model->image_height = height; model->image_channels = channels; // get space for the parameters of the algorithm model->parameters = malloc(sizeof(struct lbp_parameters_t)); if(model->parameters == NULL) { free(model); return NULL; } // fill the parameters model->feature_size = lbp_parameters(width, height, channels, options, model->parameters); if(model->feature_size == 0) { free(model->parameters); free(model); return NULL; } // get the default feature extraction method model->method = lbp_extract; // return the created model return model; } void lbp_view(struct feature_t *par_model) { struct lbp_parameters_t *model = par_model->parameters; printf("Parameters of the Local binary Pattern Model\n"); printf("Options:\n"); printf("> Radius : %d\n", model->radius); printf("> Neighbors : %d\n", model->neighbors); printf("> Block Size : [%d %d]\n", model->b_size[0], model->b_size[1]); printf("> Uniform LBP : %d\n", model->uniform); printf("Computed Values:\n"); printf("> Feature Size : %d\n", model->feature_size); printf("> Histogram Bin : %d\n", model->hist_bin_size); printf("> LBP image size : [%d %d]\n", model->win_width - 2*model->radius, model->win_height - 2*model->radius); } uint32_t lbp_feature_size(struct feature_t *model) { if(model == NULL) { return 0; } return ((struct lbp_parameters_t*)model)->feature_size; } uint32_t lbp_width(struct lbp_parameters_t *model) { if(model == NULL) { return 0; } return model->win_width - 2*model->radius; } uint32_t lbp_height(struct lbp_parameters_t *model) { if(model == NULL) { return 0; } return model->win_height - 2*model->radius; } /* void Computestruct lbp_t8(const unsigned char *src, unsigned char *dst, int cols, int rows) { int numberOfCols; int value; int center; int r0,r1,r5,r6,r7,r8; const unsigned char *p2,*p3,*p4; p2 = src; p3 = p2 + cols; p4 = p3 + cols; dst = dst + cols - 1; rows -= 2; cols -= 2; do { dst += 2; p2 += 2; r0 = *(p2 - 2); r1 = *(p2 - 1); p3 += 2; r7 = *(p3 - 2); r8 = *(p3 - 1); p4 += 2; r6 = *(p4 - 2); r5 = *(p4 - 1); numberOfCols = cols; do { center = r8; center += 2; value = (((center - r0) & 0x80000000) >> 31); r0 = r1; value |= (((center - r1) & 0x80000000) >> 30); r1 = *p2++; value |= (((center - r1) & 0x80000000) >> 29); value |= (((center - r7) & 0x80000000) >> 24); r7 = r8; r8 = *p3++; value |= (((center - r8) & 0x80000000) >> 28); value |= (((center - r6) & 0x80000000) >> 25); r6 = r5; value |= (((center - r5) & 0x80000000) >> 26); r5 = *p4++; value |= (((center - r5) & 0x80000000) >> 27); *dst++ = (unsigned char) value; } while (--numberOfCols); } while (--rows); } */ void lbp_3x3(matrix_t *in, int *lbp_feat) { uint32_t i,j; unsigned char cx, code; // @TODO add support for floating point images uint8_t *in_data = data(uint8_t, in); // extract lbp on 3x3 neighborhood for(j=1; j < height(in)-1; j++) { for(i=1; i < width(in)-1; i++) { cx = in_data[i + j*width(in)]; code = 0; code |= (in_data[i-1 + (j )*width(in)] > cx) << 7; code |= (in_data[i-1 + (j+1)*width(in)] > cx) << 6; code |= (in_data[i + (j+1)*width(in)] > cx) << 5; code |= (in_data[i+1 + (j+1)*width(in)] > cx) << 4; code |= (in_data[i+1 + (j )*width(in)] > cx) << 3; code |= (in_data[i+1 + (j-1)*width(in)] > cx) << 2; code |= (in_data[i + (j-1)*width(in)] > cx) << 1; code |= (in_data[i-1 + (j-1)*width(in)] > cx) << 0; //lbp_feat[i-1 + (j-1)*(imge->width-2)] = code; *lbp_feat++ = code; } } } void lbp_nxn(matrix_t *in, int *lbp_feat, struct lbp_parameters_t *model) { uint32_t i,j; // extract lbp on NxN neighborhood for(i=0; i < model->neighbors; i++) { float xp = model->radius*cosf(2*imlab_pi*i / (float)model->neighbors); float yp = -model->radius*sinf(2*imlab_pi*i / (float)model->neighbors); // floor and ceil the subpixel to use bilinear interpolation int fx = (int) xp; int fy = (int) yp; int cx = (int) xp+1; int cy = (int) yp+1; //use opencv bilinear format f(x,y) = [1-x, x][ f(0,0),f(0,1); f(1,0),f(1,1)] [1-y ; y] // f(x,y) = f(0,0)(1-x)(1-y)+f(1,0)x(1-y)+f(0,1)(1-x)y+f(1,1)xy // fractional part float ty = xp - fy; float tx = yp - fx; // set interpolation weights float w1 = (1-tx) * (1-ty); float w2 = tx * (1-ty); float w3 = (1-tx) * ty; float w4 = tx * ty; // @TODO add support for floating point images uint8_t *in_data = data(uint8_t, in); float fxy; for(j=model->radius; j < height(in)-model->radius; j++) { for(i=model->radius; i < width(in)-model->radius; i++) { // neighbor is on the subpixel, use bilinear interpolation fxy = w1*in_data[ i+fx + (j+fy)*width(in) ] + w2*in_data[ i+cx + (j+fy)*width(in) ]; fxy += w3*in_data[ i+fx + (j+cy)*width(in) ] + w4*in_data[ i+cx + (j+cy)*width(in) ]; lbp_feat[ i-model->radius + (j-model->radius)*(width(in)-2*model->radius) ] |= (fxy > in_data[i + j*width(in)]); } } printf("lbp_feat: %d\n", lbp_feat[ i-model->radius + (j-model->radius)*(width(in)-2*model->radius) ] ); // shift the computed value lbp_feat[ i-model->radius + (j-model->radius)*(width(in)-2*model->radius) ] <<= 1; } //done } static void lbp_cell_histogram(int *lbp_feat, float *feature, float *cell_sum, int width, int height, int wi, int hj, struct lbp_parameters_t *model) { uint32_t i,j, bi,bj, idx; // TODO: remove this if(width == height) { } int cell_in_col = (model->win_width -2*model->radius) / model->b_size[1]; lbp_feat += wi+hj*(width-2*model->radius); for(j=0; j < model->win_height-2*model->radius; j++) { bj = (j) / (model->b_size[1]) - 0.5f; for(i=0; i < model->win_width -2*model->radius; i++) { bi = (i) / (model->b_size[0]) - 0.5f; idx = model->hist_bin_size*(bi+bj*cell_in_col); feature[ idx + lbp_feat[i + j*(width -2*model->radius)] ] += 1.0f; cell_sum[ bi+bj*cell_in_col ] += 1.0f; } } } return_t lbp_image(matrix_t *in, matrix_t *out, struct lbp_parameters_t *model) { int feat_in_row = lbp_height(model); int feat_in_col = lbp_width(model); // update the size of the output if needed return_t ret_val = matrix_resize(out, feat_in_row, feat_in_col, 1); check_return(ret_val, ret_val); /// if the struct lbp_t is called with the deafault value, use optimized version, else use extented struct lbp_t if(model->radius == 1 && model->neighbors == 8) { lbp_3x3(in, out->_data); } else { lbp_nxn(in, out->_data, model); } return SUCCESS; } return_t lbp_extract(matrix_t *in, struct feature_t *par_model, float *feature) { struct lbp_parameters_t *model = par_model->parameters; uint32_t i,j, bin; matrix_t *out = matrix_create(int32_t); return_t ret_val = lbp_image(in, out, model); check_return(ret_val, ret_val); int32_t *lbp_feat = data(int32_t, out); /// if uniform mode is on, compute the scores if(model->uniform != model->neighbors) { /// use the look up table for uniform struct lbp_t if(model->table != NULL) { for(i=0; i < volume(out); i++) { lbp_feat[i] = model->table[ lbp_feat[i] ]; } } } uint32_t cell_in_row = rows(out) / model->b_size[0]; uint32_t cell_in_col = cols(out) / model->b_size[1]; memset(feature, 0, model->feature_size*sizeof(float)); float *cell_sum = (float*) calloc(cell_in_row*cell_in_col, sizeof(float)); /// uniform lbp computed, now create histogram vector for each cell lbp_cell_histogram(lbp_feat, feature, cell_sum, model->win_width, model->win_height, 0,0, model); /* for(j=0; j < feat_in_row; j++) { int bj = (j) / (model->b_size[0]) - 0.5f; for(i=0; i < feat_in_col; i++) { int bi = (i) / (model->b_size[1]) - 0.5f; int idx = model->hist_bin_size*(bi+bj*cell_in_col); //printf("IDX: %d %d--%d %d--%d\n", idx, bi, cell_in_col, bj, cell_in_row); feature[ idx + lbp_feat[i + j*feat_in_col] ] += 1.0f; cell_sum[ bi+bj*cell_in_col ] += 1.0f; } } */ /// now normalize the cell for(j=0; j < cell_in_row; j++) { for(i=0; i < cell_in_col; i++) { int idx = model->hist_bin_size*(i+j*cell_in_col); float norm = 1.0f / (imlab_epsilon + cell_sum[ i+j*cell_in_col ]); for(bin=0; bin < model->hist_bin_size; bin++) { feature[ idx + bin ] = feature[ idx + bin ] * norm; } } } free(lbp_feat); free(cell_sum); //done return SUCCESS; } matrix_t *lbp2image(float *feature, struct feature_t *par_model) { // get the LBP model struct lbp_parameters_t *model = par_model->parameters; // compute the cell in single row and cell in single column uint32_t cell_in_row = lbp_height(model) / model->b_size[0]; uint32_t cell_in_col = lbp_width(model) / model->b_size[1]; uint32_t output_cell_size = 16; // compute the necessary image size uint32_t image_width = output_cell_size * cell_in_col; uint32_t image_height = output_cell_size * cell_in_row; // create the output image matrix_t *image = matrix_create(uint8_t, image_height, image_width, 3); // check that the necessary memories are allocated check_null(image, matrix_null()); uint32_t i, j, bin; /// now normalize the cell for (j = 0; j < cell_in_row; j++) { for (i = 0; i < cell_in_col; i++) { // find the most occured two patterns in the cell uint32_t idx = model->hist_bin_size * (i + j * cell_in_col); uint32_t bin1 = 0; uint32_t bin2 = 0; // search for the maximum for (bin = 0; bin < model->hist_bin_size; bin++) { if(feature[idx + bin] >= feature[idx + bin1]) { bin2 = bin1; bin1 = bin; } } // find the color struct color_t b1 = HSV(map(bin1, 0, model->hist_bin_size - 1, 0, 255), 200, 200); struct color_t b2 = HSV(map(bin2, 0, model->hist_bin_size - 1, 0, 255), 200, 200); // now colorize the output image uint32_t x, x1 = i * output_cell_size; uint32_t y, y1 = j * output_cell_size; // continue if empty or too small if( (feature[idx + bin1] + feature[idx + bin2]) < 1e-5) { continue; } uint32_t t = output_cell_size * (feature[idx + bin1] / (feature[idx + bin1] + feature[idx + bin2])); // fill the grid for (y = 0; y < output_cell_size; y++) { for (x = 0; x < t; x++) { atui8(image, y + y1, x + x1, 0) = b1.blue; atui8(image, y + y1, x + x1, 1) = b1.green; atui8(image, y + y1, x + x1, 2) = b1.red; } for (x = t; x < output_cell_size; x++) { atui8(image, y + y1, x + x1, 0) = b2.blue; atui8(image, y + y1, x + x1, 1) = b2.green; atui8(image, y + y1, x + x1, 2) = b2.red; } } } } //done return image; } /* static void lbp_cell_normalize(float *feature, float *cell_sum, int cell_in_row, int cell_in_col, int hist_bin_size) { int ci,cj, bin; float norm; for(cj=0; cj < cell_in_row; cj++) { for(ci=0; ci < cell_in_col; ci++) { norm = 1.0f/ (imlab_epsilon + *cell_sum++); for(bin=0; bin < hist_bin_size; bin++) { *feature++ *= norm; } } } } */ /* void lbp_detect(matrix_t *in, struct lbp_parameters_t *model, struct glm_t *net, float threshold, matrix_t *out) { int i,j, ci,cj,bin; // detection options static int MaxDet = 1024; int WS, WindowSize = 20; float ScaleFactor = 1.2; int stride = 3; matrix_t *gray; // convert the input into grayscale rgb2gray(in, out); // resize the given output matrix matrix_resize(out, height(in), width(in), 3); //@TODO add support for floating point images uint8_t *in_data = data(uint8_t, in); uint8_t *out_data = data(uint8_t, out); for(j=0; j < height(out); j++) { for(i=0; i < width(out); i++) { int idx = i + width(out)*j; out_data[ channels(out)*idx + 0 ] = in_data[idx]*0.2; out_data[ channels(out)*idx + 1 ] = in_data[idx]*0.2; out_data[ channels(out)*idx + 2 ] = in_data[idx]*0.2; } } /// extract the struct lbp_t of the whole image int feat_in_row = height(in)-2*model->radius; int feat_in_col = width(in) -2*model->radius; int cell_in_row = (model->win_height-2*model->radius) / model->b_size[1]; int cell_in_col = (model->win_width -2*model->radius) / model->b_size[0]; // output lbp feature int *lbp_feat = (int*) calloc( feat_in_row*feat_in_col,sizeof(int) ); float *cell_sum = (float*) calloc(cell_in_row*cell_in_col, sizeof(float)); /// if the struct lbp_t is called with the deafault value, use optimized version, else use extented struct lbp_t if(model->radius == 1 && model->neighbors == 8) { lbp_3x3(in, lbp_feat); } else { lbp_nxn(in, lbp_feat, model); } /// if uniform mode is on, compute the scores if(model->uniform != model->neighbors) { /// use the look up table for uniform struct lbp_t if(model->table != NULL) { for(i=0; i < feat_in_row*feat_in_col; i++) { lbp_feat[i] = model->table[ lbp_feat[i] ]; } } } matrix_t *feature = matrix_create(float, 1,model->feature_size); float *feature_data = data(float, feature); float label; //#pragma omp parallel for private(i,j, label) for(j=0; j < height(in)-model->win_height; j+=stride) { //printf("Progress: %3.2f\r", 100.0f*j/(imge->height-model->height)); for(i=0; i < width(in)-model->win_width; i+=stride) { memset(feature_data, 0, model->feature_size*sizeof(float)); memset(cell_sum, 0, cell_in_row*cell_in_col*sizeof(float)); /// extract the histogram for the cells lbp_cell_histogram(lbp_feat, feature_data, cell_sum, width(in), height(in), i,j, model); lbp_cell_normalize(feature_data, cell_sum, cell_in_row, cell_in_col, model->hist_bin_size); glm_predict(feature, &label, net); //label = max2(-1, min2(1, label)); label = label > threshold ? 1:-1; //#pragma omp critical out_data[ channels(out)*(i+model->win_width/2 + width(out)*(j+model->win_height/2)) + 0 ] += 76*(label+1); out_data[ channels(out)*(i+model->win_width/2 + width(out)*(j+model->win_height/2)) + 1 ] += 96*(label+1); out_data[ channels(out)*(i+model->win_width/2 + width(out)*(j+model->win_height/2)) + 2 ] += 10*(label+1); } } free(lbp_feat); free(cell_sum); return; } */
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 32; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-12,16),ceild(4*t2-Nz-19,32));t3<=min(min(floord(4*Nt+Ny-9,32),floord(2*t1+Ny-3,32)),floord(4*t2+Ny-9,32));t3++) { for (t4=max(max(ceild(t1-60,64),ceild(4*t2-Nz-115,128)),ceild(32*t3-Ny-115,128));t4<=min(min(min(floord(4*Nt+Nx-9,128),floord(2*t1+Nx-3,128)),floord(4*t2+Nx-9,128)),floord(32*t3+Nx+19,128));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(128*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(128*t4,4*t5+4); ubv=min(128*t4+127,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
fibonacci.h
#include <iostream> #include <chrono> #include <omp.h> #include "xitao.h" using namespace std; // enable a known trick to avoid redundant recursion for evaluated cases //#define MEMOIZE // the maximum number of Fibonacci terms that can fit in unsigned 64 bit const uint32_t MAX_FIB = 92; // a global variable to manage the granularity of TAO creation (coarsening level) uint32_t grain_size; // declare the class class FibTAO; // init the memoization array of TAOs FibTAO* fib_taos[MAX_FIB + 1]; // basic Fibonacci implementation size_t fib(uint32_t num) { // return 0 for 0 and negative terms (undefined) if(num <= 0) return 0; // return 1 for the term 1 else if(num == 1) return 1; // recursively find the result return fib(num - 1) + fib(num - 2); } // basic Fibonacci implementation size_t fib_omp(uint32_t num) { // return 0 for 0 and negative terms (undefined) if(num <= 0) return 0; // return 1 for the term 1 else if(num == 1) return 1; // recursively find the result #pragma omp task if (num > grain_size) auto num_1 = fib_omp(num - 1); #pragma omp task if (num > grain_size) auto num_2 = fib_omp(num - 2); #pragma omp taskwait return num_1 + num_2; } // the Fibonacci TAO (Every TAO class must inherit from AssemblyTask) class FibTAO : public AssemblyTask { public: // the n - 1 tao FibTAO* prev1; // the n - 2 tao FibTAO* prev2; // the term number uint32_t term; // the Fib value for the TAO size_t val; // the tao construction. resource hint 1 FibTAO(int _term): term(_term), AssemblyTask(1) { } // the work function void execute(int nthread) { // calculate locally if at required granularity if(term <= grain_size) val = fib(term); // if this is not a terminal term else if(term > 1) // calculate the value val = prev1->val + prev2->val; } void cleanup(){ } }; // build the DAG by reversing the recursion tree FibTAO* buildDAG(uint32_t term) { // gaurd against negative terms if(term < 0) term = 0; // if this is terminal term if(term <= 1) { // create the terminal tao fib_taos[term] = new FibTAO(term); // push the tao gotao_push(fib_taos[term]); // return the tao return fib_taos[term]; } #ifdef MEMOIZE // if this TAO has already been created (avoid redundant calculation) if(fib_taos[term]) return fib_taos[term]; #endif // construct the tao fib_taos[term] = new FibTAO(term); // create TAOs as long as you are above the grain size if(term > grain_size) { // build DAG of n - 1 term fib_taos[term]->prev1 = buildDAG(term - 1); // make edge to current fib_taos[term]->prev1->make_edge(fib_taos[term]); // build DAG of n - 1 term fib_taos[term]->prev2 = buildDAG(term - 2); // make edge to current fib_taos[term]->prev2->make_edge(fib_taos[term]); } else { // you have reached a terminal TAO // push the TAO to fire the DAG execution gotao_push(fib_taos[term]); } // return the current tao (the head of the DAG) return fib_taos[term]; }
singleModificado2.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #define omp_get_num_threads() 1 #endif int main(int argc, char ** argv) { int n = 9, i, a, b[n]; for (i=0; i<n; i++) b[i] = -1; #ifdef _OPENMP #pragma omp parallel #endif { #ifdef _OPENMP #pragma omp single #endif { printf("Introduce valor de inicialización a: "); scanf("%d", &a ); printf("Single ejecutada por el thread %d\n",omp_get_thread_num()); } #ifdef _OPENMP #pragma omp for #endif for (i=0; i<n; i++) b[i] = a; #ifdef _OPENMP #pragma omp barrier #pragma omp master #endif { printf("Dentro del parallel en la thread %d:\n",omp_get_thread_num()); for (i=0; i<n; i++) printf("b[%d] = %d\t",i,b[i]); printf("\n"); } } return 0; }
trmv_x_dia_u_lo_conj.c
#include "alphasparse/kernel.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t ONAME_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA* A, const ALPHA_Number* x, const ALPHA_Number beta, ALPHA_Number* y) { #ifdef COMPLEX const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number** tmp = (ALPHA_Number**)malloc(sizeof(ALPHA_Number*) * thread_num); for(int i = 0; i < thread_num; ++i) { tmp[i] = malloc(sizeof(ALPHA_Number) * m); memset(tmp[i], 0, sizeof(ALPHA_Number) * m); } const ALPHA_INT diags = A->ndiag; #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < diags; ++i) { const ALPHA_INT threadId = alpha_get_thread_id(); const ALPHA_INT dis = A->distance[i]; if(dis < 0) { const ALPHA_INT row_start = -dis; const ALPHA_INT col_start = 0; const ALPHA_INT nnz = m + dis; const ALPHA_INT start = i * A->lval; for(ALPHA_INT j = 0; j < nnz; ++j) { ALPHA_Number v; alpha_mul_3c(v, alpha, A->values[start + row_start + j]); alpha_madde(tmp[threadId][col_start + j], v, x[row_start + j]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); alpha_madde(y[i], alpha, x[i]); for(ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(y[i], y[i], tmp[j][i]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < thread_num; ++i) { alpha_free(tmp[i]); } alpha_free(tmp); return ALPHA_SPARSE_STATUS_SUCCESS; #else return ALPHA_SPARSE_STATUS_INVALID_VALUE; #endif } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA* A, const ALPHA_Number* x, const ALPHA_Number beta, ALPHA_Number* y) { #ifdef COMPLEX return ONAME_omp(alpha, A, x, beta, y); #else return ALPHA_SPARSE_STATUS_INVALID_VALUE; #endif }
omp_task_imp_firstprivate.c
<ompts:test> <ompts:testdescription> Test to see if implied private works properly</ompts:testdescription> <ompts:ompversion>3.0</ompts:ompversion> <ompts:directive>omp task</ompts:directive> <ompts:dependences>omp single</ompts:dependences> <ompts:testcode> #include <stdio.h> #include <math.h> #include "omp_testsuite.h" /* Utility function do spend some time in a loop */ int <ompts:testcode:functionname>omp_task_imp_firstprivate</ompts:testcode:functionname> (FILE * logFile) { int i=5; int k = 0; int result = 0; int task_result = 1; #pragma omp parallel firstprivate(i) { #pragma omp single { for (k = 0; k < NUM_TASKS; k++) { #pragma omp task shared(result , task_result<ompts:crosscheck>, i</ompts:crosscheck>) { int j; //check if i is private if(i != 5) task_result = 0; for(j = 0; j < NUM_TASKS; j++) i++; //this should be firstprivate implicitly } } #pragma omp taskwait result = (task_result && i==5); } } return result; } </ompts:testcode> </ompts:test>
GB_binop__bset_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__bset_uint64 // A.*B function (eWiseMult): GB_AemultB__bset_uint64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__bset_uint64 // C+=b function (dense accum): GB_Cdense_accumb__bset_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bset_uint64 // C=scalar+B GB_bind1st__bset_uint64 // C=scalar+B' GB_bind1st_tran__bset_uint64 // C=A+scalar GB_bind2nd__bset_uint64 // C=A'+scalar GB_bind2nd_tran__bset_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = GB_BITSET (aij, bij, uint64_t, 64) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_BITSET (x, y, uint64_t, 64) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BSET || GxB_NO_UINT64 || GxB_NO_BSET_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__bset_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__bset_uint64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__bset_uint64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *GB_RESTRICT Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__bset_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__bset_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__bset_uint64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = GB_BITSET (x, bij, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__bset_uint64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = Ax [p] ; Cx [p] = GB_BITSET (aij, y, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITSET (x, aij, uint64_t, 64) ; \ } GrB_Info GB_bind1st_tran__bset_uint64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITSET (aij, y, uint64_t, 64) ; \ } GrB_Info GB_bind2nd_tran__bset_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nr_incore.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. 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. * * Incore version of non-relativistic integrals JK contraction * ic in CVHFic... is short for incore */ #include <stdlib.h> #include <math.h> //#include <omp.h> #include "config.h" #include "cvhf.h" #include "np_helper/np_helper.h" #include "fblas.h" /* * J */ void CVHFics8_ij_s2kl_o0(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i, j, ij; double dm_ij; double vj_ij = 0; if (ic > jc) { dm_ij = dm[ic*nao+jc] + dm[jc*nao+ic]; } else if (ic == jc) { dm_ij = dm[ic*nao+ic]; } else { return; } for (i = 0, ij = 0; i < ic; i++) { for (j = 0; j < i; j++, ij++) { vj_ij += eri[ij] *(dm[i*nao+j]+dm[j*nao+i]); vj[i*nao+j] += eri[ij] * dm_ij; } vj_ij += eri[ij] * dm[i*nao+i]; vj[i*nao+i] += eri[ij] * dm_ij; ij++; } // i == ic for (j = 0; j < jc; j++, ij++) { vj_ij += eri[ij] *(dm[i*nao+j]+dm[j*nao+i]); vj[i*nao+j] += eri[ij] * dm_ij; } vj_ij += eri[ij] * dm_ij; vj[ic*nao+jc] += vj_ij; } void CVHFics4_ij_s2kl_o0(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i, j, ij; double dm_ij; if (ic > jc) { dm_ij = dm[ic*nao+jc] + dm[jc*nao+ic]; } else if (ic == jc) { dm_ij = dm[ic*nao+ic]; } else { return; } for (i = 0, ij = 0; i < nao; i++) { for (j = 0; j <= i; j++, ij++) { vj[i*nao+j] += eri[ij] * dm_ij; } } } void CVHFics2kl_kl_s1ij_o0(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i, j, ij; double vj_ij = 0; for (i = 0, ij = 0; i < nao; i++) { for (j = 0; j < i; j++, ij++) { vj_ij += eri[ij] *(dm[i*nao+j]+dm[j*nao+i]); } vj_ij += eri[ij] * dm[i*nao+i]; ij++; } vj[ic*nao+jc] += vj_ij; } /* * K */ void CVHFics8_jk_s1il_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; if (ic > jc) { for (k = 0, kl = 0; k < ic; k++) { for (l = 0; l < k; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; vk[l*nao+jc] += eri[kl] * dm[k*nao+ic]; vk[k*nao+jc] += eri[kl] * dm[l*nao+ic]; vk[l*nao+ic] += eri[kl] * dm[k*nao+jc]; vk[k*nao+ic] += eri[kl] * dm[l*nao+jc]; } vk[jc*nao+k] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+k]; vk[k*nao+jc] += eri[kl] * dm[k*nao+ic]; vk[k*nao+ic] += eri[kl] * dm[k*nao+jc]; kl++; } k = ic; for (l = 0; l < jc; l++, kl++) { // l<k vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; vk[l*nao+jc] += eri[kl] * dm[k*nao+ic]; vk[k*nao+jc] += eri[kl] * dm[l*nao+ic]; vk[l*nao+ic] += eri[kl] * dm[k*nao+jc]; vk[k*nao+ic] += eri[kl] * dm[l*nao+jc]; } // ic = k, jc = l; vk[jc*nao+jc] += eri[kl] * dm[ic*nao+ic]; vk[ic*nao+jc] += eri[kl] * dm[jc*nao+ic]; vk[jc*nao+ic] += eri[kl] * dm[ic*nao+jc]; vk[ic*nao+ic] += eri[kl] * dm[jc*nao+jc]; } else if (ic == jc) { for (k = 0, kl = 0; k < ic; k++) { for (l = 0; l < k; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[ic*nao+l]; vk[l*nao+ic] += eri[kl] * dm[k*nao+ic]; vk[k*nao+ic] += eri[kl] * dm[l*nao+ic]; } vk[ic*nao+k] += eri[kl] * dm[ic*nao+k]; vk[k*nao+ic] += eri[kl] * dm[k*nao+ic]; kl++; } k = ic; for (l = 0; l < k; l++, kl++) { // l<k vk[ic*nao+l] += eri[kl] * dm[ic*nao+ic]; vk[l*nao+ic] += eri[kl] * dm[ic*nao+ic]; vk[ic*nao+ic] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+ic] += eri[kl] * dm[l*nao+ic]; } // ic = jc = k = l vk[ic*nao+ic] += eri[kl] * dm[ic*nao+ic]; } } void CVHFics8_jk_s2il_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l; //double vk_jj = 0; //double vk_ij = 0; if (ic > jc) { // k < jc for (k=0; k < jc; k++) { for (l = 0; l < k; l++) { vk[jc*nao+l] += eri[l] * dm[ic*nao+k]; vk[jc*nao+k] += eri[l] * dm[ic*nao+l]; vk[ic*nao+l] += eri[l] * dm[jc*nao+k]; vk[ic*nao+k] += eri[l] * dm[jc*nao+l]; } // l = k vk[jc*nao+k] += eri[k] * dm[ic*nao+k]; vk[ic*nao+k] += eri[k] * dm[jc*nao+k]; eri += k + 1; } // k = jc for (l = 0; l < k; l++) { vk[jc*nao+l ] += eri[l] * dm[ic*nao+jc]; vk[ic*nao+l ] += eri[l] * dm[jc*nao+jc]; vk[jc*nao+jc] += eri[l] *(dm[ic*nao+l] + dm[l*nao+ic]); vk[ic*nao+jc] += eri[l] * dm[jc*nao+l]; } // l = k = jc vk[jc*nao+jc] += eri[l] *(dm[ic*nao+jc] + dm[jc*nao+ic]); vk[ic*nao+jc] += eri[l] * dm[jc*nao+jc]; eri += k + 1; // k > jc for (k=jc+1; k < ic; k++) { // l < jc for (l = 0; l < jc; l++) { vk[jc*nao+l] += eri[l] * dm[ic*nao+k]; vk[ic*nao+l] += eri[l] * dm[jc*nao+k]; vk[ic*nao+k] += eri[l] * dm[jc*nao+l]; vk[k*nao+jc] += eri[l] * dm[l*nao+ic]; } // l = jc vk[jc*nao+jc] += eri[l] *(dm[ic*nao+k] + dm[k*nao+ic]); vk[ic*nao+jc] += eri[l] * dm[jc*nao+k]; vk[ic*nao+k] += eri[l] * dm[jc*nao+jc]; vk[k*nao+jc] += eri[l] * dm[jc*nao+ic]; //eri += jc+1; // l > jc for (l = jc+1; l < k; l++) { vk[ic*nao+l] += eri[l] * dm[jc*nao+k]; vk[ic*nao+k] += eri[l] * dm[jc*nao+l]; vk[l*nao+jc] += eri[l] * dm[k*nao+ic]; vk[k*nao+jc] += eri[l] * dm[l*nao+ic]; } // l = k vk[jc*nao+k] += eri[l] * dm[ic*nao+k]; vk[ic*nao+k] += eri[l] * dm[jc*nao+k]; vk[k*nao+jc] += eri[l] * dm[k*nao+ic]; eri += k + 1; } // k = ic for (l = 0; l < jc; l++) { vk[jc*nao+l] += eri[l] * dm[ic*nao+ic]; vk[ic*nao+l] += eri[l] * dm[jc*nao+ic]; vk[ic*nao+ic] += eri[l] *(dm[jc*nao+l] + dm[l*nao+jc]); vk[ic*nao+jc] += eri[l] * dm[l*nao+ic]; } // ic = k, jc = l; vk[jc*nao+jc] += eri[l] * dm[ic*nao+ic]; vk[ic*nao+jc] += eri[l] * dm[jc*nao+ic]; vk[ic*nao+ic] += eri[l] * dm[jc*nao+jc]; eri += jc + 1; } else if (ic == jc) { for (k = 0; k < ic-1; k+=2) { for (l = 0; l < k; l++) { vk[ic*nao+l] += eri[l] * dm[ic*nao+k]; vk[ic*nao+k] += eri[l] * dm[ic*nao+l]; vk[ic*nao+l ] += eri[l+k+1] * dm[ic*nao+k+1]; vk[ic*nao+k+1] += eri[l+k+1] * dm[ic*nao+l ]; } vk[ic*nao+k] += eri[k] * dm[ic*nao+k]; eri += k+1; vk[ic*nao+k ] += eri[k] * dm[ic*nao+k+1]; vk[ic*nao+k+1] += eri[k] * dm[ic*nao+k ]; vk[ic*nao+k+1] += eri[k+1] * dm[ic*nao+k+1]; eri += k+2; } for (; k < ic; k++) { for (l = 0; l < k; l++) { vk[ic*nao+l] += eri[l] * dm[ic*nao+k]; vk[ic*nao+k] += eri[l] * dm[ic*nao+l]; } vk[ic*nao+k] += eri[k] * dm[ic*nao+k]; eri += k+1; } for (l = 0; l < k; l++) { // l<k vk[ic*nao+l] += eri[l] * dm[ic*nao+ic]; vk[ic*nao+ic] += eri[l] *(dm[ic*nao+l] + dm[l*nao+ic]); } // ic = jc = k = l vk[ic*nao+ic] += eri[l] * dm[ic*nao+ic]; eri += k + 1; } } void CVHFics4_jk_s1il_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; if (ic > jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < k; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } vk[jc*nao+k] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+k]; kl++; } } else if (ic == jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < k; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[ic*nao+l]; } vk[ic*nao+k] += eri[kl] * dm[ic*nao+k]; kl++; } } } void CVHFics4_il_s1jk_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s1il_o0(eri, dm, vk, nao, ic, jc); } void CVHFics4_jk_s2il_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; if (ic > jc) { for (k = 0, kl = 0; k <= jc; k++) { for (l = 0; l < k; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } vk[jc*nao+k] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+k]; kl++; } for (k = jc+1; k <= ic; k++) { for (l = 0; l <= jc; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } for (l = jc+1; l < k; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } vk[ic*nao+k] += eri[kl] * dm[jc*nao+k]; kl++; } for (k = ic+1; k < nao; k++) { for (l = 0, kl = k*(k+1)/2; l <= jc; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; } for (l = jc+1; l <= ic; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; } } } else if (ic == jc) { for (k = 0, kl = 0; k <= ic; k++) { for (l = 0; l < k; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+k] += eri[kl] * dm[ic*nao+l]; } vk[ic*nao+k] += eri[kl] * dm[ic*nao+k]; kl++; } for (k = ic+1; k < nao; k++) { for (l = 0, kl = k*(k+1)/2; l <= ic; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[ic*nao+k]; } } } } void CVHFics4_il_s2jk_o0(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s2il_o0(eri, dm, vk, nao, ic, jc); } /* * einsum ijkl,ij->(s2)kl * 8-fold symmetry for eri: i>=j,k>=l,ij>=kl * input address eri of the first element for pair ij=ic*(ic+1)/2+jc * i.e. ~ &eri_ao[ij*(ij+1)/2] * dm can be non-Hermitian, * output vk might not be Hermitian * * NOTE all _s2kl (nrs8_, nrs4_, nrs2kl_) assumes the tril part of eri * being stored in C-order *contiguously*. so call CVHFunpack_nrblock2tril * to generate eris */ void CVHFics8_ij_s2kl(double *eri, double *dm, double *vj, int nao, int ic, int jc) { CVHFics8_ij_s2kl_o0(eri, dm, vj, nao, ic, jc); } // tri_dm: fold upper triangular dm to lower triangle, // tri_dm[i*(i+1)/2+j] = dm[i*nao+j] + dm[j*nao+i] for i > j void CVHFics8_tridm_vj(double *eri, double *tri_dm, double *vj, int nao, int ic, int jc) { int i, j, ij; double dm_ijc = tri_dm[ic*(ic+1)/2+jc]; double vj_ij = 0; const int INC1 = 1; int i1; for (i = 0, ij = 0; i < ic; i++) { i1 = i + 1; vj_ij += ddot_(&i1, eri+ij, &INC1, tri_dm+ij, &INC1); daxpy_(&i1, &dm_ijc, eri+ij, &INC1, vj+i*nao, &INC1); ij += i1; } // i == ic for (j = 0; j < jc; j++, ij++) { vj_ij += eri[ij] * tri_dm[ij]; vj[i*nao+j] += eri[ij] * dm_ijc; } vj_ij += eri[ij] * dm_ijc; vj[ic*nao+jc] += vj_ij; } void CVHFics8_jk_s1il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics8_jk_s1il_o0(eri, dm, vk, nao, ic, jc); } /* * einsum ijkl,jk->(s2)il * output vk should be Hermitian */ void CVHFics8_jk_s2il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics8_jk_s2il_o0(eri, dm, vk, nao, ic, jc); } /* * einsum ijkl,jk->il * 4-fold symmetry for eri: i>=j,k>=l */ void CVHFics4_jk_s1il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s1il_o0(eri, dm, vk, nao, ic, jc); } void CVHFics4_il_s1jk(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s1il_o0(eri, dm, vk, nao, ic, jc); } /* * output vk should be Hermitian */ void CVHFics4_jk_s2il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s2il_o0(eri, dm, vk, nao, ic, jc); } void CVHFics4_il_s2jk(double *eri, double *dm, double *vk, int nao, int ic, int jc) { CVHFics4_jk_s2il_o0(eri, dm, vk, nao, ic, jc); } void CVHFics4_ij_s2kl(double *eri, double *dm, double *vj, int nao, int ic, int jc) { CVHFics4_ij_s2kl_o0(eri, dm, vj, nao, ic, jc); } void CVHFics4_kl_s2ij(double *eri, double *dm, double *vj, int nao, int ic, int jc) { if (ic >= jc) { CVHFics2kl_kl_s1ij_o0(eri, dm, vj, nao, ic, jc); } } void CVHFics1_ij_s1kl(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i; double dm_ij = dm[ic*nao+jc]; for (i = 0; i < nao*nao; i++) { vj[i] += eri[i] * dm_ij; } } void CVHFics1_kl_s1ij(double *eri, double *dm, double *vj, int nao, int ic, int jc) { const int INC1 = 1; int nn = nao * nao; vj[ic*nao+jc] += ddot_(&nn, eri, &INC1, dm, &INC1); } void CVHFics1_jk_s1il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; } } } void CVHFics1_il_s1jk(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; } } } void CVHFics2ij_ij_s1kl(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i; double dm_ij; if (ic > jc) { dm_ij = dm[ic*nao+jc] + dm[jc*nao+ic]; } else if (ic == jc) { dm_ij = dm[ic*nao+ic]; } else { return; } for (i = 0; i < nao*nao; i++) { vj[i] += eri[i] * dm_ij; } } void CVHFics2ij_kl_s2ij(double *eri, double *dm, double *vj, int nao, int ic, int jc) { if (ic < jc) { return; } CVHFics1_kl_s1ij(eri, dm, vj, nao, ic, jc); } void CVHFics2ij_jk_s1il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; if (ic > jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; } } } else if (ic == jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[ic*nao+k]; } } } } void CVHFics2ij_il_s1jk(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; if (ic > jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } } } else if (ic == jc) { for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < nao; l++, kl++) { vk[ic*nao+k] += eri[kl] * dm[ic*nao+l]; } } } } void CVHFics2kl_ij_s2kl(double *eri, double *dm, double *vj, int nao, int ic, int jc) { int i, j, ij; double dm_ij = dm[ic*nao+jc]; for (i = 0, ij = 0; i < nao; i++) { for (j = 0; j <= i; j++, ij++) { vj[i*nao+j] += eri[ij] * dm_ij; } } } void CVHFics2kl_kl_s1ij(double *eri, double *dm, double *vj, int nao, int ic, int jc) { CVHFics2kl_kl_s1ij_o0(eri, dm, vj, nao, ic, jc); } void CVHFics2kl_jk_s1il(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < k; l++, kl++) { vk[ic*nao+l] += eri[kl] * dm[jc*nao+k]; vk[ic*nao+k] += eri[kl] * dm[jc*nao+l]; } vk[ic*nao+k] += eri[kl] * dm[jc*nao+k]; kl++; } } void CVHFics2kl_il_s1jk(double *eri, double *dm, double *vk, int nao, int ic, int jc) { int k, l, kl; for (k = 0, kl = 0; k < nao; k++) { for (l = 0; l < k; l++, kl++) { vk[jc*nao+l] += eri[kl] * dm[ic*nao+k]; vk[jc*nao+k] += eri[kl] * dm[ic*nao+l]; } vk[jc*nao+k] += eri[kl] * dm[ic*nao+k]; kl++; } } /************************************************** * s8 8-fold symmetry: i>=j,k>=l,ij>=kl * s4 4-fold symmetry: i>=j,k>=l * s2ij 2-fold symmetry: i>=j * s2kl 2-fold symmetry: k>=l * s1 no permutation symmetry **************************************************/ typedef void (*FjkPtr)(double *eri, double *dm, double *vk, int nao, int ic, int jc); void CVHFnrs8_incore_drv(double *eri, double **dms, double **vjk, int n_dm, int nao, void (**fjk)()) { #pragma omp parallel default(none) \ shared(eri, dms, vjk, n_dm, nao, fjk) { int i, j, ic; size_t ij, off; size_t npair = nao*(nao+1)/2; size_t nn = nao * nao; double *v_priv = calloc(nn*n_dm, sizeof(double)); FjkPtr pf; double *pv; #pragma omp for nowait schedule(dynamic, 4) for (ij = 0; ij < npair; ij++) { i = (int)(sqrt(2*ij+.25) - .5 + 1e-7); j = ij - i*(i+1)/2; off = ij*(ij+1)/2; for (ic = 0; ic < n_dm; ic++) { pf = fjk[ic]; pv = v_priv + ic*nn; (*pf)(eri+off, dms[ic], pv, nao, i, j); } } #pragma omp critical { for (ic = 0; ic < n_dm; ic++) { pv = vjk[ic]; for (i = 0; i < nn; i++) { pv[i] += v_priv[ic*nn+i]; } } } free(v_priv); } } void CVHFnrs4_incore_drv(double *eri, double **dms, double **vjk, int n_dm, int nao, void (**fjk)()) { #pragma omp parallel default(none) \ shared(eri, dms, vjk, n_dm, nao, fjk) { int i, j, ic; size_t ij, off; size_t npair = nao*(nao+1)/2; size_t nn = nao * nao; double *v_priv = calloc(nn*n_dm, sizeof(double)); FjkPtr pf; double *pv; #pragma omp for nowait schedule(dynamic, 4) for (ij = 0; ij < npair; ij++) { i = (int)(sqrt(2*ij+.25) - .5 + 1e-7); j = ij - i*(i+1)/2; off = ij * npair; for (ic = 0; ic < n_dm; ic++) { pf = fjk[ic]; pv = v_priv + ic*nn; (*pf)(eri+off, dms[ic], pv, nao, i, j); } } #pragma omp critical { for (ic = 0; ic < n_dm; ic++) { pv = vjk[ic]; for (i = 0; i < nn; i++) { pv[i] += v_priv[ic*nn+i]; } } } free(v_priv); } } void CVHFnrs2ij_incore_drv(double *eri, double **dms, double **vjk, int n_dm, int nao, void (**fjk)()) { #pragma omp parallel default(none) \ shared(eri, dms, vjk, n_dm, nao, fjk) { int i, j, ic; size_t ij, off; size_t npair = nao*(nao+1)/2; size_t nn = nao * nao; double *v_priv = calloc(nn*n_dm, sizeof(double)); FjkPtr pf; double *pv; #pragma omp for nowait schedule(dynamic, 4) for (ij = 0; ij < npair; ij++) { i = (int)(sqrt(2*ij+.25) - .5 + 1e-7); j = ij - i*(i+1)/2; off = ij * nn; for (ic = 0; ic < n_dm; ic++) { pf = fjk[ic]; pv = v_priv + ic*nn; (*pf)(eri+off, dms[ic], pv, nao, i, j); } } #pragma omp critical { for (ic = 0; ic < n_dm; ic++) { pv = vjk[ic]; for (i = 0; i < nn; i++) { pv[i] += v_priv[ic*nn+i]; } } } free(v_priv); } } void CVHFnrs2kl_incore_drv(double *eri, double **dms, double **vjk, int n_dm, int nao, void (**fjk)()) { #pragma omp parallel default(none) \ shared(eri, dms, vjk, n_dm, nao, fjk) { int i, j, ic; size_t ij, off; size_t npair = nao*(nao+1)/2; size_t nn = nao * nao; double *v_priv = calloc(nn*n_dm, sizeof(double)); FjkPtr pf; double *pv; #pragma omp for nowait schedule(dynamic, 4) for (ij = 0; ij < nn; ij++) { i = ij / nao; j = ij - i * nao; off = ij * npair; for (ic = 0; ic < n_dm; ic++) { pf = fjk[ic]; pv = v_priv + ic*nn; (*pf)(eri+off, dms[ic], pv, nao, i, j); } } #pragma omp critical { for (ic = 0; ic < n_dm; ic++) { pv = vjk[ic]; for (i = 0; i < nn; i++) { pv[i] += v_priv[ic*nn+i]; } } } free(v_priv); } } void CVHFnrs1_incore_drv(double *eri, double **dms, double **vjk, int n_dm, int nao, void (**fjk)()) { #pragma omp parallel default(none) \ shared(eri, dms, vjk, n_dm, nao, fjk) { int i, j, ic; size_t ij, off; size_t nn = nao * nao; double *v_priv = calloc(nn*n_dm, sizeof(double)); FjkPtr pf; double *pv; #pragma omp for nowait schedule(dynamic, 4) for (ij = 0; ij < nn; ij++) { i = ij / nao; j = ij - i * nao; off = ij * nn; for (ic = 0; ic < n_dm; ic++) { pf = fjk[ic]; pv = v_priv + ic*nn; (*pf)(eri+off, dms[ic], pv, nao, i, j); } } #pragma omp critical { for (ic = 0; ic < n_dm; ic++) { pv = vjk[ic]; for (i = 0; i < nn; i++) { pv[i] += v_priv[ic*nn+i]; } } } free(v_priv); } }
3d25pt.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 24; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=2*Nt-2;t1++) { lbp=ceild(t1+2,2); ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1-8,12),ceild(4*t2-Nz-11,24));t3<=min(min(floord(4*Nt+Ny-9,24),floord(2*t1+Ny-3,24)),floord(4*t2+Ny-9,24));t3++) { for (t4=max(max(ceild(t1-508,512),ceild(4*t2-Nz-1011,1024)),ceild(24*t3-Ny-1011,1024));t4<=min(min(min(floord(4*Nt+Nx-9,1024),floord(2*t1+Nx-3,1024)),floord(4*t2+Nx-9,1024)),floord(24*t3+Nx+11,1024));t4++) { for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(24*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) { for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(24*t3,4*t5+4);t7<=min(24*t3+23,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
GB_binop__isne_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isne_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__isne_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__isne_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__isne_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isne_fp32) // A*D function (colscale): GB (_AxD__isne_fp32) // D*A function (rowscale): GB (_DxB__isne_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__isne_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__isne_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isne_fp32) // C=scalar+B GB (_bind1st__isne_fp32) // C=scalar+B' GB (_bind1st_tran__isne_fp32) // C=A+scalar GB (_bind2nd__isne_fp32) // C=A'+scalar GB (_bind2nd_tran__isne_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x != y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISNE || GxB_NO_FP32 || GxB_NO_ISNE_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isne_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isne_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isne_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isne_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isne_fp32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *restrict Cx = (float *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isne_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isne_fp32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isne_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isne_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isne_fp32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isne_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isne_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__isne_fp32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__isne_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Fdtd.h
#pragma once #include "Constants.h" #include "FieldSolver.h" #include "Grid.h" #include "PmlFdtd.h" #include "Vectors.h" #include <algorithm> namespace pfc { class FDTD : public RealFieldSolver<YeeGridType> { public: FDTD(YeeGrid* grid, FP dt); void updateFields(); void setPML(int sizePMLx, int sizePMLy, int sizePMLz); void setFieldGenerator(FieldGeneratorYee * _generator); void updateHalfB(); void updateE(); void setTimeStep(FP dt); FP getCourantCondition() const { double tmp = sqrt(1.0 / (grid->steps.x*grid->steps.x) + 1.0 / (grid->steps.y*grid->steps.y) + 1.0 / (grid->steps.z*grid->steps.z)); return 1.0 / (constants::c * tmp); } bool ifCourantConditionSatisfied(FP dt) const { return dt < getCourantCondition(); } private: void updateHalfB3D(); void updateHalfB2D(); void updateHalfB1D(); void updateE3D(); void updateE2D(); void updateE1D(); FP3 anisotropyCoeff; void setAnisotropy(const FP frequency, int axis); }; inline FDTD::FDTD(YeeGrid* grid, FP dt) : RealFieldSolver(grid, dt, 0.0, 0.5*dt, 0.0) { if (!ifCourantConditionSatisfied(dt)) { std::cout << "WARNING: FDTD Courant condition is not satisfied. Another time step was setted up" << std::endl; this->dt = getCourantCondition() * 0.5; } updateDims(); pml.reset(new Pml<GridTypes::YeeGridType>(this, Int3(0, 0, 0)));//pml.reset(new PmlFdtd(this));; generator.reset(new ReflectFieldGeneratorYee(this)); updateInternalDims(); anisotropyCoeff = FP3(1, 1, 1); } inline void FDTD::setPML(int sizePMLx, int sizePMLy, int sizePMLz) { pml.reset(new PmlFdtd(this, Int3(sizePMLx, sizePMLy, sizePMLz))); updateInternalDims(); } inline void FDTD::setTimeStep(FP dt) { if (ifCourantConditionSatisfied(dt)) { this->dt = dt; this->timeShiftB = 0.5*dt; if (pml->sizePML == Int3(0, 0, 0)) pml.reset(new Pml<GridTypes::YeeGridType>(this, Int3(0, 0, 0))); else pml.reset(new PmlFdtd(this, pml->sizePML)); generator.reset(generator->createInstance(this)); } else { std::cout << "WARNING: FDTD Courant condition is not satisfied. Time step was not changed" << std::endl; } } inline void FDTD::setFieldGenerator(FieldGeneratorYee * _generator) { generator.reset(_generator); } inline void FDTD::setAnisotropy(FP frequency, int axis) { // We introduce artificial anisotropy, through one axis. // For this we upgrade Maxwell equations by coefficients, // which computes from major signal frequency. // See more in Juntunen,Tsiboukis - Reduction of Numerical Dispersion in // FDTD Method Through Artificial Anisotropy. FP3 steps = grid->steps; FP WP = constants::pi * 2.0 * constants::c / frequency; FP R = WP / steps.norm(); const FP q = 0.99; // q - stability coefficient, 0 <= q <= 1 FP Amax = constants::pi / (3 * R * asin(asin(constants::pi / (R * sqrt(3.0))) / sqrt(3.0))); FP Q = Amax - 1; FP c1 = 1 - Q / 2; int axis0 = axis; int axis1 = (axis + 1) % 3; int axis2 = (axis + 2) % 3; // equivalents of the variables // Z1 == Zy, Zz == Zz // Zy,Zz - designation from article FP Z1 = steps[axis0] / steps[axis1]; FP Z2 = steps[axis0] / steps[axis2]; // equivalents of the variables // CoeffA == K1, CoeffB == K2, a1 == a, a2 == b // K1, K2, a, b - designation from article FP CoeffA = constants::pi / (R * sqrt(1 + 1 / (Z1 * Z1) + 1 / (Z2 * Z2))); FP a1 = sin(CoeffA / c1) * sin(CoeffA / c1) / (Z1 * Z1 * sin(CoeffA / (c1 * Z1)) * sin(CoeffA / (c1 * Z1))); FP a2 = sin(CoeffA / c1) * sin(CoeffA / c1) / (Z2 * Z2 * sin(CoeffA / (c1 * Z2)) * sin(CoeffA / (c1 * Z2))); FP CoeffB = sqrt(1 + a1 * Z1 * Z1 + a2 * Z2 * Z2); anisotropyCoeff[axis0] = CoeffB / (CoeffA * q * sqrt(a1 * a2)) * asin(q * sin(CoeffA / c1) / CoeffB); anisotropyCoeff[axis1] = a1 * anisotropyCoeff[axis0]; anisotropyCoeff[axis2] = a2 * anisotropyCoeff[axis0]; } inline void FDTD::updateFields() { updateHalfB(); pml->updateB(); generator->generateB(); updateE(); pml->updateE(); generator->generateE(); updateHalfB(); globalTime += dt; } // Update grid values of magnetic field in FDTD. inline void FDTD::updateHalfB() { if (grid->dimensionality == 3) updateHalfB3D(); else if (grid->dimensionality == 2) updateHalfB2D(); else if (grid->dimensionality == 1) updateHalfB1D(); } inline void FDTD::updateHalfB3D() { updateBAreaBegin = Int3(1, 1, 1); updateBAreaEnd = grid->numCells - Int3(1, 1, 1); for (int d = 0; d < 3; ++d) { internalBAreaBegin[d] = std::max(updateBAreaBegin[d], pml->leftDims[d]); internalBAreaEnd[d] = std::min(updateBAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP cdt = constants::c * dt * (FP)0.5; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); const FP coeffYX = cdt / (grid->steps.y * anisotropyCoeff.x); const FP coeffYZ = cdt / (grid->steps.y * anisotropyCoeff.z); const FP coeffZX = cdt / (grid->steps.z * anisotropyCoeff.x); const FP coeffZY = cdt / (grid->steps.z * anisotropyCoeff.y); // In central area use b(i, j, k) += c * dt * -rot(e(i, j, k)), which is: // b.x(i, j, k) += c * dt * ((e.y(i, j, k) - e.y(i, j, k-1)) / eps_z * dz - // (e.z(i, j, k) - e.z(i, j-1, k)) / eps_y * dy), // b.y(i, j, k) += c * dt * ((e.z(i, j, k) - e.z(i-1, j, k)) / eps_x * dx - // (e.x(i, j, k) - e.x(i, j, k-1)) / eps_z * dz), // b.z(i, j, k) += c * dt * ((e.x(i, j, k) - e.x(i, j-1, k)) / eps_y * dy - // (e.y(i, j, k) - e.y(i-1, j, k)) / eps_x * dx), const Int3 begin = internalBAreaBegin; const Int3 end = internalBAreaEnd; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { #pragma simd for (int k = begin.z; k < end.z; k++) { grid->Bx(i, j, k) += coeffZX * (grid->Ey(i, j, k) - grid->Ey(i, j, k - 1)) - coeffYX * (grid->Ez(i, j, k) - grid->Ez(i, j - 1, k)); grid->By(i, j, k) += coeffXY * (grid->Ez(i, j, k) - grid->Ez(i - 1, j, k)) - coeffZY * (grid->Ex(i, j, k) - grid->Ex(i, j, k - 1)); grid->Bz(i, j, k) += coeffYZ * (grid->Ex(i, j, k) - grid->Ex(i, j - 1, k)) - coeffXZ * (grid->Ey(i, j, k) - grid->Ey(i - 1, j, k)); } } } inline void FDTD::updateHalfB2D() { updateBAreaBegin = Int3(1, 1, 0); updateBAreaEnd = grid->numCells - Int3(1, 1, 0); for (int d = 0; d < 2; ++d) { internalBAreaBegin[d] = std::max(updateBAreaBegin[d], pml->leftDims[d]); internalBAreaEnd[d] = std::min(updateBAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP cdt = constants::c * dt * (FP)0.5; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); const FP coeffYX = cdt / (grid->steps.y * anisotropyCoeff.x); const FP coeffYZ = cdt / (grid->steps.y * anisotropyCoeff.z); // In central area use b(i, j, k) += c * dt * -rot(e(i, j, k)), which is: // b.x(i, j, k) += c * dt * ((e.y(i, j, k) - e.y(i, j, k-1)) / eps_z * dz - // (e.z(i, j, k) - e.z(i, j-1, k)) / eps_y * dy), // b.y(i, j, k) += c * dt * ((e.z(i, j, k) - e.z(i-1, j, k)) / eps_x * dx - // (e.x(i, j, k) - e.x(i, j, k-1)) / eps_z * dz), // b.z(i, j, k) += c * dt * ((e.x(i, j, k) - e.x(i, j-1, k)) / eps_y * dy - // (e.y(i, j, k) - e.y(i-1, j, k)) / eps_x * dx), const Int3 begin = internalBAreaBegin; const Int3 end = internalBAreaEnd; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) { #pragma simd for (int j = begin.y; j < end.y; j++) { grid->Bx(i, j, 0) += -coeffYX * (grid->Ez(i, j, 0) - grid->Ez(i, j - 1, 0)); grid->By(i, j, 0) += coeffXY * (grid->Ez(i, j, 0) - grid->Ez(i - 1, j, 0)); grid->Bz(i, j, 0) += coeffYZ * (grid->Ex(i, j, 0) - grid->Ex(i, j - 1, 0)) - coeffXZ * (grid->Ey(i, j, 0) - grid->Ey(i - 1, j, 0)); } } } inline void FDTD::updateHalfB1D() { updateBAreaBegin = Int3(1, 0, 0); updateBAreaEnd = grid->numCells - Int3(1, 0, 0); for (int d = 0; d < 1; ++d) { internalBAreaBegin[d] = std::max(updateBAreaBegin[d], pml->leftDims[d]); internalBAreaEnd[d] = std::min(updateBAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP cdt = constants::c * dt * (FP)0.5; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); // In central area use b(i, j, k) += c * dt * -rot(e(i, j, k)), which is: // b.x(i, j, k) += c * dt * ((e.y(i, j, k) - e.y(i, j, k-1)) / eps_z * dz - // (e.z(i, j, k) - e.z(i, j-1, k)) / eps_y * dy), // b.y(i, j, k) += c * dt * ((e.z(i, j, k) - e.z(i-1, j, k)) / eps_x * dx - // (e.x(i, j, k) - e.x(i, j, k-1)) / eps_z * dz), // b.z(i, j, k) += c * dt * ((e.x(i, j, k) - e.x(i, j-1, k)) / eps_y * dy - // (e.y(i, j, k) - e.y(i-1, j, k)) / eps_x * dx), const Int3 begin = internalBAreaBegin; const Int3 end = internalBAreaEnd; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) { grid->By(i, 0, 0) += coeffXY * (grid->Ez(i, 0, 0) - grid->Ez(i - 1, 0, 0)); grid->Bz(i, 0, 0) += -coeffXZ * (grid->Ey(i, 0, 0) - grid->Ey(i - 1, 0, 0)); } } // Update grid values of electric field in FDTD. inline void FDTD::updateE() { if (grid->dimensionality == 3) updateE3D(); else if (grid->dimensionality == 2) updateE2D(); else if (grid->dimensionality == 1) updateE1D(); } inline void FDTD::updateE3D() { updateEAreaBegin = Int3(0, 0, 0); updateEAreaEnd = grid->numCells - Int3(1, 1, 1); for (int d = 0; d < 3; ++d) { internalEAreaBegin[d] = std::max(updateEAreaBegin[d], pml->leftDims[d]); internalEAreaEnd[d] = std::min(updateEAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP coeffCurrent = -(FP)4 * constants::pi * dt; const FP cdt = constants::c * dt; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); const FP coeffYX = cdt / (grid->steps.y * anisotropyCoeff.x); const FP coeffYZ = cdt / (grid->steps.y * anisotropyCoeff.z); const FP coeffZX = cdt / (grid->steps.z * anisotropyCoeff.x); const FP coeffZY = cdt / (grid->steps.z * anisotropyCoeff.y); // In internal area use: // e.x(i, j, k) += dt * -4pi * j.x(i, j, k) + c * dt * ((b.z(i, j+1, k) - // b.z(i, j, k)) / eps_y * dy - (b.y(i, j, k+1) - b.y(i, j, k)) / eps_z * dz), // e.y(i, j, k) += dt * -4pi * j.y(i, j, k) + c * dt * ((b.x(i, j, k+1) - // b.x(i, j, k)) / eps_z * dz - (b.z(i+1, j, k) - b.z(i, j, k)) / eps_x * dx), // e.z(i, j, k) += dt * -4pi * j.z(i, j, k) + c * dt * ((b.y(i+1, j, k) - // b.y(i, j, k)) / eps_x * dx - (b.x(i, j+1, k) - b.x(i, j, k)) / eps_y * dy), const Int3 begin = internalEAreaBegin; const Int3 end = internalEAreaEnd; #pragma omp parallel for collapse(2) for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) { #pragma simd for (int k = begin.z; k < end.z; k++) { grid->Ex(i, j, k) += coeffCurrent * grid->Jx(i, j, k) + coeffYX * (grid->Bz(i, j + 1, k) - grid->Bz(i, j, k)) - coeffZX * (grid->By(i, j, k + 1) - grid->By(i, j, k)); grid->Ey(i, j, k) += coeffCurrent * grid->Jy(i, j, k) + coeffZY * (grid->Bx(i, j, k + 1) - grid->Bx(i, j, k)) - coeffXY * (grid->Bz(i + 1, j, k) - grid->Bz(i, j, k)); grid->Ez(i, j, k) += coeffCurrent * grid->Jz(i, j, k) + coeffXZ * (grid->By(i + 1, j, k) - grid->By(i, j, k)) - coeffYZ * (grid->Bx(i, j + 1, k) - grid->Bx(i, j, k)); } } // Process edge values if (updateEAreaEnd.x == grid->numCells.x - 1) { int i = updateEAreaEnd.x; #pragma omp parallel for for (int j = begin.y; j < end.y; j++) for (int k = begin.z; k < end.z; k++) grid->Ex(i, j, k) += coeffCurrent * grid->Jx(i, j, k) + coeffYX * (grid->Bz(i, j + 1, k) - grid->Bz(i, j, k)) - coeffZX * (grid->By(i, j, k + 1) - grid->By(i, j, k)); } if (updateEAreaEnd.y == grid->numCells.y - 1) { int j = updateEAreaEnd.y; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) for (int k = begin.z; k < end.z; k++) grid->Ey(i, j, k) += coeffCurrent * grid->Jy(i, j, k) + coeffZY * (grid->Bx(i, j, k + 1) - grid->Bx(i, j, k)) - coeffXY * (grid->Bz(i + 1, j, k) - grid->Bz(i, j, k)); } if (updateEAreaEnd.z == grid->numCells.z - 1) { int k = updateEAreaEnd.z; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) for (int j = begin.y; j < end.y; j++) grid->Ez(i, j, k) += coeffCurrent * grid->Jz(i, j, k) + coeffXZ * (grid->By(i + 1, j, k) - grid->By(i, j, k)) - coeffYZ * (grid->Bx(i, j + 1, k) - grid->Bx(i, j, k)); } } inline void FDTD::updateE2D() { updateEAreaBegin = Int3(0, 0, 0); updateEAreaEnd = grid->numCells - Int3(1, 1, 0); for (int d = 0; d < 2; ++d) { internalEAreaBegin[d] = std::max(updateEAreaBegin[d], pml->leftDims[d]); internalEAreaEnd[d] = std::min(updateEAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP coeffCurrent = -(FP)4 * constants::pi * dt; const FP cdt = constants::c * dt; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); const FP coeffYX = cdt / (grid->steps.y * anisotropyCoeff.x); const FP coeffYZ = cdt / (grid->steps.y * anisotropyCoeff.z); // In internal area use: // e.x(i, j, k) += dt * -4pi * j.x(i, j, k) + c * dt * ((b.z(i, j+1, k) - // b.z(i, j, k)) / eps_y * dy - (b.y(i, j, k+1) - b.y(i, j, k)) / eps_z * dz), // e.y(i, j, k) += dt * -4pi * j.y(i, j, k) + c * dt * ((b.x(i, j, k+1) - // b.x(i, j, k)) / eps_z * dz - (b.z(i+1, j, k) - b.z(i, j, k)) / eps_x * dx), // e.z(i, j, k) += dt * -4pi * j.z(i, j, k) + c * dt * ((b.y(i+1, j, k) - // b.y(i, j, k)) / eps_x * dx - (b.x(i, j+1, k) - b.x(i, j, k)) / eps_y * dy), const Int3 begin = internalEAreaBegin; const Int3 end = internalEAreaEnd; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) { #pragma simd for (int j = begin.y; j < end.y; j++) { grid->Ex(i, j, 0) += coeffCurrent * grid->Jx(i, j, 0) + coeffYX * (grid->Bz(i, j + 1, 0) - grid->Bz(i, j, 0)); grid->Ey(i, j, 0) += coeffCurrent * grid->Jy(i, j, 0) - coeffXY * (grid->Bz(i + 1, j, 0) - grid->Bz(i, j, 0)); grid->Ez(i, j, 0) += coeffCurrent * grid->Jz(i, j, 0) + coeffXZ * (grid->By(i + 1, j, 0) - grid->By(i, j, 0)) - coeffYZ * (grid->Bx(i, j + 1, 0) - grid->Bx(i, j, 0)); } } // Process edge values if (updateEAreaEnd.x == grid->numCells.x - 1) { int i = updateEAreaEnd.x; #pragma omp parallel for for (int j = begin.y; j < end.y; j++) grid->Ex(i, j, 0) += coeffCurrent * grid->Jx(i, j, 0) + coeffYX * (grid->Bz(i, j + 1, 0) - grid->Bz(i, j, 0)); } if (updateEAreaEnd.y == grid->numCells.y - 1) { int j = updateEAreaEnd.y; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) grid->Ey(i, j, 0) += coeffCurrent * grid->Jy(i, j, 0) - coeffXY * (grid->Bz(i + 1, j, 0) - grid->Bz(i, j, 0)); } } inline void FDTD::updateE1D() { updateEAreaBegin = Int3(0, 0, 0); updateEAreaEnd = grid->numCells - Int3(1, 0, 0); for (int d = 0; d < 1; ++d) { internalEAreaBegin[d] = std::max(updateEAreaBegin[d], pml->leftDims[d]); internalEAreaEnd[d] = std::min(updateEAreaEnd[d], grid->numCells[d] - pml->rightDims[d]); } const FP coeffCurrent = -(FP)4 * constants::pi * dt; const FP cdt = constants::c * dt; const FP coeffXY = cdt / (grid->steps.x * anisotropyCoeff.y); const FP coeffXZ = cdt / (grid->steps.x * anisotropyCoeff.z); // In internal area use: // e.x(i, j, k) += dt * -4pi * j.x(i, j, k) + c * dt * ((b.z(i, j+1, k) - // b.z(i, j, k)) / eps_y * dy - (b.y(i, j, k+1) - b.y(i, j, k)) / eps_z * dz), // e.y(i, j, k) += dt * -4pi * j.y(i, j, k) + c * dt * ((b.x(i, j, k+1) - // b.x(i, j, k)) / eps_z * dz - (b.z(i+1, j, k) - b.z(i, j, k)) / eps_x * dx), // e.z(i, j, k) += dt * -4pi * j.z(i, j, k) + c * dt * ((b.y(i+1, j, k) - // b.y(i, j, k)) / eps_x * dx - (b.x(i, j+1, k) - b.x(i, j, k)) / eps_y * dy), const Int3 begin = internalEAreaBegin; const Int3 end = internalEAreaEnd; #pragma omp parallel for for (int i = begin.x; i < end.x; i++) { grid->Ex(i, 0, 0) += coeffCurrent * grid->Jx(i, 0, 0); grid->Ey(i, 0, 0) += coeffCurrent * grid->Jy(i, 0, 0) - coeffXY * (grid->Bz(i + 1, 0, 0) - grid->Bz(i, 0, 0)); grid->Ez(i, 0, 0) += coeffCurrent * grid->Jz(i, 0, 0) + coeffXZ * (grid->By(i + 1, 0, 0) - grid->By(i, 0, 0)); } } }
cell_division_gpu.h
// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef INTEGRATION_CELL_DIVISION_GPU_H_ #define INTEGRATION_CELL_DIVISION_GPU_H_ #include <array> #include "biodynamo.h" #include "math_util.h" namespace bdm { // ---------------------------------------------------------------------------- // Starting with 8 cells, we let each cell grow in volume up until a point // a cell must divide. This tests whether the GPU accelerated mechanical // interactions properly handle the creation of new cells. // ----------------------------------------------------------------------------- inline void EXPECT_ARR_NEAR(const std::array<double, 3>& actual, const std::array<double, 3>& expected, bool* ret) { for (size_t i = 0; i < actual.size(); i++) { if (std::fabs(expected[i] - actual[i]) > 1e-9) { *ret = false; std::cout << "Wrong result! Expected " << expected[i] << ", but instead got " << actual[i] << ", which is a difference of " << std::fabs(expected[i] - actual[i]) << ", which is larger than 1e-9" << std::endl; } } } // 2. Define compile time parameter template <typename Backend> struct CompileTimeParam : public DefaultCompileTimeParam<Backend> { using BiologyModules = Variant<GrowDivide>; }; inline void RunTest(bool* result) { auto rm = ResourceManager<>::Get(); rm->Clear(); auto cells = rm->template Get<Cell>(); // Param::Reset(); // We need to give every test the same seed for the RNG, because in the cell // division, random numbers are used. Within a single executable these numbers // vary. Also within the threads this needs to be enforced #pragma omp parallel { gRandom.SetSeed(1); } size_t cells_per_dim = 2; auto construct = [](const std::array<double, 3>& position) { Cell cell(position); cell.SetDiameter(30); cell.SetAdherence(0.4); cell.SetMass(1.0); cell.AddBiologyModule(GrowDivide(30.05, 5000, {gAllBmEvents})); return cell; }; for (size_t x = 0; x < cells_per_dim; x++) { double x_pos = x * 20.0; for (size_t y = 0; y < cells_per_dim; y++) { double y_pos = y * 20.0; for (size_t z = 0; z < cells_per_dim; z++) { auto new_simulation_object = construct({x_pos, y_pos, z * 20.0}); cells->push_back(new_simulation_object); } } } // Run for 10 timesteps. In step 2 a division should take place. In step 3 // these new cells are instantiated Scheduler<> scheduler; scheduler.Simulate(10); EXPECT_ARR_NEAR( (*cells)[0].GetPosition(), {4.1399071506916413909, -5.9871942139195297727, 2.8344890446256703065}, result); EXPECT_ARR_NEAR( (*cells)[1].GetPosition(), {-2.4263219149482031511, -1.4202336557809887019, 29.769029317615839147}, result); EXPECT_ARR_NEAR( (*cells)[2].GetPosition(), {-4.9118212650644856865, 23.156656083480623209, -9.1231684411316447125}, result); EXPECT_ARR_NEAR( (*cells)[3].GetPosition(), {4.3076765979041251597, 15.615300607043293368, 25.657658447555828474}, result); EXPECT_ARR_NEAR( (*cells)[4].GetPosition(), {28.139314619772036963, -0.20987998233654170388, 4.6381417441282613012}, result); EXPECT_ARR_NEAR( (*cells)[5].GetPosition(), {24.417550786690171094, 3.347525366344008102, 28.067824703341415216}, result); EXPECT_ARR_NEAR( (*cells)[6].GetPosition(), {16.614520566718258721, 15.828015607618416638, -4.8357284569095106974}, result); EXPECT_ARR_NEAR( (*cells)[7].GetPosition(), {14.446017269290647889, 22.250832446808978204, 20.180438615017894932}, result); } inline int Simulate(int argc, const char** argv) { bool result = true; // TODO(ahmad): after Trello card ("Fix inconsistency in cell state due to // direct updates in Biology Modules") // enable multithreading, and adjust results if necessary omp_set_num_threads(1); // Run CPU version RunTest(&result); // Run GPU (CUDA) version Param::use_gpu_ = true; InitializeGPUEnvironment<>(); RunTest(&result); // Run GPU (OpenCL) version Param::use_opencl_ = true; InitializeGPUEnvironment<>(); RunTest(&result); return !result; } } // namespace bdm #endif // INTEGRATION_CELL_DIVISION_GPU_H_
GB_binop__land_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__land_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__land_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__land_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__land_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__land_uint32) // A*D function (colscale): GB (_AxD__land_uint32) // D*A function (rowscale): GB (_DxB__land_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__land_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__land_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__land_uint32) // C=scalar+B GB (_bind1st__land_uint32) // C=scalar+B' GB (_bind1st_tran__land_uint32) // C=A+scalar GB (_bind2nd__land_uint32) // C=A'+scalar GB (_bind2nd_tran__land_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ((x != 0) && (y != 0)) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LAND || GxB_NO_UINT32 || GxB_NO_LAND_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__land_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__land_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__land_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__land_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__land_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__land_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__land_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__land_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__land_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__land_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__land_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__land_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = ((aij != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__land_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__land_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
task-taskgroup-unrelated.c
/* * task-taskgroup-unrelated.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run-race | FileCheck %s // REQUIRES: tsan #include "ompt/ompt-signal.h" #include <omp.h> #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { int var = 0, a = 0; #pragma omp parallel num_threads(2) shared(var, a) #pragma omp master { #pragma omp task shared(var, a) { var++; OMPT_SIGNAL(a); // Give master thread time to execute the task in the taskgroup. OMPT_WAIT(a, 2); } #pragma omp taskgroup { #pragma omp task if (0) { // Dummy task. } // Give other threads time to steal the tasks. OMPT_WAIT(a, 1); OMPT_SIGNAL(a); } var++; } int error = (var != 2); fprintf(stderr, "DONE\n"); return error; } // CHECK: WARNING: ThreadSanitizer: data race // CHECK-NEXT: {{(Write|Read)}} of size 4 // CHECK-NEXT: #0 {{.*}}task-taskgroup-unrelated.c:47 // CHECK: Previous write of size 4 // CHECK-NEXT: #0 {{.*}}task-taskgroup-unrelated.c:29 // CHECK: DONE // CHECK: ThreadSanitizer: reported 1 warnings
GB_binop__pair_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__pair_uint8) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__pair_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__pair_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pair_uint8) // A*D function (colscale): GB (_AxD__pair_uint8) // D*A function (rowscale): GB (_DxB__pair_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__pair_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__pair_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_uint8) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = 1 #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = 1 ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_PAIR || GxB_NO_UINT8 || GxB_NO_PAIR_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__pair_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__pair_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__pair_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__pair_uint8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__pair_uint8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pair_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__pair_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__pair_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__pair_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__pair_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
omp_task.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <math.h> #include "omp_testsuite.h" #include "omp_my_sleep.h" int test_omp_task() { int tids[NUM_TASKS]; int i; #pragma omp parallel { #pragma omp single { for (i = 0; i < NUM_TASKS; i++) { /* First we have to store the value of the loop index in a new variable * which will be private for each task because otherwise it will be overwritten * if the execution of the task takes longer than the time which is needed to * enter the next step of the loop! */ int myi; myi = i; #pragma omp task { my_sleep (SLEEPTIME); tids[myi] = omp_get_thread_num(); } /* end of omp task */ } /* end of for */ } /* end of single */ } /*end of parallel */ /* Now we ckeck if more than one thread executed the tasks. */ for (i = 1; i < NUM_TASKS; i++) { if (tids[0] != tids[i]) return 1; } return 0; } /* end of check_parallel_for_private */ int main() { int i; int num_failed=0; if (omp_get_max_threads() < 2) omp_set_num_threads(8); for(i = 0; i < REPETITIONS; i++) { if(!test_omp_task()) { num_failed++; } } return num_failed; }
GB_binop__minus_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__minus_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__minus_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__minus_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__minus_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint32) // A*D function (colscale): GB (_AxD__minus_uint32) // D*A function (rowscale): GB (_DxB__minus_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__minus_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__minus_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint32) // C=scalar+B GB (_bind1st__minus_uint32) // C=scalar+B' GB (_bind1st_tran__minus_uint32) // C=A+scalar GB (_bind2nd__minus_uint32) // C=A'+scalar GB (_bind2nd_tran__minus_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = (aij - bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x - y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINUS || GxB_NO_UINT32 || GxB_NO_MINUS_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__minus_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__minus_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__minus_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__minus_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__minus_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__minus_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__minus_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__minus_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__minus_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__minus_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__minus_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__minus_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = (x - bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__minus_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij - y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x - aij) ; \ } GrB_Info GB (_bind1st_tran__minus_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - y) ; \ } GrB_Info GB (_bind2nd_tran__minus_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ConvolutionRules.h
// Copyright 2016-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #ifndef CONVOLUTIONRULES_H #define CONVOLUTIONRULES_H #include "RectangularRegions.h" template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(SparseGrid<dimension> &inputGrid, SparseGrid<dimension> &outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { rules.resize(volume<dimension>(size)); for (auto const &inIter : inputGrid.mp) { auto outRegion = OutputRegionCalculator<dimension>( inIter.first, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(inIter.first); auto mapVal = outputGrid.mp.insert(std::make_pair(j, 0)); if (mapVal.second) { mapVal.first->second = outputGrid.ctr++; } rules[rulesOffset].push_back(inIter.second + inputGrid.ctr); rules[rulesOffset].push_back(mapVal.first->second); } } } template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs(SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize) { rules.clear(); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); Int output_nActive = 0; for (Int i = 0; i < batchSize; i++) { auto &iSG = input_SGs[i]; auto &oSG = output_SGs[i]; oSG.ctr = output_nActive; Convolution_InputSgToRulesAndOutputSg<dimension>( iSG, oSG, rules, filterSize, filterStride, input_spatialSize, output_spatialSize); output_nActive = oSG.ctr; oSG.ctr = 0; } return output_nActive; } template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize) { rules.clear(); rules.resize(volume<dimension>(filterSize)); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); std::vector<RuleBook> rbs(batchSize); { Int i; #pragma omp parallel for private(i) for (i = 0; i < batchSize; i++) Convolution_InputSgToRulesAndOutputSg<dimension>( input_SGs[i], output_SGs[i], rbs[i], filterSize, filterStride, input_spatialSize, output_spatialSize); } Int output_nActive = 0; for (Int i = 0; i < batchSize; i++) { // Parallel assignment: // output_nActive <- output_nActive+output_SGs[i].ctr // output_SGs[i].ctr <- output_nActive Int tmp = output_nActive; output_nActive += output_SGs[i].ctr; output_SGs[i].ctr = tmp; } { Int i; #pragma omp parallel for private(i) for (i = 0; i < (Int)rules.size(); i++) { auto &R = rules[i]; for (Int j = 0; j < batchSize; j++) { auto &r = rbs[j][i]; auto offset = output_SGs[j].ctr; for (Int k = 0; k < (Int)r.size();) { R.push_back(r[k++]); R.push_back(r[k++] + offset); } } } } return output_nActive; } // for each active site, list of (inputFeatureNumber,batchIdx, spatialOffset) // triples template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); for (Int batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); Int batchIdx; #pragma omp parallel for private(batchIdx) for (batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } #endif /* CONVOLUTIONRULES_H */
solver.c
//======================================================================================================================================================150 // UPDATE //======================================================================================================================================================150 // Summary of changes by Lukasz G. Szafaryn: // 1) The original code was obtained from: Mathematics Source Library (http://mymathlib.webtrellis.net/index.html) // 2) This solver and particular solving algorithm used with it (embedded_fehlberg_7_8) were adapted to work with a set of equations, not just one like in original version. // 3) In order for solver to provide deterministic number of steps (needed for particular amount of memore previousely allocated for results), every next step is incremented by 1 time unit (h_init). // 4) Function assumes that time interval starts at 0 (xmin) and ends at integer value (xmax) specified by the uses as a parameter on command line. // 5) The appropriate amount of memory is previousely allocated for that range (y). // 5) This setup in 3) - 5) allows solver to adjust the step ony from current time instance to current time instance + 0.9. The next time instance is current time instance + 1; // 6) Solver also takes parameters (params) that it then passes to the equations. // 7) The original solver cannot handle cases when equations return NAN and INF values due to discontinuities and /0. That is why equations provided by user need to make sure that no NAN and INF are returned. // Last update: 15 DEC 09 //======================================================================================================================================================150 // DESCRIPTION //======================================================================================================================================================150 // int solver( fp (*f)(fp, fp), fp y[], // // fp x, fp h, fp xmax, fp *h_next, fp tolerance ) // // // // Description: // // This function solves the differential equation y'=f(x,y) with the // // initial condition y(x) = y[0]. The value at xmax is returned in y[1]. // // The function returns 0 if successful or -1 if it fails. // // // // Arguments: // // fp *f Pointer to the function which returns the slope at (x,y) of // // integral curve of the differential equation y' = f(x,y) // // which passes through the point (x0,y0) corresponding to the // // initial condition y(x0) = y0. // // fp y[] On input y[0] is the initial value of y at x, on output // // y[1] is the solution at xmax. // // fp x The initial value of x. // // fp h Initial step size. // // fp xmax The endpoint of x. // // fp *h_next A pointer to the estimated step size for successive // // calls to solver. // // fp tolerance The tolerance of y(xmax), i.e. a solution is sought // // so that the relative error < tolerance. // // // // Return Values: // // 0 The solution of y' = f(x,y) from x to xmax is stored y[1] and // // h_next has the value to the next size to try. // // -1 The solution of y' = f(x,y) from x to xmax failed. // // -2 Failed because either xmax < x or the step size h <= 0. // // -3 Memory limit allocated for results was reached // //========================================================================================================================================================================================================200 // DEFINE/INCLUDE //========================================================================================================================================================================================================200 //======================================================================================================================================================150 // COMMON //======================================================================================================================================================150 //======================================================================================================================================================150 // DEFINE //======================================================================================================================================================150 #define ATTEMPTS 12 #define MIN_SCALE_FACTOR 0.125 #define MAX_SCALE_FACTOR 4.0 //======================================================================================================================================================150 // KERNEL //======================================================================================================================================================150 #include "./embedded_fehlberg_7_8.c" // (in path provided here) //======================================================================================================================================================150 // LIBRARIES //======================================================================================================================================================150 #include <stdlib.h> // (in path known to compiler) needed by malloc, free #include <math.h> // (in path known to compiler) needed by pow, fabs //======================================================================================================================================================150 // END //======================================================================================================================================================150 //========================================================================================================================================================================================================200 // FUNCTION //========================================================================================================================================================================================================200 int solver( fp **y, fp *x, int xmax, fp *params, fp *com, long long *timecopyin, long long *timecopykernel, long long *timecopyout) { //======================================================================================================================== // VARIABLES //======================================================================================================================== // solver parameters fp err_exponent; int error; int outside; fp h; fp h_init; fp tolerance; int xmin; // memory fp scale_min; fp scale_fina; fp* err= (fp *) malloc(EQUATIONS* sizeof(fp)); fp* scale= (fp *) malloc(EQUATIONS* sizeof(fp)); fp* yy= (fp *) malloc(EQUATIONS* sizeof(fp)); // counters int i, j, k; //======================================================================================================================== // INITIAL SETUP //======================================================================================================================== // solver parameters err_exponent = 1.0 / 7.0; h_init = 1; h = h_init; xmin = 0; tolerance = 10 / (fp)(xmax-xmin); // save value for initial time instance x[0] = 0; //======================================================================================================================== // CHECKING //======================================================================================================================== // Verify that the step size is positive and that the upper endpoint of integration is greater than the initial enpoint. // if (xmax < xmin || h <= 0.0){ return -2; } // If the upper endpoint of the independent variable agrees with the initial value of the independent variable. Set the value of the dependent variable and return success. // if (xmax == xmin){ return 0; } // Insure that the step size h is not larger than the length of the integration interval. // if (h > (xmax - xmin) ) { h = (fp)xmax - (fp)xmin; } //======================================================================================================================== // SOLVING //======================================================================================================================== #ifdef DEBUG printf("Time Steps: "); fflush(0); #endif #pragma omp target enter data map(alloc: params[0:PARAMETERS], com[0:3]) for(k=1; k<=xmax; k++) { // start after initial value x[k] = k-1; h = h_init; //========================================================================================== // REINITIALIZE VARIABLES //========================================================================================== scale_fina = 1.0; //========================================================================================== // MAKE ATTEMPTS TO MINIMIZE ERROR //========================================================================================== // make attempts to minimize error for (j = 0; j < ATTEMPTS; j++) { //============================================================ // REINITIALIZE VARIABLES //============================================================ error = 0; outside = 0; scale_min = MAX_SCALE_FACTOR; //============================================================ // EVALUATE ALL EQUATIONS //============================================================ embedded_fehlberg_7_8( x[k], h, y[k-1], y[k], params, com, err, timecopyin, timecopykernel, timecopyout); //============================================================ // IF THERE WAS NO ERROR FOR ANY OF EQUATIONS, SET SCALE AND LEAVE THE LOOP //============================================================ for(i=0; i<EQUATIONS; i++){ if(err[i] > 0){ error = 1; } } if (error != 1) { scale_fina = MAX_SCALE_FACTOR; break; } //============================================================ // FIGURE OUT SCALE AS THE MINIMUM OF COMPONENT SCALES //============================================================ for(i=0; i<EQUATIONS; i++){ if(y[k-1][i] == 0.0){ yy[i] = tolerance; } else{ yy[i] = fabs(y[k-1][i]); } scale[i] = 0.8 * pow( tolerance * yy[i] / err[i] , err_exponent ); if(scale[i]<scale_min){ scale_min = scale[i]; } } #define max(x,y) ( (x) < (y) ? (y) : (x) ) #define min(x,y) ( (x) < (y) ? (x) : (y) ) scale_fina = min( max(scale_min,MIN_SCALE_FACTOR), MAX_SCALE_FACTOR); //============================================================ // IF WITHIN TOLERANCE, FINISH ATTEMPTS... //============================================================ for(i=0; i<EQUATIONS; i++){ if ( err[i] > ( tolerance * yy[i] ) ){ outside = 1; } } if (outside == 0){ break; } //============================================================ // ...OTHERWISE, ADJUST STEP FOR NEXT ATTEMPT //============================================================ // scale next step in a default way h = h * scale_fina; // limit step to 0.9, because when it gets close to 1, it no longer makes sense, as 1 is already the next time instance (added to original algorithm) if (h >= 0.9) { h = 0.9; } // if instance+step exceeds range limit, limit to that range if ( x[k] + h > (fp)xmax ){ h = (fp)xmax - x[k]; } // if getting closer to range limit, decrease step else if ( x[k] + h + 0.5 * h > (fp)xmax ){ h = 0.5 * h; } } //========================================================================================== // SAVE TIME INSTANCE THAT SOLVER ENDED UP USING //========================================================================================== x[k] = x[k] + h; //========================================================================================== // IF MAXIMUM NUMBER OF ATTEMPTS REACHED AND CANNOT GIVE SOLUTION, EXIT PROGRAM WITH ERROR //========================================================================================== if ( j >= ATTEMPTS ) { #pragma omp target exit data map(release: params[0:PARAMETERS], com[0:3]) return -1; } #ifdef DEBUG printf("%d ", k); fflush(0); #endif } #pragma omp target exit data map(release: params[0:PARAMETERS], com[0:3]) #ifdef DEBUG printf("\n"); fflush(0); #endif //======================================================================================================================== // FREE MEMORY //======================================================================================================================== free(err); free(scale); free(yy); //======================================================================================================================== // FINAL RETURN //======================================================================================================================== return 0; }
nbody-block.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "timer.h" #define CACHELINE 64 // size of cache line [bytes] #define SOFTENING 1e-9f typedef struct { float *x, *y, *z, *vx, *vy, *vz; } BodySystem; void randomizeBodies(float *data, int n) { for (int i = 0; i < n; i++) { data[i] = 2.0f * (rand() / (float)RAND_MAX) - 1.0f; } } void bodyForce(BodySystem p, float dt, int n, int tileSize) { for (int tile = 0; tile < n; tile += tileSize) { int to = tile + tileSize; if (to > n) to = n; #pragma omp parallel for schedule(dynamic) for (int i = 0; i < n; i++) { float Fx = 0.0f; float Fy = 0.0f; float Fz = 0.0f; for (int j = tile; j < to; j++) { float dy = p.y[j] - p.y[i]; float dz = p.z[j] - p.z[i]; float dx = p.x[j] - p.x[i]; float distSqr = dx*dx + dy*dy + dz*dz + SOFTENING; float invDist = 1.0f / sqrtf(distSqr); float invDist3 = invDist * invDist * invDist; Fx += dx * invDist3; Fy += dy * invDist3; Fz += dz * invDist3; } p.vx[i] += dt*Fx; p.vy[i] += dt*Fy; p.vz[i] += dt*Fz; } } } int main(const int argc, const char** argv) { int nBodies = 30000; if (argc > 1) nBodies = atoi(argv[1]); int tileSize = 24400; if (tileSize > nBodies) tileSize = nBodies; const float dt = 0.01f; // time step const int nIters = 10; // simulation iterations int bytes = 6*nBodies*sizeof(float); float *buf = (float*)malloc(bytes); BodySystem p; p.x = buf+0*nBodies; p.y = buf+1*nBodies; p.z = buf+2*nBodies; p.vx = buf+3*nBodies; p.vy = buf+4*nBodies; p.vz = buf+5*nBodies; randomizeBodies(buf, 6*nBodies); // Init pos / vel data double totalTime = 0.0; for (int iter = 1; iter <= nIters; iter++) { StartTimer(); bodyForce(p, dt, nBodies, tileSize); // compute interbody forces for (int i = 0 ; i < nBodies; i++) { // integrate position p.x[i] += p.vx[i]*dt; p.y[i] += p.vy[i]*dt; p.z[i] += p.vz[i]*dt; } const double tElapsed = GetTimer() / 1000.0; if (iter > 1) { // First iter is warm up totalTime += tElapsed; } #ifndef SHMOO printf("Iteration %d: %.3f seconds\n", iter, tElapsed); #endif } double avgTime = totalTime / (double)(nIters-1); #ifdef SHMOO printf("%d, %0.3f\n", nBodies, 1e-9 * nBodies * nBodies / avgTime); #else printf("Average rate for iterations 2 through %d: %.3f +- %.3f steps per second.\n", nIters, rate); printf("%d Bodies: average %0.3f Billion Interactions / second\n", nBodies, 1e-9 * nBodies * nBodies / avgTime); #endif free(buf); }
kpoint.c
/* kpoint.c */ /* Copyright (C) 2008 Atsushi Togo */ #include <stdio.h> #include <stdlib.h> #include "mathfunc.h" #include "symmetry.h" #include "kpoint.h" #include "debug.h" /* #define GRID_ORDER_XYZ */ /* The addressing order of mesh grid is defined as running left */ /* element first. But when GRID_ORDER_XYZ is defined, it is changed to right */ /* element first. */ static PointSymmetry get_point_group_reciprocal(const MatINT * rotations, const int is_time_reversal); static PointSymmetry get_point_group_reciprocal_with_q(SPGCONST PointSymmetry * pointgroup, const double symprec, const int num_q, SPGCONST double qpoints[][3]); static int get_ir_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, SPGCONST PointSymmetry * point_symmetry, const double symprec); static int get_ir_reciprocal_mesh(int grid_point[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry); static Triplets * get_ir_triplets(const int mesh[3], const int is_time_reversal, const MatINT * rotations, const double symprec); static int get_ir_triplets_with_q(int weights[], int grid_points[][3], int third_q[], const int grid_point, const int mesh[3], PointSymmetry * pointgroup, const double symprec); static int extract_ir_triplets_with_q(int triplets_with_q[][3], int weight_with_q[], const int fixed_grid_number, SPGCONST int triplets[][3], const int num_triplets, const int mesh[3], SPGCONST PointSymmetry * point_symmetry); static void get_grid_mapping_table(int **map_sym, SPGCONST PointSymmetry * point_symmetry, const int mesh[3], const int is_shift[3]); static void address_to_grid(int grid_double[3], const int address, const int mesh[3], const int is_shift[3]); static void get_grid_points(int grid_point[3], const int grid[3], const int mesh[3]); static void get_vector_modulo(int v[3], const int m[3]); static int grid_to_address(const int grid[3], const int mesh[3], const int is_shift[3]); static void free_array2D_int(int **array, const int num_row); static int ** allocate_array2d_int(const int num_row, const int num_column); static Triplets * allocate_triplets(const int num_triplets, const int mesh[3]); int kpt_get_irreducible_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, const Symmetry * symmetry, const int is_time_reversal, const double symprec) { int i; PointSymmetry point_symmetry; MatINT *rotations; rotations = mat_alloc_MatINT(symmetry->size); for (i = 0; i < symmetry->size; i++) { mat_copy_matrix_i3(rotations->mat[i], symmetry->rot[i]); } point_symmetry = get_point_group_reciprocal(rotations, is_time_reversal); mat_free_MatINT(rotations); return get_ir_kpoints(map, kpoints, num_kpoint, &point_symmetry, symprec); } /* grid_point (e.g. 4x4x4 mesh) */ /* [[ 0 0 0] */ /* [ 1 0 0] */ /* [ 2 0 0] */ /* [-1 0 0] */ /* [ 0 1 0] */ /* [ 1 1 0] */ /* [ 2 1 0] */ /* [-1 1 0] */ /* .... ] */ /* */ /* Each value of 'map' correspnds to the index of grid_point. */ int kpt_get_irreducible_reciprocal_mesh(int grid_points[][3], int map[], const int mesh[3], const int is_shift[3], const int is_time_reversal, const Symmetry * symmetry) { int i; PointSymmetry point_symmetry; MatINT *rotations; rotations = mat_alloc_MatINT(symmetry->size); for (i = 0; i < symmetry->size; i++) { mat_copy_matrix_i3(rotations->mat[i], symmetry->rot[i]); } point_symmetry = get_point_group_reciprocal(rotations, is_time_reversal); mat_free_MatINT(rotations); return get_ir_reciprocal_mesh(grid_points, map, mesh, is_shift, &point_symmetry); } void kpt_free_triplets(Triplets * t) { free(t->triplets); t->triplets = NULL; free(t->weights); t->weights = NULL; free(t->mesh_points); t->mesh_points = NULL; free(t); t = NULL; } int kpt_get_stabilized_reciprocal_mesh(int grid_points[][3], int map[], const int mesh[3], const int is_shift[3], const int is_time_reversal, const MatINT * rotations, const int num_q, SPGCONST double qpoints[][3], const double symprec) { PointSymmetry pointgroup, pointgroup_q; pointgroup = get_point_group_reciprocal(rotations, is_time_reversal); pointgroup_q = get_point_group_reciprocal_with_q(&pointgroup, symprec, num_q, qpoints); return get_ir_reciprocal_mesh(grid_points, map, mesh, is_shift, &pointgroup_q); } Triplets * kpt_get_triplets_reciprocal_mesh(const int mesh[3], const int is_time_reversal, const MatINT * rotations, const double symprec) { return get_ir_triplets(mesh, is_time_reversal, rotations, symprec); } int kpt_get_ir_triplets_at_q(int weights[], int grid_points[][3], int third_q[], const int grid_point, const int mesh[3], const int is_time_reversal, const MatINT * rotations, const double symprec) { PointSymmetry pointgroup; pointgroup = get_point_group_reciprocal(rotations, is_time_reversal); return get_ir_triplets_with_q(weights, grid_points, third_q, grid_point, mesh, &pointgroup, symprec); } int kpt_extract_triplets_reciprocal_mesh_at_q(int triplets_with_q[][3], int weight_with_q[], const int fixed_grid_number, const int num_triplets, SPGCONST int triplets[][3], const int mesh[3], const int is_time_reversal, const MatINT * rotations) { PointSymmetry point_group; point_group = get_point_group_reciprocal(rotations, is_time_reversal); return extract_ir_triplets_with_q(triplets_with_q, weight_with_q, fixed_grid_number, triplets, num_triplets, mesh, &point_group); } /* qpoints are used to find stabilizers (operations). */ /* num_q is the number of the qpoints. */ static PointSymmetry get_point_group_reciprocal(const MatINT * rotations, const int is_time_reversal) { int i, j, num_pt = 0; MatINT *rot_reciprocal; PointSymmetry point_symmetry; SPGCONST int inversion[3][3] = { {-1, 0, 0 }, { 0,-1, 0 }, { 0, 0,-1 } }; if (is_time_reversal) { rot_reciprocal = mat_alloc_MatINT(rotations->size * 2); } else { rot_reciprocal = mat_alloc_MatINT(rotations->size); } for (i = 0; i < rotations->size; i++) { mat_transpose_matrix_i3(rot_reciprocal->mat[i], rotations->mat[i]); if (is_time_reversal) { mat_multiply_matrix_i3(rot_reciprocal->mat[rotations->size+i], inversion, rot_reciprocal->mat[i]); } } for (i = 0; i < rot_reciprocal->size; i++) { for (j = 0; j < num_pt; j++) { if (mat_check_identity_matrix_i3(point_symmetry.rot[j], rot_reciprocal->mat[i])) { goto escape; } } mat_copy_matrix_i3(point_symmetry.rot[num_pt], rot_reciprocal->mat[i]); num_pt++; escape: ; } point_symmetry.size = num_pt; mat_free_MatINT(rot_reciprocal); return point_symmetry; } static PointSymmetry get_point_group_reciprocal_with_q(SPGCONST PointSymmetry * pointgroup, const double symprec, const int num_q, SPGCONST double qpoints[][3]) { int i, j, k, l, is_all_ok=0, num_ptq = 0; double q_rot[3], diff[3]; PointSymmetry pointgroup_q; for (i = 0; i < pointgroup->size; i++) { for (j = 0; j < num_q; j++) { is_all_ok = 0; mat_multiply_matrix_vector_id3(q_rot, pointgroup->rot[i], qpoints[j]); for (k = 0; k < num_q; k++) { for (l = 0; l < 3; l++) { diff[l] = q_rot[l] - qpoints[k][l]; diff[l] -= mat_Nint(diff[l]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { is_all_ok = 1; break; } } if (! is_all_ok) { break; } } if (is_all_ok) { mat_copy_matrix_i3(pointgroup_q.rot[num_ptq], pointgroup->rot[i]); num_ptq++; } } pointgroup_q.size = num_ptq; return pointgroup_q; } static int get_ir_kpoints(int map[], SPGCONST double kpoints[][3], const int num_kpoint, SPGCONST PointSymmetry * point_symmetry, const double symprec) { int i, j, k, l, num_ir_kpoint = 0, is_found; int *ir_map; double kpt_rot[3], diff[3]; ir_map = (int*)malloc(num_kpoint*sizeof(int)); for (i = 0; i < num_kpoint; i++) { map[i] = i; is_found = 1; for (j = 0; j < point_symmetry->size; j++) { mat_multiply_matrix_vector_id3(kpt_rot, point_symmetry->rot[j], kpoints[i]); for (k = 0; k < 3; k++) { diff[k] = kpt_rot[k] - kpoints[i][k]; diff[k] = diff[k] - mat_Nint(diff[k]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { continue; } for (k = 0; k < num_ir_kpoint; k++) { mat_multiply_matrix_vector_id3(kpt_rot, point_symmetry->rot[j], kpoints[i]); for (l = 0; l < 3; l++) { diff[l] = kpt_rot[l] - kpoints[ir_map[k]][l]; diff[l] = diff[l] - mat_Nint(diff[l]); } if (mat_Dabs(diff[0]) < symprec && mat_Dabs(diff[1]) < symprec && mat_Dabs(diff[2]) < symprec) { is_found = 0; map[i] = ir_map[k]; break; } } if (! is_found) break; } if (is_found) { ir_map[num_ir_kpoint] = i; num_ir_kpoint++; } } free(ir_map); ir_map = NULL; return num_ir_kpoint; } static int get_ir_reciprocal_mesh(int grid[][3], int map[], const int mesh[3], const int is_shift[3], SPGCONST PointSymmetry * point_symmetry) { /* In the following loop, mesh is doubled. */ /* Even and odd mesh numbers correspond to */ /* is_shift[i] = 0 and 1, respectively. */ /* is_shift = [0,0,0] gives Gamma center mesh. */ /* grid: reducible grid points */ /* map: the mapping from each point to ir-point. */ int i, j, k, l, address, address_rot, num_ir = 0; int grid_double[3], grid_rot[3], mesh_double[3]; for (i = 0; i < 3; i++) { mesh_double[i] = mesh[i] * 2; } /* "-1" means the element is not touched yet. */ for (i = 0; i < mesh[0] * mesh[1] * mesh[2]; i++) { map[i] = -1; } #ifndef GRID_ORDER_XYZ for (i = 0; i < mesh_double[2]; i++) { if ((is_shift[2] && i % 2 == 0) || (is_shift[2] == 0 && i % 2 != 0)) continue; for (j = 0; j < mesh_double[1]; j++) { if ((is_shift[1] && j % 2 == 0) || (is_shift[1] == 0 && j % 2 != 0)) continue; for (k = 0; k < mesh_double[0]; k++) { if ((is_shift[0] && k % 2 == 0) || (is_shift[0] == 0 && k % 2 != 0)) continue; grid_double[0] = k; grid_double[1] = j; grid_double[2] = i; #else for (i = 0; i < mesh_double[0]; i++) { if ((is_shift[0] && i % 2 == 0) || (is_shift[0] == 0 && i % 2 != 0)) continue; for (j = 0; j < mesh_double[1]; j++) { if ((is_shift[1] && j % 2 == 0) || (is_shift[1] == 0 && j % 2 != 0)) continue; for (k = 0; k < mesh_double[2]; k++) { if ((is_shift[2] && k % 2 == 0) || (is_shift[2] == 0 && k % 2 != 0)) continue; grid_double[0] = i; grid_double[1] = j; grid_double[2] = k; #endif address = grid_to_address(grid_double, mesh, is_shift); get_grid_points(grid[address], grid_double, mesh); for (l = 0; l < point_symmetry->size; l++) { mat_multiply_matrix_vector_i3(grid_rot, point_symmetry->rot[l], grid_double); get_vector_modulo(grid_rot, mesh_double); address_rot = grid_to_address(grid_rot, mesh, is_shift); if (address_rot > -1) { /* Invalid if even --> odd or odd --> even */ if (map[address_rot] > -1) { map[address] = map[address_rot]; break; } } } /* Set itself to the map when equivalent point */ /* with smaller numbering could not be found. */ if (map[address] == -1) { map[address] = address; num_ir++; } } } } return num_ir; } /* Unique q-point triplets that conserve the momentum, */ /* q+q'+q''=G, are obtained. */ /* */ /* The first q-point is selected among the ir-q-points. */ /* The second q-point is selected among the ir-q-points */ /* constrained by the first q-point (stabilizer) */ /* The third q-point is searched through the all grid */ /* points and is checked if it satisfies q+q'+q''=G, */ /* here q, q', and q'' can be exchanged one another. */ static Triplets * get_ir_triplets(const int mesh[3], const int is_time_reversal, const MatINT * rotations, const double symprec) { int i, j, k, l, num_ir, num_grid, weight, weight_q, count, q_2; int num_triplets, num_unique_q; int mesh_double[3], address[3], is_shift[3]; int grid_double[3][3]; int (*grid)[3], (*grid_local)[3]; int *map, *map_q, *unique_q; int **map_sym = NULL; int **weight_counts; double stabilizer_q[1][3]; PointSymmetry point_symmetry, point_symmetry_q; Triplets * tps; const int index_exchange[6][3] = {{ 0, 1, 2 }, { 2, 0, 1 }, { 1, 2, 0 }, { 2, 1, 0 }, { 0, 2, 1 }, { 1, 0, 2 }}; num_grid = mesh[0] * mesh[1] * mesh[2]; map = (int*) malloc(num_grid * sizeof(int)); unique_q = (int*) malloc(num_grid * sizeof(int)); grid = (int (*)[3]) malloc(sizeof(int[3]) * num_grid); point_symmetry = get_point_group_reciprocal(rotations, is_time_reversal); /* Only consider the gamma-point */ for (i = 0; i < 3; i++) { is_shift[i] = 0; } num_ir = get_ir_reciprocal_mesh(grid, map, mesh, is_shift, &point_symmetry); weight_counts = allocate_array2d_int(num_ir, num_grid); for (i = 0; i < num_ir; i++) { for (j = 0; j < num_grid; j++) { weight_counts[i][j] = 0; } } for (i = 0; i < 3; i++) { mesh_double[i] = mesh[i] * 2; } /* Prepare triplet mapping table to enhance speed of query */ /* 'unique_q' numbering is prepared for saving memory space */ num_unique_q = 0; for (i = 0; i < num_grid; i++) { if (i == map[i]) { unique_q[i] = num_unique_q; num_unique_q++; } else { unique_q[i] = unique_q[map[i]]; } } /* Prepare grid point mapping table */ map_sym = allocate_array2d_int(point_symmetry.size, num_grid); get_grid_mapping_table(map_sym, &point_symmetry, mesh, is_shift); /* Search triplets without considersing combination */ /* #pragma omp parallel for private(j, k, l, grid_double, point_symmetry_q, stabilizer_q, weight_q, grid_local, address, map_q, weight ) */ for (i = 0; i < num_grid; i++) { if (! (i == map[i])) { continue; } weight = 0; for (j = 0; j < num_grid; j++) { if (i == map[j]) { weight++; } } /* Search irreducible q-points (map_q) with a stabilizer */ address_to_grid(grid_double[0], i, mesh, is_shift); /* q */ for (j = 0; j < 3; j++) { stabilizer_q[0][j] = (double)grid_double[0][j] / mesh_double[j]; } point_symmetry_q = get_point_group_reciprocal_with_q(&point_symmetry, symprec, 1, stabilizer_q); grid_local = (int (*)[3]) malloc(sizeof(int[3]) * num_grid); map_q = (int*) malloc(num_grid * sizeof(int)); get_ir_reciprocal_mesh(grid_local, map_q, mesh, is_shift, &point_symmetry_q); free(grid_local); grid_local = NULL; for (j = 0; j < num_grid; j++) { if (! (j == map_q[j])) { continue; } weight_q = 0; for (k = 0; k < num_grid; k++) { if (j == map_q[k]) { weight_q++; } } address_to_grid(grid_double[1], j, mesh, is_shift); /* q' */ for (k = 0; k < 3; k++) { /* q'' */ grid_double[2][k] = - grid_double[0][k] - grid_double[1][k]; } get_vector_modulo(grid_double[2], mesh_double); q_2 = grid_to_address(grid_double[2], mesh, is_shift); /* Look for irreducible triplets exchanging three q-points */ /* and equivalent by symmetry rotations */ for (k = 0; k < point_symmetry.size; k++) { /* Index exchange */ for (l = 0; l < 6; l++) { /* Rotated grid point addresses with index exchange */ address[index_exchange[l][0]] = map_sym[k][i]; address[index_exchange[l][1]] = map_sym[k][j]; address[index_exchange[l][2]] = map_sym[k][q_2]; /* address[0] has to be one of ir-q-points. */ if (address[0] == map[address[0]]) { /* Is the set of ddress[0] and address[1] already found? */ if (weight_counts[unique_q[address[0]]][address[1]]) { weight_counts[unique_q[address[0]]][address[1]] += weight * weight_q; goto escape; } } } } /* Not found, then this is an irreducible triplet. */ weight_counts[unique_q[i]][j] = weight * weight_q; escape: ; } free(map_q); map_q = NULL; } num_triplets = 0; for (i = 0; i < num_grid; i++) { if (! (i == map[i])) { continue; } for (j = 0; j < num_grid; j++) { if (weight_counts[unique_q[i]][j]) { num_triplets++; } } } tps = allocate_triplets(num_triplets, mesh); for (i = 0; i < num_grid; i++) { for (j = 0; j < 3; j++) { tps->mesh_points[i][j] = grid[i][j]; } } count = 0; for (i = 0; i < num_grid; i++) { if (! (i == map[i])) { continue; } for (j = 0; j < num_grid; j++) { if (weight_counts[unique_q[i]][j] ) { tps->triplets[count][0] = i; tps->triplets[count][1] = j; address_to_grid(grid_double[0], i, mesh, is_shift); /* q */ address_to_grid(grid_double[1], j, mesh, is_shift); /* q' */ for (l = 0; l < 3; l++) { /* q'' */ grid_double[2][l] = - grid_double[0][l] - grid_double[1][l]; } get_vector_modulo(grid_double[2], mesh_double); tps->triplets[count][2] = grid_to_address(grid_double[2], mesh, is_shift); tps->weights[count] = weight_counts[unique_q[i]][j]; count++; } } } free_array2D_int(map_sym, point_symmetry.size); free_array2D_int(weight_counts, num_ir); free(map); map = NULL; free(unique_q); unique_q = NULL; free(grid); grid = NULL; return tps; } static int get_ir_triplets_with_q(int weights[], int grid_points[][3], int third_q[], const int grid_point, const int mesh[3], PointSymmetry * pointgroup, const double symprec) { int i, j, k, num_grid, weight_q, q_2, num_ir; int mesh_double[3], address[3], is_shift[3]; int grid_double[3][3]; int *map_q; int **map_sym = NULL; double stabilizer_q[1][3]; PointSymmetry pointgroup_q; const int index_exchange[6][3] = {{ 0, 1, 2 }, { 2, 0, 1 }, { 1, 2, 0 }, { 2, 1, 0 }, { 0, 2, 1 }, { 1, 0, 2 }}; num_grid = mesh[0] * mesh[1] * mesh[2]; for (i = 0; i < 3; i++) { /* Only consider the gamma-point */ is_shift[i] = 0; mesh_double[i] = mesh[i] * 2; } /* Search irreducible q-points (map_q) with a stabilizer */ address_to_grid(grid_double[0], grid_point, mesh, is_shift); /* q */ for (i = 0; i < 3; i++) { stabilizer_q[0][i] = (double)grid_double[0][i] / mesh_double[i]; } pointgroup_q = get_point_group_reciprocal_with_q(pointgroup, symprec, 1, stabilizer_q); map_sym = allocate_array2d_int(pointgroup->size, num_grid); get_grid_mapping_table(map_sym, pointgroup, mesh, is_shift); map_q = (int*) malloc(sizeof(int) * num_grid); get_ir_reciprocal_mesh(grid_points, map_q, mesh, is_shift, &pointgroup_q); for (i = 0; i < num_grid; i++) { weights[i] = 0; third_q[i] = -1; } num_ir = 0; for (i = 0; i < num_grid; i++) { if (! (i == map_q[i])) { continue; } weight_q = 0; for (j = 0; j < num_grid; j++) { if (i == map_q[j]) { weight_q++; } } address_to_grid(grid_double[1], i, mesh, is_shift); /* q' */ for (j = 0; j < 3; j++) { /* q'' */ grid_double[2][j] = - grid_double[0][j] - grid_double[1][j]; } get_vector_modulo(grid_double[2], mesh_double); q_2 = grid_to_address(grid_double[2], mesh, is_shift); third_q[i] = q_2; /* Look for irreducible triplets exchanging three q-points */ /* and equivalent by symmetry rotations */ for (j = 0; j < pointgroup->size; j++) { /* Index exchange */ for (k = 0; k < 6; k++) { /* Rotated grid point addresses with index exchange */ address[index_exchange[k][0]] = map_sym[j][grid_point]; address[index_exchange[k][1]] = map_sym[j][i]; address[index_exchange[k][2]] = map_sym[j][q_2]; if (address[0] == grid_point) { /* Is the set of ddress[0] and address[1] already found? */ if (weights[address[1]]) { weights[address[1]] += weight_q; goto escape; } } } } /* Not found, then this is an irreducible triplet. */ weights[i] = weight_q; num_ir++; escape: ; } free(map_q); map_q = NULL; free_array2D_int(map_sym, pointgroup->size); return num_ir; } static int extract_ir_triplets_with_q(int triplets_with_q[][3], int weight_with_q[], const int fixed_grid_number, SPGCONST int triplets[][3], const int num_triplets, const int mesh[3], SPGCONST PointSymmetry *point_symmetry) { int i, j, k, sym_num, rest_index, num_triplets_with_q; int address0, address1, address1_orig, found; int is_shift[3]; int num_grid; int **map_sym; num_grid = mesh[0] * mesh[1] * mesh[2]; map_sym = allocate_array2d_int(point_symmetry->size, num_grid); /* Only consider the gamma-point */ for (i = 0; i < 3; i++) { is_shift[i] = 0; } /* Prepare mapping tables */ get_grid_mapping_table(map_sym, point_symmetry, mesh, is_shift); num_triplets_with_q = 0; for (i = 0; i < num_triplets; i++) { sym_num = -1; for (j = 0; j < point_symmetry->size; j++) { address0 = map_sym[j][fixed_grid_number]; if (triplets[i][0] == address0 || triplets[i][1] == address0 || triplets[i][2] == address0) { for (k = 0; k < num_grid; k++) { address1 = map_sym[j][k]; /* Matching indices 0 and 1 */ if ((triplets[i][0] == address0 && triplets[i][1] == address1) || (triplets[i][1] == address0 && triplets[i][0] == address1)) { sym_num = j; rest_index = 2; address1_orig = k; break; } /* Matching indices 1 and 2 */ if ((triplets[i][1] == address0 && triplets[i][2] == address1) || (triplets[i][2] == address0 && triplets[i][1] == address1)) { sym_num = j; rest_index = 0; address1_orig = k; break; } /* Matching indices 2 and 0 */ if ((triplets[i][2] == address0 && triplets[i][0] == address1) || (triplets[i][0] == address0 && triplets[i][2] == address1)) { sym_num = j; rest_index = 1; address1_orig = k; break; } } if (sym_num > -1) { break; } } } /* Found? */ if (sym_num > -1) { for (j = 0; j < num_grid; j++) { if (map_sym[sym_num][j] == triplets[i][rest_index]) { triplets_with_q[num_triplets_with_q][0] = fixed_grid_number; if (j > address1_orig) { triplets_with_q[num_triplets_with_q][1] = address1_orig; triplets_with_q[num_triplets_with_q][2] = j; } else { triplets_with_q[num_triplets_with_q][2] = address1_orig; triplets_with_q[num_triplets_with_q][1] = j; } num_triplets_with_q++; break; } } } } for (i = 0; i < num_triplets_with_q; i++) { weight_with_q[i] = 0; } for (i = 0; i < num_grid; i++) { found = 0; for (j = 0; j < num_triplets_with_q; j++) { for (k = 0; k < point_symmetry->size; k++) { if (map_sym[k][fixed_grid_number] == triplets_with_q[j][0]) { if (map_sym[k][i] == triplets_with_q[j][1] || map_sym[k][i] == triplets_with_q[j][2]) { weight_with_q[j]++; found = 1; break; } } if (map_sym[k][fixed_grid_number] == triplets_with_q[j][1]) { if (map_sym[k][i] == triplets_with_q[j][2] || map_sym[k][i] == triplets_with_q[j][0]) { weight_with_q[j]++; found = 1; break; } } if (map_sym[k][fixed_grid_number] == triplets_with_q[j][2]) { if (map_sym[k][i] == triplets_with_q[j][0] || map_sym[k][i] == triplets_with_q[j][1]) { weight_with_q[j]++; found = 1; break; } } } if (found) { break; } } if (! found) { warning_print("spglib: Unexpected behavior in extract_ir_triplets_with_q "); warning_print("(line %d, %s).\n", __LINE__, __FILE__); num_triplets_with_q = 0; break; } } free_array2D_int(map_sym, point_symmetry->size); return num_triplets_with_q; } static void get_grid_mapping_table(int **map_sym, SPGCONST PointSymmetry *point_symmetry, const int mesh[3], const int is_shift[3]) { int i, j; int grid_rot[3], grid_double[3], mesh_double[3]; for (i = 0; i < 3; i++) { mesh_double[i] = mesh[i] * 2; } for (i = 0; i < point_symmetry->size; i++) { for (j = 0; j < mesh[0]*mesh[1]*mesh[2]; j++) { address_to_grid(grid_double, j, mesh, is_shift); mat_multiply_matrix_vector_i3(grid_rot, point_symmetry->rot[i], grid_double); get_vector_modulo(grid_rot, mesh_double); map_sym[i][j] = grid_to_address(grid_rot, mesh, is_shift); } } } static int grid_to_address(const int grid_double[3], const int mesh[3], const int is_shift[3]) { int i, grid[3]; for (i = 0; i < 3; i++) { if (grid_double[i] % 2 == 0 && (! is_shift[i]) ) { grid[i] = grid_double[i] / 2; } else { if (grid_double[i] % 2 != 0 && is_shift[i]) { grid[i] = (grid_double[i] - 1) / 2; } else { return -1; } } } #ifndef GRID_ORDER_XYZ return grid[2] * mesh[0] * mesh[1] + grid[1] * mesh[0] + grid[0]; #else return grid[0] * mesh[1] * mesh[2] + grid[1] * mesh[2] + grid[2]; #endif } static void address_to_grid(int grid_double[3], const int address, const int mesh[3], const int is_shift[3]) { int i; int grid[3]; #ifndef GRID_ORDER_XYZ grid[2] = address / (mesh[0] * mesh[1]); grid[1] = (address - grid[2] * mesh[0] * mesh[1]) / mesh[0]; grid[0] = address % mesh[0]; #else grid[0] = address / (mesh[1] * mesh[2]); grid[1] = (address - grid[0] * mesh[1] * mesh[2]) / mesh[2]; grid[2] = address % mesh[2]; #endif for (i = 0; i < 3; i++) { grid_double[i] = grid[i] * 2 + is_shift[i]; } } static void get_grid_points(int grid[3], const int grid_double[3], const int mesh[3]) { int i; for (i = 0; i < 3; i++) { if (grid_double[i] % 2 == 0) { grid[i] = grid_double[i] / 2; } else { grid[i] = (grid_double[i] - 1) / 2; } #ifndef GRID_BOUNDARY_AS_NEGATIVE grid[i] = grid[i] - mesh[i] * (grid[i] > mesh[i] / 2); #else grid[i] = grid[i] - mesh[i] * (grid[i] >= mesh[i] / 2); #endif } } static void get_vector_modulo(int v[3], const int m[3]) { int i; for (i = 0; i < 3; i++) { v[i] = v[i] % m[i]; if (v[i] < 0) v[i] += m[i]; } } static void free_array2D_int(int **array, const int num_row) { int i; for (i = 0; i < num_row; i++) { free(array[i]); array[i] = NULL; } free(array); array = NULL; } static int ** allocate_array2d_int(const int num_row, const int num_column) { int i; int **array; array = (int**) malloc(num_row * sizeof(int*)); for (i = 0; i < num_row; i++) { array[i] = (int*) malloc(num_column * sizeof(int)); } return array; } static Triplets * allocate_triplets(const int num_triplets, const int mesh[3]) { int i, num_grid; Triplets * tps; num_grid = mesh[0] * mesh[1] * mesh[2]; tps = (Triplets*) malloc(sizeof(Triplets)); tps->size = num_triplets; tps->triplets = (int (*)[3]) malloc(sizeof(int[3]) * num_triplets); tps->weights = (int*) malloc(sizeof(int) * num_triplets); tps->mesh_points = (int (*)[3]) malloc(sizeof(int[3]) * num_grid); for (i = 0; i < 3; i++) { tps->mesh[i] = mesh[i]; } return tps; }
convolution_1x1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void conv1x1s1_sgemm_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_neon(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = 0; int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ nn_outch = outch >> 3; remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); Mat out4 = top_blob.channel(p + 4); Mat out5 = top_blob.channel(p + 5); Mat out6 = top_blob.channel(p + 6); Mat out7 = top_blob.channel(p + 7); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float bias4 = bias ? bias[p + 4] : 0.f; const float bias5 = bias ? bias[p + 5] : 0.f; const float bias6 = bias ? bias[p + 6] : 0.f; const float bias7 = bias ? bias[p + 7] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); out6.fill(bias6); out7.fill(bias7); int q = 0; for (; q + 7 < inch; q += 8) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* img4 = bottom_blob.channel(q + 4); const float* img5 = bottom_blob.channel(q + 5); const float* img6 = bottom_blob.channel(q + 6); const float* img7 = bottom_blob.channel(q + 7); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* kernel6 = kernel + (p + 6) * inch + q; const float* kernel7 = kernel + (p + 7) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; const float* r4 = img4; const float* r5 = img5; const float* r6 = img6; const float* r7 = img7; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); float32x4_t _k6 = vld1q_f32(kernel6); float32x4_t _k7 = vld1q_f32(kernel7); float32x4_t _k0n = vld1q_f32(kernel0 + 4); float32x4_t _k1n = vld1q_f32(kernel1 + 4); float32x4_t _k2n = vld1q_f32(kernel2 + 4); float32x4_t _k3n = vld1q_f32(kernel3 + 4); float32x4_t _k4n = vld1q_f32(kernel4 + 4); float32x4_t _k5n = vld1q_f32(kernel5 + 4); float32x4_t _k6n = vld1q_f32(kernel6 + 4); float32x4_t _k7n = vld1q_f32(kernel7 + 4); #ifdef __clang__ // gcc reject over 30 oprands :( if (nn > 0) { asm volatile( "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "0: \n" "fmla v18.4s, v17.4s, %34.s[0] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v20.4s}, [%3] \n" "fmla v19.4s, v17.4s, %35.s[0] \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v21.4s}, [%4] \n" "fmla v20.4s, v17.4s, %36.s[0] \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v22.4s}, [%5] \n" "fmla v21.4s, v17.4s, %37.s[0] \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v23.4s}, [%6] \n" "fmla v22.4s, v17.4s, %38.s[0] \n" "prfm pldl1keep, [%10, #128] \n" "ld1 {v16.4s}, [%10], #16 \n" "fmla v23.4s, v17.4s, %39.s[0] \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v24.4s}, [%7] \n" "fmla v18.4s, v16.4s, %34.s[1] \n" "fmla v19.4s, v16.4s, %35.s[1] \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v25.4s}, [%8] \n" "fmla v24.4s, v17.4s, %40.s[0] \n" "fmla v25.4s, v17.4s, %41.s[0] \n" "fmla v20.4s, v16.4s, %36.s[1] \n" "fmla v21.4s, v16.4s, %37.s[1] \n" "prfm pldl1keep, [%11, #128] \n" "ld1 {v17.4s}, [%11], #16 \n" "fmla v22.4s, v16.4s, %38.s[1] \n" "fmla v23.4s, v16.4s, %39.s[1] \n" "fmla v18.4s, v17.4s, %34.s[2] \n" "fmla v19.4s, v17.4s, %35.s[2] \n" "fmla v24.4s, v16.4s, %40.s[1] \n" "fmla v25.4s, v16.4s, %41.s[1] \n" "fmla v20.4s, v17.4s, %36.s[2] \n" "fmla v21.4s, v17.4s, %37.s[2] \n" "prfm pldl1keep, [%12, #128] \n" "ld1 {v16.4s}, [%12], #16 \n" "fmla v22.4s, v17.4s, %38.s[2] \n" "fmla v23.4s, v17.4s, %39.s[2] \n" "fmla v18.4s, v16.4s, %34.s[3] \n" "fmla v19.4s, v16.4s, %35.s[3] \n" "fmla v24.4s, v17.4s, %40.s[2] \n" "fmla v25.4s, v17.4s, %41.s[2] \n" "fmla v20.4s, v16.4s, %36.s[3] \n" "fmla v21.4s, v16.4s, %37.s[3] \n" "prfm pldl1keep, [%13, #128] \n" "ld1 {v17.4s}, [%13], #16 \n" "fmla v22.4s, v16.4s, %38.s[3] \n" "fmla v23.4s, v16.4s, %39.s[3] \n" "fmla v18.4s, v17.4s, %42.s[0] \n" "fmla v19.4s, v17.4s, %43.s[0] \n" "fmla v24.4s, v16.4s, %40.s[3] \n" "fmla v25.4s, v16.4s, %41.s[3] \n" "fmla v20.4s, v17.4s, %44.s[0] \n" "fmla v21.4s, v17.4s, %45.s[0] \n" "prfm pldl1keep, [%14, #128] \n" "ld1 {v16.4s}, [%14], #16 \n" "fmla v22.4s, v17.4s, %46.s[0] \n" "fmla v23.4s, v17.4s, %47.s[0] \n" "fmla v18.4s, v16.4s, %42.s[1] \n" "fmla v19.4s, v16.4s, %43.s[1] \n" "fmla v24.4s, v17.4s, %48.s[0] \n" "fmla v25.4s, v17.4s, %49.s[0] \n" "fmla v20.4s, v16.4s, %44.s[1] \n" "fmla v21.4s, v16.4s, %45.s[1] \n" "prfm pldl1keep, [%15, #128] \n" "ld1 {v17.4s}, [%15], #16 \n" "fmla v22.4s, v16.4s, %46.s[1] \n" "fmla v23.4s, v16.4s, %47.s[1] \n" "fmla v18.4s, v17.4s, %42.s[2] \n" "fmla v19.4s, v17.4s, %43.s[2] \n" "fmla v24.4s, v16.4s, %48.s[1] \n" "fmla v25.4s, v16.4s, %49.s[1] \n" "fmla v20.4s, v17.4s, %44.s[2] \n" "fmla v21.4s, v17.4s, %45.s[2] \n" "prfm pldl1keep, [%16, #128] \n" "ld1 {v16.4s}, [%16], #16 \n" "fmla v22.4s, v17.4s, %46.s[2] \n" "fmla v23.4s, v17.4s, %47.s[2] \n" "fmla v18.4s, v16.4s, %42.s[3] \n" "fmla v19.4s, v16.4s, %43.s[3] \n" "fmla v24.4s, v17.4s, %48.s[2] \n" "fmla v25.4s, v17.4s, %49.s[2] \n" "fmla v20.4s, v16.4s, %44.s[3] \n" "fmla v21.4s, v16.4s, %45.s[3] \n" "st1 {v18.4s}, [%1], #16 \n" "fmla v22.4s, v16.4s, %46.s[3] \n" "st1 {v19.4s}, [%2], #16 \n" "fmla v23.4s, v16.4s, %47.s[3] \n" "st1 {v20.4s}, [%3], #16 \n" "prfm pldl1keep, [%9, #128] \n" "ld1 {v17.4s}, [%9], #16 \n" "fmla v24.4s, v16.4s, %48.s[3] \n" "st1 {v21.4s}, [%4], #16 \n" "fmla v25.4s, v16.4s, %49.s[3] \n" "st1 {v22.4s}, [%5], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "st1 {v23.4s}, [%6], #16 \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "st1 {v24.4s}, [%7], #16 \n" "subs %w0, %w0, #1 \n" "st1 {v25.4s}, [%8], #16 \n" "bne 0b \n" "sub %9, %9, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(outptr6), // %7 "=r"(outptr7), // %8 "=r"(r0), // %9 "=r"(r1), // %10 "=r"(r2), // %11 "=r"(r3), // %12 "=r"(r4), // %13 "=r"(r5), // %14 "=r"(r6), // %15 "=r"(r7) // %16 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(outptr6), "8"(outptr7), "9"(r0), "10"(r1), "11"(r2), "12"(r3), "13"(r4), "14"(r5), "15"(r6), "16"(r7), "w"(_k0), // %34 "w"(_k1), // %35 "w"(_k2), // %36 "w"(_k3), // %37 "w"(_k4), // %38 "w"(_k5), // %39 "w"(_k6), // %40 "w"(_k7), // %41 "w"(_k0n), // %42 "w"(_k1n), // %43 "w"(_k2n), // %44 "w"(_k3n), // %45 "w"(_k4n), // %46 "w"(_k5n), // %47 "w"(_k6n), // %48 "w"(_k7n) // %49 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25" //, "v26", "v27", "v28", "v29", "v30", "v31" ); } #else for (; nn > 0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_laneq_f32(_out0p, _p, _k0, 0); _out1p = vfmaq_laneq_f32(_out1p, _p, _k1, 0); _out2p = vfmaq_laneq_f32(_out2p, _p, _k2, 0); _out3p = vfmaq_laneq_f32(_out3p, _p, _k3, 0); _out4p = vfmaq_laneq_f32(_out4p, _p, _k4, 0); _out5p = vfmaq_laneq_f32(_out5p, _p, _k5, 0); _out6p = vfmaq_laneq_f32(_out6p, _p, _k6, 0); _out7p = vfmaq_laneq_f32(_out7p, _p, _k7, 0); float32x4_t _p1 = vld1q_f32(r1); _out0p = vfmaq_laneq_f32(_out0p, _p1, _k0, 1); _out1p = vfmaq_laneq_f32(_out1p, _p1, _k1, 1); _out2p = vfmaq_laneq_f32(_out2p, _p1, _k2, 1); _out3p = vfmaq_laneq_f32(_out3p, _p1, _k3, 1); _out4p = vfmaq_laneq_f32(_out4p, _p1, _k4, 1); _out5p = vfmaq_laneq_f32(_out5p, _p1, _k5, 1); _out6p = vfmaq_laneq_f32(_out6p, _p1, _k6, 1); _out7p = vfmaq_laneq_f32(_out7p, _p1, _k7, 1); float32x4_t _p2 = vld1q_f32(r2); _out0p = vfmaq_laneq_f32(_out0p, _p2, _k0, 2); _out1p = vfmaq_laneq_f32(_out1p, _p2, _k1, 2); _out2p = vfmaq_laneq_f32(_out2p, _p2, _k2, 2); _out3p = vfmaq_laneq_f32(_out3p, _p2, _k3, 2); _out4p = vfmaq_laneq_f32(_out4p, _p2, _k4, 2); _out5p = vfmaq_laneq_f32(_out5p, _p2, _k5, 2); _out6p = vfmaq_laneq_f32(_out6p, _p2, _k6, 2); _out7p = vfmaq_laneq_f32(_out7p, _p2, _k7, 2); float32x4_t _p3 = vld1q_f32(r3); _out0p = vfmaq_laneq_f32(_out0p, _p3, _k0, 3); _out1p = vfmaq_laneq_f32(_out1p, _p3, _k1, 3); _out2p = vfmaq_laneq_f32(_out2p, _p3, _k2, 3); _out3p = vfmaq_laneq_f32(_out3p, _p3, _k3, 3); _out4p = vfmaq_laneq_f32(_out4p, _p3, _k4, 3); _out5p = vfmaq_laneq_f32(_out5p, _p3, _k5, 3); _out6p = vfmaq_laneq_f32(_out6p, _p3, _k6, 3); _out7p = vfmaq_laneq_f32(_out7p, _p3, _k7, 3); float32x4_t _p4 = vld1q_f32(r4); _out0p = vfmaq_laneq_f32(_out0p, _p4, _k0n, 0); _out1p = vfmaq_laneq_f32(_out1p, _p4, _k1n, 0); _out2p = vfmaq_laneq_f32(_out2p, _p4, _k2n, 0); _out3p = vfmaq_laneq_f32(_out3p, _p4, _k3n, 0); _out4p = vfmaq_laneq_f32(_out4p, _p4, _k4n, 0); _out5p = vfmaq_laneq_f32(_out5p, _p4, _k5n, 0); _out6p = vfmaq_laneq_f32(_out6p, _p4, _k6n, 0); _out7p = vfmaq_laneq_f32(_out7p, _p4, _k7n, 0); float32x4_t _p5 = vld1q_f32(r5); _out0p = vfmaq_laneq_f32(_out0p, _p5, _k0n, 1); _out1p = vfmaq_laneq_f32(_out1p, _p5, _k1n, 1); _out2p = vfmaq_laneq_f32(_out2p, _p5, _k2n, 1); _out3p = vfmaq_laneq_f32(_out3p, _p5, _k3n, 1); _out4p = vfmaq_laneq_f32(_out4p, _p5, _k4n, 1); _out5p = vfmaq_laneq_f32(_out5p, _p5, _k5n, 1); _out6p = vfmaq_laneq_f32(_out6p, _p5, _k6n, 1); _out7p = vfmaq_laneq_f32(_out7p, _p5, _k7n, 1); float32x4_t _p6 = vld1q_f32(r6); _out0p = vfmaq_laneq_f32(_out0p, _p6, _k0n, 2); _out1p = vfmaq_laneq_f32(_out1p, _p6, _k1n, 2); _out2p = vfmaq_laneq_f32(_out2p, _p6, _k2n, 2); _out3p = vfmaq_laneq_f32(_out3p, _p6, _k3n, 2); _out4p = vfmaq_laneq_f32(_out4p, _p6, _k4n, 2); _out5p = vfmaq_laneq_f32(_out5p, _p6, _k5n, 2); _out6p = vfmaq_laneq_f32(_out6p, _p6, _k6n, 2); _out7p = vfmaq_laneq_f32(_out7p, _p6, _k7n, 2); float32x4_t _p7 = vld1q_f32(r7); _out0p = vfmaq_laneq_f32(_out0p, _p7, _k0n, 3); _out1p = vfmaq_laneq_f32(_out1p, _p7, _k1n, 3); _out2p = vfmaq_laneq_f32(_out2p, _p7, _k2n, 3); _out3p = vfmaq_laneq_f32(_out3p, _p7, _k3n, 3); _out4p = vfmaq_laneq_f32(_out4p, _p7, _k4n, 3); _out5p = vfmaq_laneq_f32(_out5p, _p7, _k5n, 3); _out6p = vfmaq_laneq_f32(_out6p, _p7, _k6n, 3); _out7p = vfmaq_laneq_f32(_out7p, _p7, _k7n, 3); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; r5 += 4; r6 += 4; r7 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } #endif for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3] + *r4 * kernel0[4] + *r5 * kernel0[5] + *r6 * kernel0[6] + *r7 * kernel0[7]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3] + *r4 * kernel1[4] + *r5 * kernel1[5] + *r6 * kernel1[6] + *r7 * kernel1[7]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3] + *r4 * kernel2[4] + *r5 * kernel2[5] + *r6 * kernel2[6] + *r7 * kernel2[7]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3] + *r4 * kernel3[4] + *r5 * kernel3[5] + *r6 * kernel3[6] + *r7 * kernel3[7]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3] + *r4 * kernel4[4] + *r5 * kernel4[5] + *r6 * kernel4[6] + *r7 * kernel4[7]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3] + *r4 * kernel5[4] + *r5 * kernel5[5] + *r6 * kernel5[6] + *r7 * kernel5[7]; float sum6 = *r0 * kernel6[0] + *r1 * kernel6[1] + *r2 * kernel6[2] + *r3 * kernel6[3] + *r4 * kernel6[4] + *r5 * kernel6[5] + *r6 * kernel6[6] + *r7 * kernel6[7]; float sum7 = *r0 * kernel7[0] + *r1 * kernel7[1] + *r2 * kernel7[2] + *r3 * kernel7[3] + *r4 * kernel7[4] + *r5 * kernel7[5] + *r6 * kernel7[6] + *r7 * kernel7[7]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; r1++; r2++; r3++; r4++; r5++; r6++; r7++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; float* outptr6 = out6; float* outptr7 = out7; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* kernel6 = kernel + (p + 6) * inch + q; const float* kernel7 = kernel + (p + 7) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float k6 = kernel6[0]; const float k7 = kernel7[0]; const float* r0 = img0; int size = outw * outh; int nn = size >> 2; int remain = size & 3; float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); float32x4_t _k6 = vdupq_n_f32(k6); float32x4_t _k7 = vdupq_n_f32(k7); for (; nn > 0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _out0p = vld1q_f32(outptr0); float32x4_t _out1p = vld1q_f32(outptr1); float32x4_t _out2p = vld1q_f32(outptr2); float32x4_t _out3p = vld1q_f32(outptr3); float32x4_t _out4p = vld1q_f32(outptr4); float32x4_t _out5p = vld1q_f32(outptr5); float32x4_t _out6p = vld1q_f32(outptr6); float32x4_t _out7p = vld1q_f32(outptr7); _out0p = vfmaq_f32(_out0p, _p, _k0); _out1p = vfmaq_f32(_out1p, _p, _k1); _out2p = vfmaq_f32(_out2p, _p, _k2); _out3p = vfmaq_f32(_out3p, _p, _k3); _out4p = vfmaq_f32(_out4p, _p, _k4); _out5p = vfmaq_f32(_out5p, _p, _k5); _out6p = vfmaq_f32(_out6p, _p, _k6); _out7p = vfmaq_f32(_out7p, _p, _k7); vst1q_f32(outptr0, _out0p); vst1q_f32(outptr1, _out1p); vst1q_f32(outptr2, _out2p); vst1q_f32(outptr3, _out3p); vst1q_f32(outptr4, _out4p); vst1q_f32(outptr5, _out5p); vst1q_f32(outptr6, _out6p); vst1q_f32(outptr7, _out7p); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; outptr4 += 4; outptr5 += 4; outptr6 += 4; outptr7 += 4; } for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; float sum6 = *r0 * k6; float sum7 = *r0 * k7; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; *outptr6 += sum6; *outptr7 += sum7; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; outptr6++; outptr7++; } } } #else nn_outch = outch / 6; remain_outch_start = nn_outch * 6; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 6; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); Mat out4 = top_blob.channel(p + 4); Mat out5 = top_blob.channel(p + 5); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; const float bias4 = bias ? bias[p + 4] : 0.f; const float bias5 = bias ? bias[p + 5] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); out4.fill(bias4); out5.fill(bias5); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); float32x4_t _k4 = vld1q_f32(kernel4); float32x4_t _k5 = vld1q_f32(kernel5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "vmla.f32 q6, q12, %e22[0] \n" "0: \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n" // q8 = outptr2 "vmla.f32 q7, q12, %e23[0] \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n" // q9 = outptr3 "vmla.f32 q8, q12, %e24[0] \n" "pld [%8, #128] \n" "vld1.f32 {d26-d27}, [%8 :128]! \n" // q13 = r1 "vmla.f32 q9, q12, %e25[0] \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n" // q10 = outptr4 "vmla.f32 q6, q13, %e22[1] \n" "vmla.f32 q7, q13, %e23[1] \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n" // q11 = outptr5 "vmla.f32 q10, q12, %e26[0] \n" "vmla.f32 q11, q12, %e27[0] \n" "vmla.f32 q8, q13, %e24[1] \n" "vmla.f32 q9, q13, %e25[1] \n" "pld [%9, #128] \n" "vld1.f32 {d28-d29}, [%9 :128]! \n" // q14 = r2 "vmla.f32 q10, q13, %e26[1] \n" "vmla.f32 q11, q13, %e27[1] \n" "vmla.f32 q6, q14, %f22[0] \n" "vmla.f32 q7, q14, %f23[0] \n" "vmla.f32 q8, q14, %f24[0] \n" "vmla.f32 q9, q14, %f25[0] \n" "pld [%10, #128] \n" "vld1.f32 {d30-d31}, [%10 :128]! \n" // q15 = r3 "vmla.f32 q10, q14, %f26[0] \n" "vmla.f32 q11, q14, %f27[0] \n" "vmla.f32 q6, q15, %f22[1] \n" "vmla.f32 q7, q15, %f23[1] \n" "vmla.f32 q8, q15, %f24[1] \n" "vmla.f32 q9, q15, %f25[1] \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "vmla.f32 q10, q15, %f26[1] \n" "vmla.f32 q11, q15, %f27[1] \n" "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "vmla.f32 q6, q12, %e22[0] \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(r0), // %7 "=r"(r1), // %8 "=r"(r2), // %9 "=r"(r3) // %10 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "8"(r1), "9"(r2), "10"(r3), "w"(_k0), // %22 "w"(_k1), // %23 "w"(_k2), // %24 "w"(_k3), // %25 "w"(_k4), // %26 "w"(_k5) // %27 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; float sum4 = *r0 * kernel4[0] + *r1 * kernel4[1] + *r2 * kernel4[2] + *r3 * kernel4[3]; float sum5 = *r0 * kernel5[0] + *r1 * kernel5[1] + *r2 * kernel5[2] + *r3 * kernel5[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; float* outptr4 = out4; float* outptr5 = out5; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* kernel4 = kernel + (p + 4) * inch + q; const float* kernel5 = kernel + (p + 5) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float k4 = kernel4[0]; const float k5 = kernel5[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 2; int remain = size & 3; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); float32x4_t _k4 = vdupq_n_f32(k4); float32x4_t _k5 = vdupq_n_f32(k5); if (nn > 0) { asm volatile( "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "0: \n" "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :128] \n" // q7 = outptr1 "vmla.f32 q6, q12, %q16 \n" "pld [%3, #128] \n" "vld1.f32 {d16-d17}, [%3 :128] \n" // q8 = outptr2 "vmla.f32 q7, q12, %q17 \n" "pld [%4, #128] \n" "vld1.f32 {d18-d19}, [%4 :128] \n" // q9 = outptr3 "vmla.f32 q8, q12, %q18 \n" "pld [%5, #128] \n" "vld1.f32 {d20-d21}, [%5 :128] \n" // q10 = outptr4 "vmla.f32 q9, q12, %q19 \n" "pld [%6, #128] \n" "vld1.f32 {d22-d23}, [%6 :128] \n" // q11 = outptr5 "vmla.f32 q10, q12, %q20 \n" "vmla.f32 q11, q12, %q21 \n" "pld [%7, #128] \n" "vld1.f32 {d24-d25}, [%7 :128]! \n" // q12 = r0 "vst1.f32 {d12-d13}, [%1 :128]! \n" "vst1.f32 {d14-d15}, [%2 :128]! \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :128] \n" // q6 = outptr0 "vst1.f32 {d16-d17}, [%3 :128]! \n" "vst1.f32 {d18-d19}, [%4 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%5 :128]! \n" "vst1.f32 {d22-d23}, [%6 :128]! \n" "bne 0b \n" "sub %7, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(outptr4), // %5 "=r"(outptr5), // %6 "=r"(r0) // %7 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(outptr4), "6"(outptr5), "7"(r0), "w"(_k0), // %16 "w"(_k1), // %17 "w"(_k2), // %18 "w"(_k3), // %19 "w"(_k4), // %20 "w"(_k5) // %21 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12"); } #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; float sum4 = *r0 * k4; float sum5 = *r0 * k5; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; *outptr4 += sum4; *outptr5 += sum5; r0++; outptr0++; outptr1++; outptr2++; outptr3++; outptr4++; outptr5++; } } } #endif // __ARM_NEON && __aarch64__ nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "0: \n" "fmla v8.4s, v6.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v9.4s, v7.4s, %18.s[0] \n" "fmla v10.4s, v6.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v11.4s, v7.4s, %19.s[0] \n" "fmla v12.4s, v6.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v13.4s, v7.4s, %20.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "ld1 {v4.4s, v5.4s}, [%6], #32 \n" "fmla v14.4s, v6.4s, %21.s[0] \n" "fmla v15.4s, v7.4s, %21.s[0] \n" "fmla v8.4s, v4.4s, %18.s[1] \n" "fmla v9.4s, v5.4s, %18.s[1] \n" "fmla v10.4s, v4.4s, %19.s[1] \n" "fmla v11.4s, v5.4s, %19.s[1] \n" "fmla v12.4s, v4.4s, %20.s[1] \n" "fmla v13.4s, v5.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "ld1 {v6.4s, v7.4s}, [%7], #32 \n" "fmla v14.4s, v4.4s, %21.s[1] \n" "fmla v15.4s, v5.4s, %21.s[1] \n" "fmla v8.4s, v6.4s, %18.s[2] \n" "fmla v9.4s, v7.4s, %18.s[2] \n" "fmla v10.4s, v6.4s, %19.s[2] \n" "fmla v11.4s, v7.4s, %19.s[2] \n" "fmla v12.4s, v6.4s, %20.s[2] \n" "fmla v13.4s, v7.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {v4.4s, v5.4s}, [%8], #32 \n" "fmla v14.4s, v6.4s, %21.s[2] \n" "fmla v15.4s, v7.4s, %21.s[2] \n" "fmla v8.4s, v4.4s, %18.s[3] \n" "fmla v9.4s, v5.4s, %18.s[3] \n" "fmla v10.4s, v4.4s, %19.s[3] \n" "fmla v11.4s, v5.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %20.s[3] \n" "fmla v13.4s, v5.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "fmla v14.4s, v4.4s, %21.s[3] \n" "fmla v15.4s, v5.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "0: \n" "vmla.f32 q8, q6, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q9, q7, %e18[0] \n" "vmla.f32 q10, q6, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q11, q7, %e19[0] \n" "vmla.f32 q12, q6, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q13, q7, %e20[0] \n" "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]! \n" "vmla.f32 q14, q6, %e21[0] \n" "vmla.f32 q15, q7, %e21[0] \n" "vmla.f32 q8, q4, %e18[1] \n" "vmla.f32 q9, q5, %e18[1] \n" "vmla.f32 q10, q4, %e19[1] \n" "vmla.f32 q11, q5, %e19[1] \n" "vmla.f32 q12, q4, %e20[1] \n" "vmla.f32 q13, q5, %e20[1] \n" "pld [%7, #256] \n" "vld1.f32 {d12-d15}, [%7 :128]! \n" "vmla.f32 q14, q4, %e21[1] \n" "vmla.f32 q15, q5, %e21[1] \n" "vmla.f32 q8, q6, %f18[0] \n" "vmla.f32 q9, q7, %f18[0] \n" "vmla.f32 q10, q6, %f19[0] \n" "vmla.f32 q11, q7, %f19[0] \n" "vmla.f32 q12, q6, %f20[0] \n" "vmla.f32 q13, q7, %f20[0] \n" "pld [%8, #256] \n" "vld1.f32 {d8-d11}, [%8 :128]! \n" "vmla.f32 q14, q6, %f21[0] \n" "vmla.f32 q15, q7, %f21[0] \n" "vmla.f32 q8, q4, %f18[1] \n" "vmla.f32 q9, q5, %f18[1] \n" "vmla.f32 q10, q4, %f19[1] \n" "vmla.f32 q11, q5, %f19[1] \n" "vmla.f32 q12, q4, %f20[1] \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "vmla.f32 q13, q5, %f20[1] \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "vmla.f32 q14, q4, %f21[1] \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "vmla.f32 q15, q5, %f21[1] \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr2++; outptr3++; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v6.4s, %12.4s \n" "fmla v9.4s, v7.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v6.4s, %13.4s \n" "fmla v11.4s, v7.4s, %13.4s \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v6.4s, %14.4s \n" "fmla v13.4s, v7.4s, %14.4s \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "fmla v14.4s, v6.4s, %15.4s \n" "fmla v15.4s, v7.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v6.4s, v7.4s}, [%5], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" "sub %5, %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n" "vmla.f32 q8, q6, %q12 \n" "vmla.f32 q9, q7, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n" "vmla.f32 q10, q6, %q13 \n" "vmla.f32 q11, q7, %q13 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128] \n" "vmla.f32 q12, q6, %q14 \n" "vmla.f32 q13, q7, %q14 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128] \n" "vmla.f32 q14, q6, %q15 \n" "vmla.f32 q15, q7, %q15 \n" "vst1.f32 {d24-d27}, [%3 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d12-d15}, [%5 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4 :128]! \n" "bne 0b \n" "sub %5, #32 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v3.4s, %12.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v3.4s, %13.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v3.4s, %14.4s \n" "prfm pldl1keep, [%5, #256] \n" "ld1 {v2.4s, v3.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v3.4s, %15.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v3.4s, %6.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v2.4s, v3.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3"); } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 4; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p + 1); Mat out2 = top_blob.channel(p + 2); Mat out3 = top_blob.channel(p + 3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p + 1] : 0.f; const float bias2 = bias ? bias[p + 2] : 0.f; const float bias3 = bias ? bias[p + 3] : 0.f; out0.fill(bias0); out1.fill(bias1); out2.fill(bias2); out3.fill(bias3); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vld1q_f32(kernel0); float32x4_t _k1 = vld1q_f32(kernel1); float32x4_t _k2 = vld1q_f32(kernel2); float32x4_t _k3 = vld1q_f32(kernel3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n" // v4 v5 "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %18.s[0] \n" "fmla v9.4s, v5.4s, %18.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %19.s[0] \n" "fmla v11.4s, v5.4s, %19.s[0] \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "fmla v12.4s, v4.4s, %20.s[0] \n" "fmla v13.4s, v5.4s, %20.s[0] \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "prfm pldl1keep, [%6, #512] \n" "ld2 {v6.4s, v7.4s}, [%6], #32 \n" "fmla v14.4s, v4.4s, %21.s[0] \n" "fmla v15.4s, v5.4s, %21.s[0] \n" "ld2 {v4.4s, v5.4s}, [%6], #32 \n" "and v7.16b, v4.16b, v4.16b \n" // v6 v7 "fmla v8.4s, v6.4s, %18.s[1] \n" "fmla v9.4s, v7.4s, %18.s[1] \n" "fmla v10.4s, v6.4s, %19.s[1] \n" "fmla v11.4s, v7.4s, %19.s[1] \n" "fmla v12.4s, v6.4s, %20.s[1] \n" "fmla v13.4s, v7.4s, %20.s[1] \n" "prfm pldl1keep, [%7, #512] \n" "ld2 {v4.4s, v5.4s}, [%7], #32 \n" "fmla v14.4s, v6.4s, %21.s[1] \n" "fmla v15.4s, v7.4s, %21.s[1] \n" "ld2 {v6.4s, v7.4s}, [%7], #32 \n" "and v5.16b, v6.16b, v6.16b \n" // v4 v5 "fmla v8.4s, v4.4s, %18.s[2] \n" "fmla v9.4s, v5.4s, %18.s[2] \n" "fmla v10.4s, v4.4s, %19.s[2] \n" "fmla v11.4s, v5.4s, %19.s[2] \n" "fmla v12.4s, v4.4s, %20.s[2] \n" "fmla v13.4s, v5.4s, %20.s[2] \n" "prfm pldl1keep, [%8, #512] \n" "ld2 {v6.4s, v7.4s}, [%8], #32 \n" "fmla v14.4s, v4.4s, %21.s[2] \n" "fmla v15.4s, v5.4s, %21.s[2] \n" "ld2 {v4.4s, v5.4s}, [%8], #32 \n" "and v7.16b, v4.16b, v4.16b \n" // v6 v7 "fmla v8.4s, v6.4s, %18.s[3] \n" "fmla v9.4s, v7.4s, %18.s[3] \n" "fmla v10.4s, v6.4s, %19.s[3] \n" "fmla v11.4s, v7.4s, %19.s[3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v6.4s, %20.s[3] \n" "fmla v13.4s, v7.4s, %20.s[3] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v6.4s, %21.s[3] \n" "fmla v15.4s, v7.4s, %21.s[3] \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n" // q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %e18[0] \n" "vmla.f32 q9, q5, %e18[0] \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %e19[0] \n" "vmla.f32 q11, q5, %e19[0] \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vmla.f32 q12, q4, %e20[0] \n" "vmla.f32 q13, q5, %e20[0] \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "pld [%6, #512] \n" "vld2.f32 {d12-d15}, [%6]! \n" "vmla.f32 q14, q4, %e21[0] \n" "vmla.f32 q15, q5, %e21[0] \n" "vld2.f32 {d8-d11}, [%6]! \n" "vand q7, q4, q4 \n" // q6 q7 "vmla.f32 q8, q6, %e18[1] \n" "vmla.f32 q9, q7, %e18[1] \n" "vmla.f32 q10, q6, %e19[1] \n" "vmla.f32 q11, q7, %e19[1] \n" "vmla.f32 q12, q6, %e20[1] \n" "vmla.f32 q13, q7, %e20[1] \n" "pld [%7, #512] \n" "vld2.f32 {d8-d11}, [%7]! \n" "vmla.f32 q14, q6, %e21[1] \n" "vmla.f32 q15, q7, %e21[1] \n" "vld2.f32 {d12-d15}, [%7]! \n" "vand q5, q6, q6 \n" // q4 q5 "vmla.f32 q8, q4, %f18[0] \n" "vmla.f32 q9, q5, %f18[0] \n" "vmla.f32 q10, q4, %f19[0] \n" "vmla.f32 q11, q5, %f19[0] \n" "vmla.f32 q12, q4, %f20[0] \n" "vmla.f32 q13, q5, %f20[0] \n" "pld [%8, #512] \n" "vld2.f32 {d12-d15}, [%8]! \n" "vmla.f32 q14, q4, %f21[0] \n" "vmla.f32 q15, q5, %f21[0] \n" "vld2.f32 {d8-d11}, [%8]! \n" "vand q7, q4, q4 \n" // q6 q7 "vmla.f32 q8, q6, %f18[1] \n" "vmla.f32 q9, q7, %f18[1] \n" "vmla.f32 q10, q6, %f19[1] \n" "vmla.f32 q11, q7, %f19[1] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q6, %f20[1] \n" "vmla.f32 q13, q7, %f20[1] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q6, %f21[1] \n" "vmla.f32 q15, q7, %f21[1] \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k0), // %18 "w"(_k1), // %19 "w"(_k2), // %20 "w"(_k3) // %21 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * kernel0[0] + *r1 * kernel0[1] + *r2 * kernel0[2] + *r3 * kernel0[3]; float sum1 = *r0 * kernel1[0] + *r1 * kernel1[1] + *r2 * kernel1[2] + *r3 * kernel1[3]; float sum2 = *r0 * kernel2[0] + *r1 * kernel2[1] + *r2 * kernel2[2] + *r3 * kernel2[3]; float sum3 = *r0 * kernel3[0] + *r1 * kernel3[1] + *r2 * kernel3[2] + *r3 * kernel3[3]; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q < inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr2 = out2; float* outptr3 = out3; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float* kernel1 = kernel + (p + 1) * inch + q; const float* kernel2 = kernel + (p + 2) * inch + q; const float* kernel3 = kernel + (p + 3) * inch + q; const float k0 = kernel0[0]; const float k1 = kernel1[0]; const float k2 = kernel2[0]; const float k3 = kernel3[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { int size = outw; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v4.4s, v5.4s}, [%5], #32 \n" "ld2 {v6.4s, v7.4s}, [%5], #32 \n" "and v5.16b, v6.16b, v6.16b \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v8.4s, v9.4s}, [%1] \n" "fmla v8.4s, v4.4s, %12.4s \n" "fmla v9.4s, v5.4s, %12.4s \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v10.4s, v11.4s}, [%2] \n" "fmla v10.4s, v4.4s, %13.4s \n" "fmla v11.4s, v5.4s, %13.4s \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v12.4s, v13.4s}, [%3] \n" "st1 {v8.4s, v9.4s}, [%1], #32 \n" "fmla v12.4s, v4.4s, %14.4s \n" "fmla v13.4s, v5.4s, %14.4s \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {v14.4s, v15.4s}, [%4] \n" "st1 {v10.4s, v11.4s}, [%2], #32 \n" "fmla v14.4s, v4.4s, %15.4s \n" "fmla v15.4s, v5.4s, %15.4s \n" "st1 {v12.4s, v13.4s}, [%3], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v14.4s, v15.4s}, [%4], #32 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15"); } #else if (nn > 0) { asm volatile( "0: \n" "pld [%5, #512] \n" "vld2.f32 {d8-d11}, [%5]! \n" "vld2.f32 {d12-d15}, [%5]! \n" "vand q5, q6, q6 \n" // q4 q5 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1] \n" "vmla.f32 q8, q4, %q12 \n" "vmla.f32 q9, q5, %q12 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2] \n" "vmla.f32 q10, q4, %q13 \n" "vmla.f32 q11, q5, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3] \n" "vst1.f32 {d16-d19}, [%1]! \n" "vmla.f32 q12, q4, %q14 \n" "vmla.f32 q13, q5, %q14 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4] \n" "vst1.f32 {d20-d23}, [%2]! \n" "vmla.f32 q14, q4, %q15 \n" "vmla.f32 q15, q5, %q15 \n" "vst1.f32 {d24-d27}, [%3]! \n" "subs %0, #1 \n" "vst1.f32 {d28-d31}, [%4]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr2), // %3 "=r"(outptr3), // %4 "=r"(r0) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr2), "4"(outptr3), "5"(r0), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO neon optimize float sum0 = *r0 * k0; float sum1 = *r0 * k1; float sum2 = *r0 * k2; float sum3 = *r0 * k3; *outptr0 += sum0; *outptr1 += sum1; *outptr2 += sum2; *outptr3 += sum3; r0 += 2; outptr0++; outptr1++; outptr2++; outptr3++; } r0 += tailstep; } } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q + 3 < inch; q += 4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q + 1); const float* img2 = bottom_blob.channel(q + 2); const float* img3 = bottom_blob.channel(q + 3); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %12.4s \n" "fmla v1.4s, v8.4s, %12.4s \n" "prfm pldl1keep, [%3, #512] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %13.4s \n" "fmla v1.4s, v8.4s, %13.4s \n" "prfm pldl1keep, [%4, #512] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %14.4s \n" "fmla v1.4s, v8.4s, %14.4s \n" "prfm pldl1keep, [%5, #512] \n" "ld2 {v2.4s, v3.4s}, [%5], #32 \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" "fmla v0.4s, v2.4s, %15.4s \n" "fmla v1.4s, v8.4s, %15.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9"); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q < inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #256] \n" "ld1 {v0.4s, v1.4s}, [%1] \n" "fmla v0.4s, v2.4s, %6.4s \n" "fmla v1.4s, v8.4s, %6.4s \n" "prfm pldl1keep, [%2, #512] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" "bne 0b \n" "sub %2, %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9"); } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } }
swapit.h
#ifndef _SWAPIT_H_ #define _SWAPIT_H_ #include <sys/types.h> // u_int32_t, etc #include <unistd.h> // read() #include <stdexcept> // std::runtime_error #include <cstring> // memcpy() #include <vector> #include <cassert> namespace p_bin { // NO NUMTHREADS!!! inline void swap16(void* buf, ssize_t numWords){ const u_int16_t lobyte=(u_int16_t)0x00ff; const u_int16_t hibyte=(u_int16_t)0xff00; const u_int16_t bitsperbyte=(u_int16_t)8; register ssize_t i; register u_int16_t* src = reinterpret_cast<u_int16_t*>(buf); #pragma omp parallel for for(i = 0 ; i < numWords ; ++i ){ src[i] = (u_int16_t) ((u_int16_t)((src[i] & lobyte)<<bitsperbyte) | (u_int16_t)((src[i] & hibyte)>>bitsperbyte)); } } // NO NUMTHREADS!!! inline void swap32(void* buf, ssize_t numWords){ register ssize_t i; register u_int32_t* src = reinterpret_cast<u_int32_t*>(buf); #pragma omp parallel for for(i = 0 ; i < numWords ; ++i ){ src[i] = ((src[i] & 0x000000ff) << 24) | ((src[i] & 0x0000ff00) << 8) | ((src[i] & 0x00ff0000) >> 8) | ((src[i] & 0xff000000) >> 24); } } inline void swap(std::vector<u_int32_t>& buf){ swap32(&buf[0],buf.size()); } inline void swap(std::vector<int32_t>& buf){ swap32((u_int32_t*)&buf[0],buf.size()); } inline void swap(std::vector<float>& buf){ swap32((u_int32_t*)&buf[0],buf.size()); } // NO NUMTHREADS!!! inline void swap64(void* buf, ssize_t numWords){ register ssize_t i; register u_int64_t* src = reinterpret_cast<u_int64_t*>(buf); #pragma omp parallel for for(i = 0 ; i < numWords ; ++i ){ src[i] = ((u_int64_t)((u_int64_t)src[i] & 0x00000000000000ffULL)<<56ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x000000000000ff00ULL)<<40ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x0000000000ff0000ULL)<<24ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x00000000ff000000ULL)<< 8ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x000000ff00000000ULL)>> 8ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x0000ff0000000000ULL)>>24ULL | \ (u_int64_t)((u_int64_t)src[i] & 0x00ff000000000000ULL)>>40ULL | \ (u_int64_t)((u_int64_t)src[i] & 0xff00000000000000ULL)>>56ULL ); } } inline void swap(std::vector<u_int64_t>& buf){ swap64((u_int64_t*)&buf[0],buf.size()); } inline void swap(std::vector<int64_t>& buf){ swap64((u_int64_t*)&buf[0],buf.size()); } inline void swap(std::vector<double>& buf){ swap64((u_int64_t*)&buf[0],buf.size()); } inline double swap(double val){ u_int64_t bits; memcpy(&bits,&val,sizeof(double)); p_bin::swap64(&bits,1); memcpy(&val,&bits,sizeof(double)); return val; } inline float swap(float val){ u_int32_t bits; memcpy(&bits,&val,sizeof(float)); p_bin::swap32(&bits,1); memcpy(&val,&bits,sizeof(float)); return val; } inline u_int64_t swap(u_int64_t val){ u_int64_t bits; memcpy(&bits,&val,sizeof(u_int64_t)); p_bin::swap64(&bits,1); memcpy(&val,&bits,sizeof(u_int64_t)); return val; } inline u_int64_t swap(int64_t val){ u_int64_t bits; memcpy(&bits,&val,sizeof(u_int64_t)); p_bin::swap64(&bits,1); memcpy(&val,&bits,sizeof(u_int64_t)); return val; } inline u_int32_t swap(u_int32_t val){ u_int32_t bits; memcpy(&bits,&val,sizeof(u_int32_t)); p_bin::swap32(&bits,1); memcpy(&val,&bits,sizeof(u_int32_t)); return val; } inline u_int32_t swap(int32_t val){ u_int32_t bits; memcpy(&bits,&val,sizeof(u_int32_t)); p_bin::swap32(&bits,1); memcpy(&val,&bits,sizeof(u_int32_t)); return val; } inline u_int16_t swap(u_int16_t val){ u_int16_t bits; memcpy(&bits,&val,sizeof(u_int16_t)); p_bin::swap16(&bits,1); memcpy(&val,&bits,sizeof(u_int16_t)); return val; } inline u_int16_t swap(int16_t val){ u_int16_t bits; memcpy(&bits,&val,sizeof(u_int16_t)); p_bin::swap16(&bits,1); memcpy(&val,&bits,sizeof(u_int16_t)); return val; } inline u_int32_t getbareword(int fin, bool swap=false) { u_int32_t word; ssize_t res=read(fin,&word,sizeof(u_int32_t)); if( res<=0 ) throw std::logic_error("getbareword() failed"); if( swap ) p_bin::swap32(&word, 1); return word; } inline u_int32_t getrecord(int fin, bool swap=false) { return getbareword(fin,swap); } inline u_int32_t getword(int fin, bool swap=false) { u_int32_t recbgn=getrecord(fin,swap); size_t words=recbgn/sizeof(u_int32_t); if( words != 1 ) throw std::runtime_error("getword(): [rec>4] => larger than one word to read"); u_int32_t res = getbareword(fin,swap); u_int32_t recend=getrecord(fin,swap); if( recbgn != recend ) throw std::runtime_error("getword(): rec bgn/end mismatch"); return res; } template <typename T> inline void getbare(int fin, T* buf, size_t bytes, bool swap=false) { const size_t MAXBYTE=2147483648L; size_t bytesRead=0,bytesLeft=bytes; unsigned char* dst=reinterpret_cast<unsigned char*>(buf); while( bytesLeft ){ size_t req = bytesLeft>MAXBYTE ? MAXBYTE : bytesLeft; ssize_t res = read(fin,&dst[bytesRead],req); if( res <= 0) throw std::runtime_error("getbare() failed"); bytesLeft -= res; bytesRead += res; } if( swap ) { size_t N=bytes/sizeof(T); for(size_t i=0;i<N;++i) buf[i]=p_bin::swap(buf[i]); } } }; #endif
target-10.c
/* { dg-do run } */ #pragma omp declare target extern int v; #pragma omp end declare target int v; int main () { #pragma omp target update to(v) return 0; }
GB_unaryop__identity_uint16_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_uint16_int16 // op(A') function: GB_tran__identity_uint16_int16 // C type: uint16_t // A type: int16_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z = (uint16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT16 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_uint16_int16 ( uint16_t *restrict Cx, const int16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_uint16_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <nnvm/node.h> #include <mxnet/imperative.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/storage.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_ONEDNN == 1 #include "../operator/nn/dnnl/dnnl_base-inl.h" #endif #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) #include <windows.h> #else #include <unistd.h> #endif namespace mxnet { namespace common { #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__) inline size_t current_process_id() { return ::GetCurrentProcessId(); } #else inline size_t current_process_id() { return getpid(); } #endif /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template <typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i + 1] < 0 || indptr[i + 1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template <typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i + 1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i + 1] - 1 && idx[j] >= idx[j + 1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template <typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i + 1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template <typename xpu> void CheckFormatWrapper(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template <typename xpu> void CheckFormatCSRImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const mxnet::TShape shape = input.shape(); const mxnet::TShape idx_shape = input.aux_shape(csr::kIdx); const mxnet::TShape indptr_shape = input.aux_shape(csr::kIndPtr); const mxnet::TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu>* s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template <typename xpu> void CheckFormatRSPImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const mxnet::TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu>* s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template <typename xpu> void CheckFormatImpl(const RunContext& rctx, const NDArray& input, const TBlob& err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template <typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu>* s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template <typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool* has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool* has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } inline std::string attr_value_string(const nnvm::NodeAttrs& attrs, const std::string& attr_name, std::string default_val = "") { if (attrs.dict.find(attr_name) == attrs.dict.end()) { return default_val; } return attrs.dict.at(attr_name); } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\n WARNING:\n" "Execution of the operator above will fallback to the generic implementation " #if MXNET_USE_ONEDNN == 1 "(not utilizing kernels from oneDNN library) " #endif "with default dense storage type. You are seeing this warning message because " #if MXNET_USE_ONEDNN == 1 "MXNET_ONEDNN_ENABLED flag is set to 0, in which case you can re-enable the default " "execution path by setting MXNET_ONEDNN_ENABLED back to 1, or " #endif "the operator above is unable to process the given ndarrays with specified storage types, " "context and/or parameter, in which case temporary dense ndarrays are generated in order to " "execute the operator. The fallback does not affect the correctness of the programme. Using " "default storage type performance degradation might be observed. \nYou can set environment " "variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to 0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_ONEDNN == 1 if (GetDNNLCacheSize() != -1) common::LogOnce( "MXNET_ONEDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template <typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+ : sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first + len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len / 2, grainsize, comp); ParallelSortHelper(first + len / 2, len - len / 2, grainsize, comp); thr.join(); std::inplace_merge(first, first + len / 2, first + len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024 * 16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template <typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort( first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template <typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask " << ctx.dev_mask(); return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max() : size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } template <> constexpr size_t MaxIntegerValue<mshadow::bfloat::bf16_t>() { return size_t(2) << 14; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const mxnet::TShape& shape, const Context& ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const mxnet::TShape& shape, const Context& ctx, const int dtype, std::vector<NDArray>* vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template <typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { #pragma GCC diagnostic push #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" #endif std::memcpy(dst, src, sizeof(DType) * size); #pragma GCC diagnostic pop } } /*! * \breif parallelize add by OpenMP */ template <typename DType> inline void ParallelAdd(DType* dst, const DType* src, index_t size) { static index_t add_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_SIZE", 200000); if (size >= add_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } else { for (index_t i = 0; i < size; ++i) { dst[i] += src[i]; } } } /*! * \brief If numpy compatibility is turned off (default), the shapes passed in * by users follow the legacy shape definition: * 1. 0 ndim means the shape is completely unknown. * 2. 0 dim size means the dim size is unknown. * We need to convert those shapes to use the numpy shape definition: * 1. 0 ndim means it's a scalar tensor. * 2. -1 ndim means the shape is unknown. * 3. 0 dim size means no elements in that dimension. * 4. -1 dim size means the dimension's size is unknown. * so that operator's infer shape function can work in backend. * \param shape to be converted. * Note: It is possible that the shape to be converted is already * numpy compatible. For example, when a subgraph operator's infer * shape function is called from the infer shape pass of the whole * graph, its input/output shapes have been converted to numpy * compatible shapes. */ inline void ConvertToNumpyShape(mxnet::TShape* shape) { if (shape->ndim() == 0) { // legacy shape ndim = 0 means unknown *shape = mxnet::TShape(); // unknown shape ndim = -1 } else { for (int j = 0; j < shape->ndim(); ++j) { if ((*shape)[j] == 0) { // legacy shape dim_size = 0 means unknown (*shape)[j] = -1; // unknown dim size = -1 } } } } inline void ConvertToNumpyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToNumpyShape(&(shapes->at(i))); } } /*! * \brief This is function is used to convert shapes returned by * the infer shape functions/pass to the legacy shape definition. */ inline void ConvertToLegacyShape(mxnet::TShape* shape) { if (!mxnet::ndim_is_known(*shape)) { *shape = mxnet::TShape(0, -1); } else { for (int j = 0; j < shape->ndim(); ++j) { if (!mxnet::dim_size_is_known(*shape, j)) { (*shape)[j] = 0; } } } } inline void ConvertToLegacyShape(mxnet::ShapeVector* shapes) { for (size_t i = 0; i < shapes->size(); ++i) { ConvertToLegacyShape(&(shapes->at(i))); } } void ExecuteMonInputCallback( const nnvm::IndexedGraph& idx, const std::vector<NDArray*>& state_arrays, size_t nid, const std::function<void(const char*, const char*, void*)>& monitor_callback); void ExecuteMonOutputCallback( const nnvm::IndexedGraph& idx, const std::vector<NDArray*>& state_arrays, size_t nid, const std::function<void(const char*, const char*, void*)>& monitor_callback); inline mxnet::TShape CanonicalizeAxes(const mxnet::TShape& src) { // convert negative axes to positive values const int ndim = src.ndim(); mxnet::TShape axes = src; for (int i = 0; i < ndim; ++i) { if (axes[i] < 0) { axes[i] += ndim; } CHECK(axes[i] >= 0 && axes[i] < ndim) << "axes[" << i << "]=" << axes[i] << " exceeds the range [" << 0 << ", " << ndim << ")"; } return axes; } inline bool is_float(const int dtype) { return dtype == mshadow::kFloat32 || dtype == mshadow::kFloat64 || dtype == mshadow::kFloat16; } inline bool is_int(const int dtype) { return dtype == mshadow::kUint8 || dtype == mshadow::kInt8 || dtype == mshadow::kUint16 || dtype == mshadow::kInt16 || dtype == mshadow::kUint32 || dtype == mshadow::kInt32 || dtype == mshadow::kUint64 || dtype == mshadow::kInt64; } inline bool is_signed_int(const int dtype) { return dtype == mshadow::kInt8 || dtype == mshadow::kInt16 || dtype == mshadow::kInt32 || dtype == mshadow::kInt64; } inline bool is_unsigned_int(const int dtype) { return dtype == mshadow::kUint8 || dtype == mshadow::kUint16 || dtype == mshadow::kUint32 || dtype == mshadow::kUint64; } static int bits_of(const int type_flag) { switch (type_flag) { case mshadow::kFloat32: return sizeof(float) * CHAR_BIT; case mshadow::kFloat64: return sizeof(double) * CHAR_BIT; case mshadow::kUint8: return sizeof(uint8_t) * CHAR_BIT; case mshadow::kInt32: return sizeof(int32_t) * CHAR_BIT; case mshadow::kInt8: return sizeof(int8_t) * CHAR_BIT; case mshadow::kInt64: return sizeof(int64_t) * CHAR_BIT; case mshadow::kBool: return sizeof(bool) * CHAR_BIT; case mshadow::kInt16: return sizeof(int16_t) * CHAR_BIT; case mshadow::kUint16: return sizeof(uint16_t) * CHAR_BIT; case mshadow::kUint32: return sizeof(uint32_t) * CHAR_BIT; case mshadow::kUint64: return sizeof(uint64_t) * CHAR_BIT; default: { LOG(FATAL) << "Unknown type_flag=" << type_flag; return -1; } } } inline int type_promotion(const int type1, const int type2) { if (type1 == type2) return type1; if (is_float(type1) && is_float(type2)) { if (type1 == mshadow::kFloat64 || type2 == mshadow::kFloat64) { return mshadow::kFloat64; } if (type1 == mshadow::kFloat32 || type2 == mshadow::kFloat32) { return mshadow::kFloat32; } return mshadow::kFloat16; } else if (is_float(type1) || is_float(type2)) { return is_float(type1) ? type1 : type2; } if (is_signed_int(type1) && is_signed_int(type2)) { if (type1 == mshadow::kInt64 || type2 == mshadow::kInt64) { return mshadow::kInt64; } if (type1 == mshadow::kInt32 || type2 == mshadow::kInt32) { return mshadow::kInt32; } if (type1 == mshadow::kInt16 || type2 == mshadow::kInt16) { return mshadow::kInt16; } return mshadow::kInt8; } else if (is_unsigned_int(type1) && is_unsigned_int(type2)) { if (type1 == mshadow::kUint64 || type2 == mshadow::kUint64) { return mshadow::kUint64; } if (type1 == mshadow::kUint32 || type2 == mshadow::kUint32) { return mshadow::kUint32; } if (type1 == mshadow::kUint16 || type2 == mshadow::kUint16) { return mshadow::kUint16; } return mshadow::kUint8; } else if (type1 == mshadow::kBool) { return type2; } else if (type2 == mshadow::kBool) { return type1; } else if (is_unsigned_int(type1) || is_unsigned_int(type2)) { if (bits_of(type1) < bits_of(type2)) { if (type1 == mshadow::kInt8 && type2 == mshadow::kUint16) { return mshadow::kInt32; } else if (type1 == mshadow::kInt8 && type2 == mshadow::kUint32) { return mshadow::kInt64; } else if (type1 == mshadow::kInt16 && type2 == mshadow::kUint32) { return mshadow::kInt64; } else if (type2 == mshadow::kUint64) { LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); } else { return type2; } } else if (bits_of(type2) < bits_of(type1)) { if (type2 == mshadow::kInt8 && type1 == mshadow::kUint16) { return mshadow::kInt32; } else if (type2 == mshadow::kInt8 && type1 == mshadow::kUint32) { return mshadow::kInt64; } else if (type2 == mshadow::kInt16 && type1 == mshadow::kUint32) { return mshadow::kInt64; } else if (type1 == mshadow::kUint64) { LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); } else { return type1; } } else { if (type1 == mshadow::kUint8 || type2 == mshadow::kUint8) { return mshadow::kInt16; } if (type1 == mshadow::kUint16 || type2 == mshadow::kUint16) { return mshadow::kInt32; } if (type1 == mshadow::kUint32 || type2 == mshadow::kUint32) { return mshadow::kInt64; } } } LOG(FATAL) << "Unsupported type promotions between " << mshadow::dtype_string(type1) << " and " << mshadow::dtype_string(type2); return -1; } inline const std::string NodeAttrsGetProfilerScope(const nnvm::NodeAttrs& attrs) { // obtain the profiler scope name, if assigned previously std::string profiler_scope = MXNET_STORAGE_DEFAULT_PROFILER_SCOPE_CSTR; const std::unordered_map<std::string, std::string>& node_attrs_dict = attrs.dict; const std::unordered_map<std::string, std::string>::const_iterator profiler_scope_iter = node_attrs_dict.find("__profiler_scope__"); if (profiler_scope_iter != node_attrs_dict.end()) { profiler_scope = profiler_scope_iter->second; } return profiler_scope; } inline int GetDefaultDtype() { return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } inline int GetDefaultDtype(int dtype) { if (dtype != -1) return dtype; return Imperative::Get()->is_np_default_dtype() ? mshadow::kFloat64 : mshadow::kFloat32; } struct MShadowTypeInfo { std::string name; int size; int acc_size; MShadowTypeInfo(const std::string name, const int size, const int acc_size) : name(std::move(name)), size(size), acc_size(acc_size) {} MShadowTypeInfo(const std::string name, const int size) : MShadowTypeInfo(name, size, size) {} }; MShadowTypeInfo mshadow_type_info(const int type_flag); inline bool AlignedMemAlloc(void** ptr, size_t size, size_t alignment) { #if _MSC_VER *ptr = _aligned_malloc(size, alignment); if (*ptr == nullptr) return false; #else int res = posix_memalign(ptr, alignment, size); if (res != 0) return false; #endif return true; } inline void AlignedMemFree(void* ptr) { #if _MSC_VER _aligned_free(ptr); #else free(ptr); #endif } inline index_t div_round(const index_t a, const index_t b) { return (a + b - 1) / b; } inline bool IsPower2(size_t N) { return ((N & (N - 1)) == 0) && N != 0; } inline size_t RoundToPower2(size_t N) { size_t ret = 1; size_t copyN = N; while (N >= 2) { ret *= 2; N /= 2; } if (ret < copyN) { ret *= 2; } return ret; } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
exp3_omp_v1.c
#include <stdio.h> #include <omp.h> int main() { int ii; #pragma omp parallel private(ii) { for(ii=0;ii<10;ii++) { printf("Iteration: %d from %d\n",ii,omp_get_thread_num()); } } printf("\n"); return 0; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 24; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
core_zttlqt.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> // This will be swapped during the automatic code generation. #undef REAL #define COMPLEX /***************************************************************************//** * * @ingroup core_ttlqt * * Computes an LQ factorization of a rectangular matrix * formed by coupling side-by-side an m-by-m lower triangular tile A1 * and an m-by-n lower triangular tile A2: * * | A1 A2 | = L * Q * * ******************************************************************************* * * @param[in] m * The number of rows of the tile A1 and A2. m >= 0. * The number of columns of the tile A1. * * @param[in] n * The number of columns of the tile A2. n >= 0. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in,out] A1 * On entry, the m-by-m tile A1. * On exit, the elements on and below the diagonal of the array * contain the m-by-m lower trapezoidal tile L; * the elements above the diagonal are not referenced. * * @param[in] lda1 * The leading dimension of the array A1. lda1 >= max(1,m). * * @param[in,out] A2 * On entry, the m-by-n lower triangular tile A2. * On exit, the elements on and below the diagonal of the array * with the matrix T represent * the unitary tile Q as a product of elementary reflectors. * * @param[in] lda2 * The leading dimension of the array A2. lda2 >= max(1,m). * * @param[out] T * The ib-by-m triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param tau * Auxiliary workspace array of length m. * * @param work * Auxiliary workspace array of length ib*m. * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ int core_zttlqt(int m, int n, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, plasma_complex64_t *T, int ldt, plasma_complex64_t *tau, plasma_complex64_t *work) { // Check input arguments. if (m < 0) { coreblas_error("illegal value of m"); return -1; } if (n < 0) { coreblas_error("illegal value of n"); return -2; } if (ib < 0) { coreblas_error("illegal value of ib"); return -3; } if (A1 == NULL) { coreblas_error("NULL A1"); return -4; } if (lda1 < imax(1, m) && m > 0) { coreblas_error("illegal value of lda1"); return -5; } if (A2 == NULL) { coreblas_error("NULL A2"); return -6; } if (lda2 < imax(1, m) && m > 0) { coreblas_error("illegal value of lda2"); return -7; } if (T == NULL) { coreblas_error("NULL T"); return -8; } if (ldt < imax(1, ib) && ib > 0) { coreblas_error("illegal value of ldt"); return -9; } if (tau == NULL) { coreblas_error("NULL tau"); return -10; } if (work == NULL) { coreblas_error("NULL work"); return -11; } // quick return if ((m == 0) || (n == 0) || (ib == 0)) return PlasmaSuccess; // TODO: Need to check why some cases require this to avoid // uninitialized values //core_zlaset(PlasmaGeneral, ib, m, 0.0, 0.0, T, ldt); for (int ii = 0; ii < m; ii += ib) { int sb = imin(m-ii, ib); for (int i = 0; i < sb; i++) { int j = ii + i; int mi = sb-i-1; int ni = imin( j + 1, n); // Generate elementary reflector H(ii*ib+i) to annihilate // A(ii*ib+i, ii*ib+i:m). #ifdef COMPLEX LAPACKE_zlacgv_work(ni, &A2[j], lda2); LAPACKE_zlacgv_work(1, &A1[lda1*j+j], lda1); #endif LAPACKE_zlarfg_work(ni+1, &A1[lda1*j+j], &A2[j], lda2, &tau[j]); plasma_complex64_t alpha; if (mi > 0) { // Apply H(j-1) to A(j:ii+ib-1, j-1:m) from the right. cblas_zcopy( mi, &A1[lda1*j+(j+1)], 1, work, 1); plasma_complex64_t zone = 1.0; cblas_zgemv( CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans, mi, ni, CBLAS_SADDR(zone), &A2[j+1], lda2, &A2[j], lda2, CBLAS_SADDR(zone), work, 1); alpha = -(tau[j]); cblas_zaxpy( mi, CBLAS_SADDR(alpha), work, 1, &A1[lda1*j+j+1], 1); cblas_zgerc( CblasColMajor, mi, ni, CBLAS_SADDR(alpha), work, 1, &A2[j], lda2, &A2[j+1], lda2); } // Calculate T. if (i > 0 ) { int l = imin(i, imax(0, n-ii)); alpha = -(tau[j]); core_zpemv( PlasmaNoTrans, PlasmaRowwise, i, imin(j, n), l, alpha, &A2[ii], lda2, &A2[j], lda2, 0.0, &T[ldt*j], 1, work); // T(0:i-1, j) = T(0:i-1, ii:j-1) * T(0:i-1, j) cblas_ztrmv( CblasColMajor, (CBLAS_UPLO)PlasmaUpper, (CBLAS_TRANSPOSE)PlasmaNoTrans, (CBLAS_DIAG)PlasmaNonUnit, i, &T[ldt*ii], ldt, &T[ldt*j], 1); } #ifdef COMPLEX LAPACKE_zlacgv_work(ni, &A2[j], lda2 ); LAPACKE_zlacgv_work(1, &A1[lda1*j+j], lda1 ); #endif T[ldt*j+i] = tau[j]; } // Apply Q to the rest of the matrix to the right. if (m > ii+sb) { int mi = m-(ii+sb); int ni = imin(ii+sb, n); int l = imin(sb, imax(0, ni-ii)); core_zparfb( PlasmaRight, PlasmaNoTrans, PlasmaForward, PlasmaRowwise, mi, ib, mi, ni, sb, l, &A1[lda1*ii+ii+sb], lda1, &A2[ii+sb], lda2, &A2[ii], lda2, &T[ldt*ii], ldt, work, m); } } return PlasmaSuccess; } /******************************************************************************/ void core_omp_zttlqt(int m, int n, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, plasma_complex64_t *T, int ldt, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A1[0:lda1*m]) \ depend(inout:A2[0:lda2*n]) \ depend(out:T[0:ib*m]) // T should be mxib, but is stored // as ibxm { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); plasma_complex64_t *tau = ((plasma_complex64_t*)work.spaces[tid]); // Call the kernel. int info = core_zttlqt(m, n, ib, A1, lda1, A2, lda2, T, ldt, tau, tau+m); if (info != PlasmaSuccess) { plasma_error("core_ztslqt() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
GB_positional_op_ip.c
//------------------------------------------------------------------------------ // GB_positional_op_ip: C = positional_op (A), depending only on i //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // A can be jumbled. If A is jumbled, so is C. { //-------------------------------------------------------------------------- // Cx = positional_op (A) //-------------------------------------------------------------------------- int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { // Cx [p] = op (A (i,j)) int64_t i = GBI (Ai, p, avlen) ; GB_APPLY (p) ; } } #undef GB_APPLY
fill_nr_3c.c
/* * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include "config.h" #include "cint.h" #define NCTRMAX 72 static void dcopy_s1(double *out, double *in, int comp, int ni, int nij, int nijk, int di, int dj, int dk) { const size_t dij = di * dj; int i, j, k, ic; double *pout, *pin; for (ic = 0; ic < comp; ic++) { for (k = 0; k < dk; k++) { pout = out + k * nij; pin = in + k * dij; for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { pout[j*ni+i] = pin[j*di+i]; } } } out += nijk; in += dij * dk; } } /* * out[naoi,naoj,naok,comp] in F-order */ void GTOnr3c_fill_s1(int (*intor)(), double *out, int comp, int ish, int jsh, double *buf, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t nij = naoi * naoj; const size_t nijk = nij * naok; ish += ish0; jsh += jsh0; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += jp * naoi + ip; int ksh, dk, k0; int shls[3]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { shls[2] = ksh; k0 = ao_loc[ksh ] - ao_loc[ksh0]; dk = ao_loc[ksh+1] - ao_loc[ksh]; (*intor)(buf, shls, atm, natm, bas, nbas, env, cintopt); dcopy_s1(out+k0*nij, buf, comp, naoi, nij, nijk, di, dj, dk); } } static void dcopy_s2_igtj(double *out, double *in, int comp, int ip, int nij, int nijk, int di, int dj, int dk) { const size_t dij = di * dj; const size_t ip1 = ip + 1; int i, j, k, ic; double *pout, *pin; for (ic = 0; ic < comp; ic++) { for (k = 0; k < dk; k++) { pout = out + k * nij; pin = in + k * dij; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { pout[j] = pin[j*di+i]; } pout += ip1 + i; } } out += nijk; in += dij * dk; } } static void dcopy_s2_ieqj(double *out, double *in, int comp, int ip, int nij, int nijk, int di, int dj, int dk) { const size_t dij = di * dj; const size_t ip1 = ip + 1; int i, j, k, ic; double *pout, *pin; for (ic = 0; ic < comp; ic++) { for (k = 0; k < dk; k++) { pout = out + k * nij; pin = in + k * dij; for (i = 0; i < di; i++) { for (j = 0; j <= i; j++) { pout[j] = pin[j*di+i]; } pout += ip1 + i; } } out += nijk; in += dij * dk; } } /* * out[comp,naok,nij] in C-order * nij = i1*(i1+1)/2 - i0*(i0+1)/2 * [ \ ] * [**** ] * [***** ] * [*****. ] <= . may not be filled, if jsh-upper-bound < ish-upper-bound * [ \] */ void GTOnr3c_fill_s2ij(int (*intor)(), double *out, int comp, int ish, int jsh, double *buf, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; ish += ish0; jsh += jsh0; const int ip = ao_loc[ish]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; if (ip < jp) { return; } const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const int i0 = ao_loc[ish0]; const int i1 = ao_loc[ish1]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off = i0 * (i0 + 1) / 2; const size_t nij = i1 * (i1 + 1) / 2 - off; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; out += ip * (ip + 1) / 2 - off + jp; int ksh, dk, k0; int shls[3]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { shls[2] = ksh; dk = ao_loc[ksh+1] - ao_loc[ksh]; k0 = ao_loc[ksh ] - ao_loc[ksh0]; (*intor)(buf, shls, atm, natm, bas, nbas, env, cintopt); if (ip != jp) { dcopy_s2_igtj(out+k0*nij, buf, comp, ip, nij, nijk, di, dj, dk); } else { dcopy_s2_ieqj(out+k0*nij, buf, comp, ip, nij, nijk, di, dj, dk); } } } void GTOnr3c_fill_s2jk(int (*intor)(), double *out, int comp, int ish, int jsh, double *buf, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { // TODO; } void GTOnr3c_drv(int (*intor)(), void (*fill)(), double *eri, int comp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; #pragma omp parallel default(none) \ shared(intor, fill, eri, comp, shls_slice, ao_loc, cintopt, \ atm, natm, bas, nbas, env) { int ish, jsh, ij; double *buf = (double *)malloc(sizeof(double)*NCTRMAX*NCTRMAX*NCTRMAX*comp); #pragma omp for schedule(dynamic) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; (*fill)(intor, eri, comp, ish, jsh, buf, shls_slice, ao_loc, cintopt, atm, natm, bas, nbas, env); } free(buf); } }
linear_tree_learner.h
/*! * Copyright (c) 2020 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_TREELEARNER_LINEAR_TREE_LEARNER_H_ #define LIGHTGBM_TREELEARNER_LINEAR_TREE_LEARNER_H_ #include <string> #include <cmath> #include <cstdio> #include <memory> #include <random> #include <vector> #include "serial_tree_learner.h" namespace LightGBM { class LinearTreeLearner: public SerialTreeLearner { public: explicit LinearTreeLearner(const Config* config) : SerialTreeLearner(config) {} void Init(const Dataset* train_data, bool is_constant_hessian) override; void InitLinear(const Dataset* train_data, const int max_leaves) override; Tree* Train(const score_t* gradients, const score_t *hessians, bool is_first_tree) override; /*! \brief Create array mapping dataset to leaf index, used for linear trees */ void GetLeafMap(Tree* tree) const; template<bool HAS_NAN> void CalculateLinear(Tree* tree, bool is_refit, const score_t* gradients, const score_t* hessians, bool is_first_tree) const; Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override; Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred, const score_t* gradients, const score_t* hessians) const override; void AddPredictionToScore(const Tree* tree, double* out_score) const override { CHECK_LE(tree->num_leaves(), data_partition_->num_leaves()); bool has_nan = false; if (any_nan_) { for (int i = 0; i < tree->num_leaves() - 1 ; ++i) { // use split_feature because split_feature_inner doesn't work when refitting existing tree if (contains_nan_[train_data_->InnerFeatureIndex(tree->split_feature(i))]) { has_nan = true; break; } } } if (has_nan) { AddPredictionToScoreInner<true>(tree, out_score); } else { AddPredictionToScoreInner<false>(tree, out_score); } } template<bool HAS_NAN> void AddPredictionToScoreInner(const Tree* tree, double* out_score) const { int num_leaves = tree->num_leaves(); std::vector<double> leaf_const(num_leaves); std::vector<std::vector<double>> leaf_coeff(num_leaves); std::vector<std::vector<const float*>> feat_ptr(num_leaves); std::vector<double> leaf_output(num_leaves); std::vector<int> leaf_num_features(num_leaves); for (int leaf_num = 0; leaf_num < num_leaves; ++leaf_num) { leaf_const[leaf_num] = tree->LeafConst(leaf_num); leaf_coeff[leaf_num] = tree->LeafCoeffs(leaf_num); leaf_output[leaf_num] = tree->LeafOutput(leaf_num); for (int feat : tree->LeafFeaturesInner(leaf_num)) { feat_ptr[leaf_num].push_back(train_data_->raw_index(feat)); } leaf_num_features[leaf_num] = static_cast<int>(feat_ptr[leaf_num].size()); } OMP_INIT_EX(); #pragma omp parallel for schedule(static) if (num_data_ > 1024) for (int i = 0; i < num_data_; ++i) { OMP_LOOP_EX_BEGIN(); int leaf_num = leaf_map_[i]; if (leaf_num < 0) { continue; } double output = leaf_const[leaf_num]; int num_feat = leaf_num_features[leaf_num]; if (HAS_NAN) { bool nan_found = false; for (int feat_ind = 0; feat_ind < num_feat; ++feat_ind) { float val = feat_ptr[leaf_num][feat_ind][i]; if (std::isnan(val)) { nan_found = true; break; } output += val * leaf_coeff[leaf_num][feat_ind]; } if (nan_found) { out_score[i] += leaf_output[leaf_num]; } else { out_score[i] += output; } } else { for (int feat_ind = 0; feat_ind < num_feat; ++feat_ind) { output += feat_ptr[leaf_num][feat_ind][i] * leaf_coeff[leaf_num][feat_ind]; } out_score[i] += output; } OMP_LOOP_EX_END(); } OMP_THROW_EX(); } protected: /*! \brief whether numerical features contain any nan values */ std::vector<int8_t> contains_nan_; /*! whether any numerical feature contains a nan value */ bool any_nan_; /*! \brief map dataset to leaves */ mutable std::vector<int> leaf_map_; /*! \brief temporary storage for calculating linear model coefficients */ mutable std::vector<std::vector<float>> XTHX_; mutable std::vector<std::vector<float>> XTg_; mutable std::vector<std::vector<std::vector<float>>> XTHX_by_thread_; mutable std::vector<std::vector<std::vector<float>>> XTg_by_thread_; }; } // namespace LightGBM #endif // LightGBM_TREELEARNER_LINEAR_TREE_LEARNER_H_
CH4-15step.c
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #if defined(BL_FORT_USE_UPPERCASE) #define CKINDX CKINDX #define CKINIT CKINIT #define CKFINALIZE CKFINALIZE #define CKXNUM CKXNUM #define CKSYME CKSYME #define CKSYMS CKSYMS #define CKRP CKRP #define CKPX CKPX #define CKPY CKPY #define CKPC CKPC #define CKRHOX CKRHOX #define CKRHOY CKRHOY #define CKRHOC CKRHOC #define CKWT CKWT #define CKAWT CKAWT #define CKMMWY CKMMWY #define CKMMWX CKMMWX #define CKMMWC CKMMWC #define CKYTX CKYTX #define CKYTCP CKYTCP #define CKYTCR CKYTCR #define CKXTY CKXTY #define CKXTCP CKXTCP #define CKXTCR CKXTCR #define CKCTX CKCTX #define CKCTY CKCTY #define CKCPOR CKCPOR #define CKHORT CKHORT #define CKSOR CKSOR #define CKCVML CKCVML #define CKCPML CKCPML #define CKUML CKUML #define CKHML CKHML #define CKGML CKGML #define CKAML CKAML #define CKSML CKSML #define CKCVMS CKCVMS #define CKCPMS CKCPMS #define CKUMS CKUMS #define CKHMS CKHMS #define CKGMS CKGMS #define CKAMS CKAMS #define CKSMS CKSMS #define CKCPBL CKCPBL #define CKCPBS CKCPBS #define CKCVBL CKCVBL #define CKCVBS CKCVBS #define CKHBML CKHBML #define CKHBMS CKHBMS #define CKUBML CKUBML #define CKUBMS CKUBMS #define CKSBML CKSBML #define CKSBMS CKSBMS #define CKGBML CKGBML #define CKGBMS CKGBMS #define CKABML CKABML #define CKABMS CKABMS /* #define CKWC CKWC */ #define CKWYP CKWYP #define CKWXP CKWXP #define CKWYR CKWYR #define CKWXR CKWXR #define CKQC CKQC #define CKKFKR CKKFKR #define CKQYP CKQYP #define CKQXP CKQXP #define CKQYR CKQYR #define CKQXR CKQXR #define CKNU CKNU #define CKNCF CKNCF #define CKABE CKABE #define CKEQC CKEQC #define CKEQYP CKEQYP #define CKEQXP CKEQXP #define CKEQYR CKEQYR #define CKEQXR CKEQXR #define DWDOT DWDOT #define VCKHMS VCKHMS #define VCKPY VCKPY #define VCKWYR VCKWYR #define VCKYTX VCKYTX #define GET_T_GIVEN_EY GET_T_GIVEN_EY #define GET_T_GIVEN_HY GET_T_GIVEN_HY #define GET_REACTION_MAP GET_REACTION_MAP #define GET_CRITPARAMS GET_CRITPARAMS #elif defined(BL_FORT_USE_LOWERCASE) #define CKINDX ckindx #define CKINIT ckinit #define CKFINALIZE ckfinalize #define CKXNUM ckxnum #define CKSYME cksyme #define CKSYMS cksyms #define CKRP ckrp #define CKPX ckpx #define CKPY ckpy #define CKPC ckpc #define CKRHOX ckrhox #define CKRHOY ckrhoy #define CKRHOC ckrhoc #define CKWT ckwt #define CKAWT ckawt #define CKMMWY ckmmwy #define CKMMWX ckmmwx #define CKMMWC ckmmwc #define CKYTX ckytx #define CKYTCP ckytcp #define CKYTCR ckytcr #define CKXTY ckxty #define CKXTCP ckxtcp #define CKXTCR ckxtcr #define CKCTX ckctx #define CKCTY ckcty #define CKCPOR ckcpor #define CKHORT ckhort #define CKSOR cksor #define CKCVML ckcvml #define CKCPML ckcpml #define CKUML ckuml #define CKHML ckhml #define CKGML ckgml #define CKAML ckaml #define CKSML cksml #define CKCVMS ckcvms #define CKCPMS ckcpms #define CKUMS ckums #define CKHMS ckhms #define CKGMS ckgms #define CKAMS ckams #define CKSMS cksms #define CKCPBL ckcpbl #define CKCPBS ckcpbs #define CKCVBL ckcvbl #define CKCVBS ckcvbs #define CKHBML ckhbml #define CKHBMS ckhbms #define CKUBML ckubml #define CKUBMS ckubms #define CKSBML cksbml #define CKSBMS cksbms #define CKGBML ckgbml #define CKGBMS ckgbms #define CKABML ckabml #define CKABMS ckabms /* #define CKWC ckwc */ #define CKWYP ckwyp #define CKWXP ckwxp #define CKWYR ckwyr #define CKWXR ckwxr #define CKQC ckqc #define CKKFKR ckkfkr #define CKQYP ckqyp #define CKQXP ckqxp #define CKQYR ckqyr #define CKQXR ckqxr #define CKNU cknu #define CKNCF ckncf #define CKABE ckabe #define CKEQC ckeqc #define CKEQYP ckeqyp #define CKEQXP ckeqxp #define CKEQYR ckeqyr #define CKEQXR ckeqxr #define DWDOT dwdot #define VCKHMS vckhms #define VCKPY vckpy #define VCKWYR vckwyr #define VCKYTX vckytx #define GET_T_GIVEN_EY get_t_given_ey #define GET_T_GIVEN_HY get_t_given_hy #define GET_REACTION_MAP get_reaction_map #define GET_CRITPARAMS get_critparams #elif defined(BL_FORT_USE_UNDERSCORE) #define CKINDX ckindx_ #define CKINIT ckinit_ #define CKFINALIZE ckfinalize_ #define CKXNUM ckxnum_ #define CKSYME cksyme_ #define CKSYMS cksyms_ #define CKRP ckrp_ #define CKPX ckpx_ #define CKPY ckpy_ #define CKPC ckpc_ #define CKRHOX ckrhox_ #define CKRHOY ckrhoy_ #define CKRHOC ckrhoc_ #define CKWT ckwt_ #define CKAWT ckawt_ #define CKMMWY ckmmwy_ #define CKMMWX ckmmwx_ #define CKMMWC ckmmwc_ #define CKYTX ckytx_ #define CKYTCP ckytcp_ #define CKYTCR ckytcr_ #define CKXTY ckxty_ #define CKXTCP ckxtcp_ #define CKXTCR ckxtcr_ #define CKCTX ckctx_ #define CKCTY ckcty_ #define CKCPOR ckcpor_ #define CKHORT ckhort_ #define CKSOR cksor_ #define CKCVML ckcvml_ #define CKCPML ckcpml_ #define CKUML ckuml_ #define CKHML ckhml_ #define CKGML ckgml_ #define CKAML ckaml_ #define CKSML cksml_ #define CKCVMS ckcvms_ #define CKCPMS ckcpms_ #define CKUMS ckums_ #define CKHMS ckhms_ #define CKGMS ckgms_ #define CKAMS ckams_ #define CKSMS cksms_ #define CKCPBL ckcpbl_ #define CKCPBS ckcpbs_ #define CKCVBL ckcvbl_ #define CKCVBS ckcvbs_ #define CKHBML ckhbml_ #define CKHBMS ckhbms_ #define CKUBML ckubml_ #define CKUBMS ckubms_ #define CKSBML cksbml_ #define CKSBMS cksbms_ #define CKGBML ckgbml_ #define CKGBMS ckgbms_ #define CKABML ckabml_ #define CKABMS ckabms_ /* #define CKWC ckwc_ */ #define CKWYP ckwyp_ #define CKWXP ckwxp_ #define CKWYR ckwyr_ #define CKWXR ckwxr_ #define CKQC ckqc_ #define CKKFKR ckkfkr_ #define CKQYP ckqyp_ #define CKQXP ckqxp_ #define CKQYR ckqyr_ #define CKQXR ckqxr_ #define CKNU cknu_ #define CKNCF ckncf_ #define CKABE ckabe_ #define CKEQC ckeqc_ #define CKEQYP ckeqyp_ #define CKEQXP ckeqxp_ #define CKEQYR ckeqyr_ #define CKEQXR ckeqxr_ #define DWDOT dwdot_ #define VCKHMS vckhms_ #define VCKPY vckpy_ #define VCKWYR vckwyr_ #define VCKYTX vckytx_ #define GET_T_GIVEN_EY get_t_given_ey_ #define GET_T_GIVEN_HY get_t_given_hy_ #define GET_REACTION_MAP get_reaction_map_ #define GET_CRITPARAMS get_critparams_ #endif /*function declarations */ #if defined(BL_FORT_USE_UPPERCASE) #define egtransetEPS EGTRANSETEPS #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetEPS egtranseteps #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetEPS egtranseteps_ #endif void egtransetEPS(double * EPS); #if defined(BL_FORT_USE_UPPERCASE) #define egtransetSIG EGTRANSETSIG #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetSIG egtransetsig #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetSIG egtransetsig_ #endif void egtransetSIG(double* SIG); void atomicWeight(double * restrict awt); void molecularWeight(double * restrict wt); void gibbs(double * restrict species, double * restrict tc); void helmholtz(double * restrict species, double * restrict tc); void speciesInternalEnergy(double * restrict species, double * restrict tc); void speciesEnthalpy(double * restrict species, double * restrict tc); void speciesEntropy(double * restrict species, double * restrict tc); void cp_R(double * restrict species, double * restrict tc); void cv_R(double * restrict species, double * restrict tc); void equilibriumConstants(double * restrict kc, double * restrict g_RT, double T); void productionRate(double * restrict wdot, double * restrict sc, double T); void comp_k_f(double * restrict tc, double invT, double * restrict k_f); void comp_Kc(double * restrict tc, double invT, double * restrict Kc); void comp_qfqr(double * restrict q_f, double * restrict q_r, double * restrict sc, double * restrict tc, double invT); void progressRate(double * restrict qdot, double * restrict speciesConc, double T); void progressRateFR(double * restrict q_f, double * restrict q_r, double * restrict speciesConc, double T); void CKINIT(); void CKFINALIZE(); void CKINDX(int * iwrk, double * restrict rwrk, int * mm, int * kk, int * ii, int * nfit ); void CKXNUM(char * line, int * nexp, int * lout, int * nval, double * restrict rval, int * kerr, int lenline); void CKSNUM(char * line, int * nexp, int * lout, char * kray, int * nn, int * knum, int * nval, double * restrict rval, int * kerr, int lenline, int lenkray); void CKSYME(int * kname, int * lenkname); void CKSYMS(int * kname, int * lenkname); void CKRP(int * ickwrk, double * restrict rckwrk, double * restrict ru, double * restrict ruc, double * restrict pa); void CKPX(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict P); void CKPY(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict P); void CKPC(double * restrict rho, double * restrict T, double * restrict c, int * iwrk, double * restrict rwrk, double * restrict P); void CKRHOX(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict rho); void CKRHOY(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict rho); void CKRHOC(double * restrict P, double * restrict T, double * restrict c, int * iwrk, double * restrict rwrk, double * restrict rho); void CKWT(int * iwrk, double * restrict rwrk, double * restrict wt); void CKAWT(int * iwrk, double * restrict rwrk, double * restrict awt); void CKMMWY(double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wtm); void CKMMWX(double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wtm); void CKMMWC(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict wtm); void CKYTX(double * restrict y, int * iwrk, double * restrict rwrk, double * restrict x); void CKYTCP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict c); void CKYTCR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict c); void CKXTY(double * restrict x, int * iwrk, double * restrict rwrk, double * restrict y); void CKXTCP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict c); void CKXTCR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict c); void CKCTX(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict x); void CKCTY(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict y); void CKCPOR(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cpor); void CKHORT(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict hort); void CKSOR(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sor); void CKCVML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvml); void CKCPML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvml); void CKUML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict uml); void CKHML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict uml); void CKGML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict gml); void CKAML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict aml); void CKSML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sml); void CKCVMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvms); void CKCPMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvms); void CKUMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ums); void CKHMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ums); void CKGMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict gms); void CKAMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ams); void CKSMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sms); void CKCPBL(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict cpbl); void CKCPBS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict cpbs); void CKCVBL(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict cpbl); void CKCVBS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict cpbs); void CKHBML(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict hbml); void CKHBMS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict hbms); void CKUBML(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict ubml); void CKUBMS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict ubms); void CKSBML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict sbml); void CKSBMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict sbms); void CKGBML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict gbml); void CKGBMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict gbms); void CKABML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict abml); void CKABMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict abms); /* void CKWC(double * restrict T, double * restrict C, int * iwrk, double * restrict rwrk, double * restrict wdot); */ void CKWYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wdot); void CKWXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wdot); void CKWYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wdot); void CKWXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wdot); void CKQC(double * restrict T, double * restrict C, int * iwrk, double * restrict rwrk, double * restrict qdot); void CKKFKR(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict q_f, double * restrict q_r); void CKQYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict qdot); void CKQXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict qdot); void CKQYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict qdot); void CKQXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict qdot); void CKNU(int * kdim, int * iwrk, double * restrict rwrk, int * nuki); void CKNCF(int * mdim, int * iwrk, double * restrict rwrk, int * ncf); void CKABE(int * iwrk, double * restrict rwrk, double * restrict a, double * restrict b, double * restrict e ); void CKEQC(double * restrict T, double * restrict C , int * iwrk, double * restrict rwrk, double * restrict eqcon ); void CKEQYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict eqcon); void CKEQXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict eqcon); void CKEQYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict eqcon); void CKEQXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict eqcon); void DWDOT(double * restrict J, double * restrict sc, double * restrict T, int * consP); void aJacobian(double * restrict J, double * restrict sc, double T, int consP); void dcvpRdT(double * restrict species, double * restrict tc); void GET_T_GIVEN_EY(double * restrict e, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict t, int *ierr); void GET_T_GIVEN_HY(double * restrict h, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict t, int *ierr); void GET_REACTION_MAP(int * restrict rmap); /*vector version */ void vproductionRate(int npt, double * restrict wdot, double * restrict c, double * restrict T); void VCKHMS(int * restrict np, double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ums); void VCKPY(int * restrict np, double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict P); void VCKWYR(int * restrict np, double * restrict rho, double * restrict T, double * restrict y, int * restrict iwrk, double * restrict rwrk, double * restrict wdot); void VCKYTX(int * restrict np, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict x); void vcomp_k_f(int npt, double * restrict k_f_s, double * restrict tc, double * restrict invT); void vcomp_gibbs(int npt, double * restrict g_RT, double * restrict tc); void vcomp_Kc(int npt, double * restrict Kc_s, double * restrict g_RT, double * restrict invT); void GET_CRITPARAMS(double * restrict Tci, double * restrict ai, double * restrict bi, double * restrict acentric_i); void vcomp_wdot(int npt, double * restrict wdot, double * restrict mixture, double * restrict sc, double * restrict k_f_s, double * restrict Kc_s, double * restrict tc, double * restrict invT, double * restrict T); /* Inverse molecular weights */ static const double imw[19] = { 1.0 / 2.015940, /*H2 */ 1.0 / 1.007970, /*H */ 1.0 / 31.998800, /*O2 */ 1.0 / 17.007370, /*OH */ 1.0 / 18.015340, /*H2O */ 1.0 / 33.006770, /*HO2 */ 1.0 / 34.014740, /*H2O2 */ 1.0 / 15.035060, /*CH3 */ 1.0 / 16.043030, /*CH4 */ 1.0 / 28.010550, /*CO */ 1.0 / 44.009950, /*CO2 */ 1.0 / 30.026490, /*CH2O */ 1.0 / 26.038240, /*C2H2 */ 1.0 / 28.054180, /*C2H4 */ 1.0 / 30.070120, /*C2H6 */ 1.0 / 17.030610, /*NH3 */ 1.0 / 30.006100, /*NO */ 1.0 / 27.025820, /*HCN */ 1.0 / 28.013400}; /*N2 */ static double fwd_A[0], fwd_beta[0], fwd_Ea[0]; static double low_A[0], low_beta[0], low_Ea[0]; static double rev_A[0], rev_beta[0], rev_Ea[0]; static double troe_a[0],troe_Ts[0], troe_Tss[0], troe_Tsss[0]; static double sri_a[0], sri_b[0], sri_c[0], sri_d[0], sri_e[0]; static double activation_units[0], prefactor_units[0], phase_units[0]; static int is_PD[0], troe_len[0], sri_len[0], nTB[0], *TBid[0]; static double *TB[0]; static double fwd_A_DEF[0], fwd_beta_DEF[0], fwd_Ea_DEF[0]; static double low_A_DEF[0], low_beta_DEF[0], low_Ea_DEF[0]; static double rev_A_DEF[0], rev_beta_DEF[0], rev_Ea_DEF[0]; static double troe_a_DEF[0],troe_Ts_DEF[0], troe_Tss_DEF[0], troe_Tsss_DEF[0]; static double sri_a_DEF[0], sri_b_DEF[0], sri_c_DEF[0], sri_d_DEF[0], sri_e_DEF[0]; static double activation_units_DEF[0], prefactor_units_DEF[0], phase_units_DEF[0]; static int is_PD_DEF[0], troe_len_DEF[0], sri_len_DEF[0], nTB_DEF[0], *TBid_DEF[0]; static double *TB_DEF[0]; static int rxn_map[0] = {}; void GET_REACTION_MAP(int *rmap) { for (int i=0; i<0; ++i) { rmap[i] = rxn_map[i]; } } #include <ReactionData.H> double* GetParamPtr(int reaction_id, REACTION_PARAMETER param_id, int species_id, int get_default) { double* ret = 0; if (reaction_id<0 || reaction_id>=0) { printf("Bad reaction id = %d",reaction_id); abort(); }; int mrid = rxn_map[reaction_id]; if (param_id == THIRD_BODY) { if (species_id<0 || species_id>=19) { printf("GetParamPtr: Bad species id = %d",species_id); abort(); } if (get_default) { for (int i=0; i<nTB_DEF[mrid]; ++i) { if (species_id == TBid_DEF[mrid][i]) { ret = &(TB_DEF[mrid][i]); } } } else { for (int i=0; i<nTB[mrid]; ++i) { if (species_id == TBid[mrid][i]) { ret = &(TB[mrid][i]); } } } if (ret == 0) { printf("GetParamPtr: No TB for reaction id = %d",reaction_id); abort(); } } else { if ( param_id == FWD_A) {ret = (get_default ? &(fwd_A_DEF[mrid]) : &(fwd_A[mrid]));} else if (param_id == FWD_BETA) {ret = (get_default ? &(fwd_beta_DEF[mrid]) : &(fwd_beta[mrid]));} else if (param_id == FWD_EA) {ret = (get_default ? &(fwd_Ea_DEF[mrid]) : &(fwd_Ea[mrid]));} else if (param_id == LOW_A) {ret = (get_default ? &(low_A_DEF[mrid]) : &(low_A[mrid]));} else if (param_id == LOW_BETA) {ret = (get_default ? &(low_beta_DEF[mrid]) : &(low_beta[mrid]));} else if (param_id == LOW_EA) {ret = (get_default ? &(low_Ea_DEF[mrid]) : &(low_Ea[mrid]));} else if (param_id == REV_A) {ret = (get_default ? &(rev_A_DEF[mrid]) : &(rev_A[mrid]));} else if (param_id == REV_BETA) {ret = (get_default ? &(rev_beta_DEF[mrid]) : &(rev_beta[mrid]));} else if (param_id == REV_EA) {ret = (get_default ? &(rev_Ea_DEF[mrid]) : &(rev_Ea[mrid]));} else if (param_id == TROE_A) {ret = (get_default ? &(troe_a_DEF[mrid]) : &(troe_a[mrid]));} else if (param_id == TROE_TS) {ret = (get_default ? &(troe_Ts_DEF[mrid]) : &(troe_Ts[mrid]));} else if (param_id == TROE_TSS) {ret = (get_default ? &(troe_Tss_DEF[mrid]) : &(troe_Tss[mrid]));} else if (param_id == TROE_TSSS) {ret = (get_default ? &(troe_Tsss_DEF[mrid]) : &(troe_Tsss[mrid]));} else if (param_id == SRI_A) {ret = (get_default ? &(sri_a_DEF[mrid]) : &(sri_a[mrid]));} else if (param_id == SRI_B) {ret = (get_default ? &(sri_b_DEF[mrid]) : &(sri_b[mrid]));} else if (param_id == SRI_C) {ret = (get_default ? &(sri_c_DEF[mrid]) : &(sri_c[mrid]));} else if (param_id == SRI_D) {ret = (get_default ? &(sri_d_DEF[mrid]) : &(sri_d[mrid]));} else if (param_id == SRI_E) {ret = (get_default ? &(sri_e_DEF[mrid]) : &(sri_e[mrid]));} else { printf("GetParamPtr: Unknown parameter id"); abort(); } } return ret; } void ResetAllParametersToDefault() { for (int i=0; i<0; i++) { if (nTB[i] != 0) { nTB[i] = 0; free(TB[i]); free(TBid[i]); } fwd_A[i] = fwd_A_DEF[i]; fwd_beta[i] = fwd_beta_DEF[i]; fwd_Ea[i] = fwd_Ea_DEF[i]; low_A[i] = low_A_DEF[i]; low_beta[i] = low_beta_DEF[i]; low_Ea[i] = low_Ea_DEF[i]; rev_A[i] = rev_A_DEF[i]; rev_beta[i] = rev_beta_DEF[i]; rev_Ea[i] = rev_Ea_DEF[i]; troe_a[i] = troe_a_DEF[i]; troe_Ts[i] = troe_Ts_DEF[i]; troe_Tss[i] = troe_Tss_DEF[i]; troe_Tsss[i] = troe_Tsss_DEF[i]; sri_a[i] = sri_a_DEF[i]; sri_b[i] = sri_b_DEF[i]; sri_c[i] = sri_c_DEF[i]; sri_d[i] = sri_d_DEF[i]; sri_e[i] = sri_e_DEF[i]; is_PD[i] = is_PD_DEF[i]; troe_len[i] = troe_len_DEF[i]; sri_len[i] = sri_len_DEF[i]; activation_units[i] = activation_units_DEF[i]; prefactor_units[i] = prefactor_units_DEF[i]; phase_units[i] = phase_units_DEF[i]; nTB[i] = nTB_DEF[i]; if (nTB[i] != 0) { TB[i] = (double *) malloc(sizeof(double) * nTB[i]); TBid[i] = (int *) malloc(sizeof(int) * nTB[i]); for (int j=0; j<nTB[i]; j++) { TB[i][j] = TB_DEF[i][j]; TBid[i][j] = TBid_DEF[i][j]; } } } } void SetAllDefaults() { for (int i=0; i<0; i++) { if (nTB_DEF[i] != 0) { nTB_DEF[i] = 0; free(TB_DEF[i]); free(TBid_DEF[i]); } fwd_A_DEF[i] = fwd_A[i]; fwd_beta_DEF[i] = fwd_beta[i]; fwd_Ea_DEF[i] = fwd_Ea[i]; low_A_DEF[i] = low_A[i]; low_beta_DEF[i] = low_beta[i]; low_Ea_DEF[i] = low_Ea[i]; rev_A_DEF[i] = rev_A[i]; rev_beta_DEF[i] = rev_beta[i]; rev_Ea_DEF[i] = rev_Ea[i]; troe_a_DEF[i] = troe_a[i]; troe_Ts_DEF[i] = troe_Ts[i]; troe_Tss_DEF[i] = troe_Tss[i]; troe_Tsss_DEF[i] = troe_Tsss[i]; sri_a_DEF[i] = sri_a[i]; sri_b_DEF[i] = sri_b[i]; sri_c_DEF[i] = sri_c[i]; sri_d_DEF[i] = sri_d[i]; sri_e_DEF[i] = sri_e[i]; is_PD_DEF[i] = is_PD[i]; troe_len_DEF[i] = troe_len[i]; sri_len_DEF[i] = sri_len[i]; activation_units_DEF[i] = activation_units[i]; prefactor_units_DEF[i] = prefactor_units[i]; phase_units_DEF[i] = phase_units[i]; nTB_DEF[i] = nTB[i]; if (nTB_DEF[i] != 0) { TB_DEF[i] = (double *) malloc(sizeof(double) * nTB_DEF[i]); TBid_DEF[i] = (int *) malloc(sizeof(int) * nTB_DEF[i]); for (int j=0; j<nTB_DEF[i]; j++) { TB_DEF[i][j] = TB[i][j]; TBid_DEF[i][j] = TBid[i][j]; } } } } /* Finalizes parameter database */ void CKFINALIZE() { for (int i=0; i<0; ++i) { free(TB[i]); TB[i] = 0; free(TBid[i]); TBid[i] = 0; nTB[i] = 0; free(TB_DEF[i]); TB_DEF[i] = 0; free(TBid_DEF[i]); TBid_DEF[i] = 0; nTB_DEF[i] = 0; } } /* Initializes parameter database */ void CKINIT() { SetAllDefaults(); } /*A few mechanism parameters */ void CKINDX(int * iwrk, double * restrict rwrk, int * mm, int * kk, int * ii, int * nfit) { *mm = 4; *kk = 19; *ii = 0; *nfit = -1; /*Why do you need this anyway ? */ } /* ckxnum... for parsing strings */ void CKXNUM(char * line, int * nexp, int * lout, int * nval, double * restrict rval, int * kerr, int lenline ) { int n,i; /*Loop Counters */ char cstr[1000]; char *saveptr; char *p; /*String Tokens */ /* Strip Comments */ for (i=0; i<lenline; ++i) { if (line[i]=='!') { break; } cstr[i] = line[i]; } cstr[i] = '\0'; p = strtok_r(cstr," ", &saveptr); if (!p) { *nval = 0; *kerr = 1; return; } for (n=0; n<*nexp; ++n) { rval[n] = atof(p); p = strtok_r(NULL, " ", &saveptr); if (!p) break; } *nval = n+1; if (*nval < *nexp) *kerr = 1; return; } /* cksnum... for parsing strings */ void CKSNUM(char * line, int * nexp, int * lout, char * kray, int * nn, int * knum, int * nval, double * restrict rval, int * kerr, int lenline, int lenkray) { /*Not done yet ... */ } /* Returns the char strings of element names */ void CKSYME(int * kname, int * plenkname ) { int i; /*Loop Counter */ int lenkname = *plenkname; /*clear kname */ for (i=0; i<lenkname*4; i++) { kname[i] = ' '; } /* O */ kname[ 0*lenkname + 0 ] = 'O'; kname[ 0*lenkname + 1 ] = ' '; /* H */ kname[ 1*lenkname + 0 ] = 'H'; kname[ 1*lenkname + 1 ] = ' '; /* C */ kname[ 2*lenkname + 0 ] = 'C'; kname[ 2*lenkname + 1 ] = ' '; /* N */ kname[ 3*lenkname + 0 ] = 'N'; kname[ 3*lenkname + 1 ] = ' '; } /* Returns the char strings of species names */ void CKSYMS(int * kname, int * plenkname ) { int i; /*Loop Counter */ int lenkname = *plenkname; /*clear kname */ for (i=0; i<lenkname*19; i++) { kname[i] = ' '; } /* H2 */ kname[ 0*lenkname + 0 ] = 'H'; kname[ 0*lenkname + 1 ] = '2'; kname[ 0*lenkname + 2 ] = ' '; /* H */ kname[ 1*lenkname + 0 ] = 'H'; kname[ 1*lenkname + 1 ] = ' '; /* O2 */ kname[ 2*lenkname + 0 ] = 'O'; kname[ 2*lenkname + 1 ] = '2'; kname[ 2*lenkname + 2 ] = ' '; /* OH */ kname[ 3*lenkname + 0 ] = 'O'; kname[ 3*lenkname + 1 ] = 'H'; kname[ 3*lenkname + 2 ] = ' '; /* H2O */ kname[ 4*lenkname + 0 ] = 'H'; kname[ 4*lenkname + 1 ] = '2'; kname[ 4*lenkname + 2 ] = 'O'; kname[ 4*lenkname + 3 ] = ' '; /* HO2 */ kname[ 5*lenkname + 0 ] = 'H'; kname[ 5*lenkname + 1 ] = 'O'; kname[ 5*lenkname + 2 ] = '2'; kname[ 5*lenkname + 3 ] = ' '; /* H2O2 */ kname[ 6*lenkname + 0 ] = 'H'; kname[ 6*lenkname + 1 ] = '2'; kname[ 6*lenkname + 2 ] = 'O'; kname[ 6*lenkname + 3 ] = '2'; kname[ 6*lenkname + 4 ] = ' '; /* CH3 */ kname[ 7*lenkname + 0 ] = 'C'; kname[ 7*lenkname + 1 ] = 'H'; kname[ 7*lenkname + 2 ] = '3'; kname[ 7*lenkname + 3 ] = ' '; /* CH4 */ kname[ 8*lenkname + 0 ] = 'C'; kname[ 8*lenkname + 1 ] = 'H'; kname[ 8*lenkname + 2 ] = '4'; kname[ 8*lenkname + 3 ] = ' '; /* CO */ kname[ 9*lenkname + 0 ] = 'C'; kname[ 9*lenkname + 1 ] = 'O'; kname[ 9*lenkname + 2 ] = ' '; /* CO2 */ kname[ 10*lenkname + 0 ] = 'C'; kname[ 10*lenkname + 1 ] = 'O'; kname[ 10*lenkname + 2 ] = '2'; kname[ 10*lenkname + 3 ] = ' '; /* CH2O */ kname[ 11*lenkname + 0 ] = 'C'; kname[ 11*lenkname + 1 ] = 'H'; kname[ 11*lenkname + 2 ] = '2'; kname[ 11*lenkname + 3 ] = 'O'; kname[ 11*lenkname + 4 ] = ' '; /* C2H2 */ kname[ 12*lenkname + 0 ] = 'C'; kname[ 12*lenkname + 1 ] = '2'; kname[ 12*lenkname + 2 ] = 'H'; kname[ 12*lenkname + 3 ] = '2'; kname[ 12*lenkname + 4 ] = ' '; /* C2H4 */ kname[ 13*lenkname + 0 ] = 'C'; kname[ 13*lenkname + 1 ] = '2'; kname[ 13*lenkname + 2 ] = 'H'; kname[ 13*lenkname + 3 ] = '4'; kname[ 13*lenkname + 4 ] = ' '; /* C2H6 */ kname[ 14*lenkname + 0 ] = 'C'; kname[ 14*lenkname + 1 ] = '2'; kname[ 14*lenkname + 2 ] = 'H'; kname[ 14*lenkname + 3 ] = '6'; kname[ 14*lenkname + 4 ] = ' '; /* NH3 */ kname[ 15*lenkname + 0 ] = 'N'; kname[ 15*lenkname + 1 ] = 'H'; kname[ 15*lenkname + 2 ] = '3'; kname[ 15*lenkname + 3 ] = ' '; /* NO */ kname[ 16*lenkname + 0 ] = 'N'; kname[ 16*lenkname + 1 ] = 'O'; kname[ 16*lenkname + 2 ] = ' '; /* HCN */ kname[ 17*lenkname + 0 ] = 'H'; kname[ 17*lenkname + 1 ] = 'C'; kname[ 17*lenkname + 2 ] = 'N'; kname[ 17*lenkname + 3 ] = ' '; /* N2 */ kname[ 18*lenkname + 0 ] = 'N'; kname[ 18*lenkname + 1 ] = '2'; kname[ 18*lenkname + 2 ] = ' '; } /* Returns R, Rc, Patm */ void CKRP(int * ickwrk, double * restrict rckwrk, double * restrict ru, double * restrict ruc, double * restrict pa) { *ru = 8.31451e+07; *ruc = 1.98721558317399615845; *pa = 1.01325e+06; } /*Compute P = rhoRT/W(x) */ void CKPX(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict P) { double XW = 0;/* To hold mean molecular wt */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ *P = *rho * 8.31451e+07 * (*T) / XW; /*P = rho*R*T/W */ return; } /*Compute P = rhoRT/W(y) */ void CKPY(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict P) { double YOW = 0;/* for computing mean MW */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ *P = *rho * 8.31451e+07 * (*T) * YOW; /*P = rho*R*T/W */ return; } /*Compute P = rhoRT/W(y) */ void VCKPY(int * restrict np, double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict P) { double YOW[*np]; for (int i=0; i<(*np); i++) { YOW[i] = 0.0; } for (int n=0; n<19; n++) { for (int i=0; i<(*np); i++) { YOW[i] += y[n*(*np)+i] * imw[n]; } } for (int i=0; i<(*np); i++) { P[i] = rho[i] * 8.31451e+07 * T[i] * YOW[i]; /*P = rho*R*T/W */ } return; } /*Compute P = rhoRT/W(c) */ void CKPC(double * restrict rho, double * restrict T, double * restrict c, int * iwrk, double * restrict rwrk, double * restrict P) { int id; /*loop counter */ /*See Eq 5 in CK Manual */ double W = 0; double sumC = 0; W += c[0]*2.015940; /*H2 */ W += c[1]*1.007970; /*H */ W += c[2]*31.998800; /*O2 */ W += c[3]*17.007370; /*OH */ W += c[4]*18.015340; /*H2O */ W += c[5]*33.006770; /*HO2 */ W += c[6]*34.014740; /*H2O2 */ W += c[7]*15.035060; /*CH3 */ W += c[8]*16.043030; /*CH4 */ W += c[9]*28.010550; /*CO */ W += c[10]*44.009950; /*CO2 */ W += c[11]*30.026490; /*CH2O */ W += c[12]*26.038240; /*C2H2 */ W += c[13]*28.054180; /*C2H4 */ W += c[14]*30.070120; /*C2H6 */ W += c[15]*17.030610; /*NH3 */ W += c[16]*30.006100; /*NO */ W += c[17]*27.025820; /*HCN */ W += c[18]*28.013400; /*N2 */ for (id = 0; id < 19; ++id) { sumC += c[id]; } *P = *rho * 8.31451e+07 * (*T) * sumC / W; /*P = rho*R*T/W */ return; } /*Compute rho = PW(x)/RT */ void CKRHOX(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict rho) { double XW = 0;/* To hold mean molecular wt */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ *rho = *P * XW / (8.31451e+07 * (*T)); /*rho = P*W/(R*T) */ return; } /*Compute rho = P*W(y)/RT */ void CKRHOY(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict rho) { double YOW = 0; double tmp[19]; for (int i = 0; i < 19; i++) { tmp[i] = y[i]*imw[i]; } for (int i = 0; i < 19; i++) { YOW += tmp[i]; } *rho = *P / (8.31451e+07 * (*T) * YOW);/*rho = P*W/(R*T) */ return; } /*Compute rho = P*W(c)/(R*T) */ void CKRHOC(double * restrict P, double * restrict T, double * restrict c, int * iwrk, double * restrict rwrk, double * restrict rho) { int id; /*loop counter */ /*See Eq 5 in CK Manual */ double W = 0; double sumC = 0; W += c[0]*2.015940; /*H2 */ W += c[1]*1.007970; /*H */ W += c[2]*31.998800; /*O2 */ W += c[3]*17.007370; /*OH */ W += c[4]*18.015340; /*H2O */ W += c[5]*33.006770; /*HO2 */ W += c[6]*34.014740; /*H2O2 */ W += c[7]*15.035060; /*CH3 */ W += c[8]*16.043030; /*CH4 */ W += c[9]*28.010550; /*CO */ W += c[10]*44.009950; /*CO2 */ W += c[11]*30.026490; /*CH2O */ W += c[12]*26.038240; /*C2H2 */ W += c[13]*28.054180; /*C2H4 */ W += c[14]*30.070120; /*C2H6 */ W += c[15]*17.030610; /*NH3 */ W += c[16]*30.006100; /*NO */ W += c[17]*27.025820; /*HCN */ W += c[18]*28.013400; /*N2 */ for (id = 0; id < 19; ++id) { sumC += c[id]; } *rho = *P * W / (sumC * (*T) * 8.31451e+07); /*rho = PW/(R*T) */ return; } /*get molecular weight for all species */ void CKWT(int * iwrk, double * restrict rwrk, double * restrict wt) { molecularWeight(wt); } /*get atomic weight for all elements */ void CKAWT(int * iwrk, double * restrict rwrk, double * restrict awt) { atomicWeight(awt); } /*given y[species]: mass fractions */ /*returns mean molecular weight (gm/mole) */ void CKMMWY(double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wtm) { double YOW = 0; double tmp[19]; for (int i = 0; i < 19; i++) { tmp[i] = y[i]*imw[i]; } for (int i = 0; i < 19; i++) { YOW += tmp[i]; } *wtm = 1.0 / YOW; return; } /*given x[species]: mole fractions */ /*returns mean molecular weight (gm/mole) */ void CKMMWX(double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wtm) { double XW = 0;/* see Eq 4 in CK Manual */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ *wtm = XW; return; } /*given c[species]: molar concentration */ /*returns mean molecular weight (gm/mole) */ void CKMMWC(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict wtm) { int id; /*loop counter */ /*See Eq 5 in CK Manual */ double W = 0; double sumC = 0; W += c[0]*2.015940; /*H2 */ W += c[1]*1.007970; /*H */ W += c[2]*31.998800; /*O2 */ W += c[3]*17.007370; /*OH */ W += c[4]*18.015340; /*H2O */ W += c[5]*33.006770; /*HO2 */ W += c[6]*34.014740; /*H2O2 */ W += c[7]*15.035060; /*CH3 */ W += c[8]*16.043030; /*CH4 */ W += c[9]*28.010550; /*CO */ W += c[10]*44.009950; /*CO2 */ W += c[11]*30.026490; /*CH2O */ W += c[12]*26.038240; /*C2H2 */ W += c[13]*28.054180; /*C2H4 */ W += c[14]*30.070120; /*C2H6 */ W += c[15]*17.030610; /*NH3 */ W += c[16]*30.006100; /*NO */ W += c[17]*27.025820; /*HCN */ W += c[18]*28.013400; /*N2 */ for (id = 0; id < 19; ++id) { sumC += c[id]; } /* CK provides no guard against divison by zero */ *wtm = W/sumC; return; } /*convert y[species] (mass fracs) to x[species] (mole fracs) */ void CKYTX(double * restrict y, int * iwrk, double * restrict rwrk, double * restrict x) { double YOW = 0; double tmp[19]; for (int i = 0; i < 19; i++) { tmp[i] = y[i]*imw[i]; } for (int i = 0; i < 19; i++) { YOW += tmp[i]; } double YOWINV = 1.0/YOW; for (int i = 0; i < 19; i++) { x[i] = y[i]*imw[i]*YOWINV; } return; } /*convert y[npoints*species] (mass fracs) to x[npoints*species] (mole fracs) */ void VCKYTX(int * restrict np, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict x) { double YOW[*np]; for (int i=0; i<(*np); i++) { YOW[i] = 0.0; } for (int n=0; n<19; n++) { for (int i=0; i<(*np); i++) { x[n*(*np)+i] = y[n*(*np)+i] * imw[n]; YOW[i] += x[n*(*np)+i]; } } for (int i=0; i<(*np); i++) { YOW[i] = 1.0/YOW[i]; } for (int n=0; n<19; n++) { for (int i=0; i<(*np); i++) { x[n*(*np)+i] *= YOW[i]; } } } /*convert y[species] (mass fracs) to c[species] (molar conc) */ void CKYTCP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict c) { double YOW = 0; double PWORT; /*Compute inverse of mean molecular wt first */ for (int i = 0; i < 19; i++) { c[i] = y[i]*imw[i]; } for (int i = 0; i < 19; i++) { YOW += c[i]; } /*PW/RT (see Eq. 7) */ PWORT = (*P)/(YOW * 8.31451e+07 * (*T)); /*Now compute conversion */ for (int i = 0; i < 19; i++) { c[i] = PWORT * y[i] * imw[i]; } return; } /*convert y[species] (mass fracs) to c[species] (molar conc) */ void CKYTCR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict c) { for (int i = 0; i < 19; i++) { c[i] = (*rho) * y[i] * imw[i]; } } /*convert x[species] (mole fracs) to y[species] (mass fracs) */ void CKXTY(double * restrict x, int * iwrk, double * restrict rwrk, double * restrict y) { double XW = 0; /*See Eq 4, 9 in CK Manual */ /*Compute mean molecular wt first */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ /*Now compute conversion */ double XWinv = 1.0/XW; y[0] = x[0]*2.015940*XWinv; y[1] = x[1]*1.007970*XWinv; y[2] = x[2]*31.998800*XWinv; y[3] = x[3]*17.007370*XWinv; y[4] = x[4]*18.015340*XWinv; y[5] = x[5]*33.006770*XWinv; y[6] = x[6]*34.014740*XWinv; y[7] = x[7]*15.035060*XWinv; y[8] = x[8]*16.043030*XWinv; y[9] = x[9]*28.010550*XWinv; y[10] = x[10]*44.009950*XWinv; y[11] = x[11]*30.026490*XWinv; y[12] = x[12]*26.038240*XWinv; y[13] = x[13]*28.054180*XWinv; y[14] = x[14]*30.070120*XWinv; y[15] = x[15]*17.030610*XWinv; y[16] = x[16]*30.006100*XWinv; y[17] = x[17]*27.025820*XWinv; y[18] = x[18]*28.013400*XWinv; return; } /*convert x[species] (mole fracs) to c[species] (molar conc) */ void CKXTCP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict c) { int id; /*loop counter */ double PORT = (*P)/(8.31451e+07 * (*T)); /*P/RT */ /*Compute conversion, see Eq 10 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*PORT; } return; } /*convert x[species] (mole fracs) to c[species] (molar conc) */ void CKXTCR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict c) { int id; /*loop counter */ double XW = 0; /*See Eq 4, 11 in CK Manual */ double ROW; /*Compute mean molecular wt first */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ ROW = (*rho) / XW; /*Compute conversion, see Eq 11 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*ROW; } return; } /*convert c[species] (molar conc) to x[species] (mole fracs) */ void CKCTX(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict x) { int id; /*loop counter */ double sumC = 0; /*compute sum of c */ for (id = 0; id < 19; ++id) { sumC += c[id]; } /* See Eq 13 */ double sumCinv = 1.0/sumC; for (id = 0; id < 19; ++id) { x[id] = c[id]*sumCinv; } return; } /*convert c[species] (molar conc) to y[species] (mass fracs) */ void CKCTY(double * restrict c, int * iwrk, double * restrict rwrk, double * restrict y) { double CW = 0; /*See Eq 12 in CK Manual */ /*compute denominator in eq 12 first */ CW += c[0]*2.015940; /*H2 */ CW += c[1]*1.007970; /*H */ CW += c[2]*31.998800; /*O2 */ CW += c[3]*17.007370; /*OH */ CW += c[4]*18.015340; /*H2O */ CW += c[5]*33.006770; /*HO2 */ CW += c[6]*34.014740; /*H2O2 */ CW += c[7]*15.035060; /*CH3 */ CW += c[8]*16.043030; /*CH4 */ CW += c[9]*28.010550; /*CO */ CW += c[10]*44.009950; /*CO2 */ CW += c[11]*30.026490; /*CH2O */ CW += c[12]*26.038240; /*C2H2 */ CW += c[13]*28.054180; /*C2H4 */ CW += c[14]*30.070120; /*C2H6 */ CW += c[15]*17.030610; /*NH3 */ CW += c[16]*30.006100; /*NO */ CW += c[17]*27.025820; /*HCN */ CW += c[18]*28.013400; /*N2 */ /*Now compute conversion */ double CWinv = 1.0/CW; y[0] = c[0]*2.015940*CWinv; y[1] = c[1]*1.007970*CWinv; y[2] = c[2]*31.998800*CWinv; y[3] = c[3]*17.007370*CWinv; y[4] = c[4]*18.015340*CWinv; y[5] = c[5]*33.006770*CWinv; y[6] = c[6]*34.014740*CWinv; y[7] = c[7]*15.035060*CWinv; y[8] = c[8]*16.043030*CWinv; y[9] = c[9]*28.010550*CWinv; y[10] = c[10]*44.009950*CWinv; y[11] = c[11]*30.026490*CWinv; y[12] = c[12]*26.038240*CWinv; y[13] = c[13]*28.054180*CWinv; y[14] = c[14]*30.070120*CWinv; y[15] = c[15]*17.030610*CWinv; y[16] = c[16]*30.006100*CWinv; y[17] = c[17]*27.025820*CWinv; y[18] = c[18]*28.013400*CWinv; return; } /*get Cp/R as a function of T */ /*for all species (Eq 19) */ void CKCPOR(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cpor) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ cp_R(cpor, tc); } /*get H/RT as a function of T */ /*for all species (Eq 20) */ void CKHORT(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict hort) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ speciesEnthalpy(hort, tc); } /*get S/R as a function of T */ /*for all species (Eq 21) */ void CKSOR(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sor) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ speciesEntropy(sor, tc); } /*get specific heat at constant volume as a function */ /*of T for all species (molar units) */ void CKCVML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ cv_R(cvml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { cvml[id] *= 8.31451e+07; } } /*get specific heat at constant pressure as a */ /*function of T for all species (molar units) */ void CKCPML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cpml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ cp_R(cpml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { cpml[id] *= 8.31451e+07; } } /*get internal energy as a function */ /*of T for all species (molar units) */ void CKUML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict uml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ speciesInternalEnergy(uml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { uml[id] *= RT; } } /*get enthalpy as a function */ /*of T for all species (molar units) */ void CKHML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict hml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ speciesEnthalpy(hml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { hml[id] *= RT; } } /*get standard-state Gibbs energy as a function */ /*of T for all species (molar units) */ void CKGML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict gml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ gibbs(gml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { gml[id] *= RT; } } /*get standard-state Helmholtz free energy as a */ /*function of T for all species (molar units) */ void CKAML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict aml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ helmholtz(aml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { aml[id] *= RT; } } /*Returns the standard-state entropies in molar units */ void CKSML(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sml) { int id; /*loop counter */ double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ speciesEntropy(sml, tc); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { sml[id] *= 8.31451e+07; } } /*Returns the specific heats at constant volume */ /*in mass units (Eq. 29) */ void CKCVMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cvms) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ cv_R(cvms, tc); /*multiply by R/molecularweight */ cvms[0] *= 4.124383662212169e+07; /*H2 */ cvms[1] *= 8.248767324424338e+07; /*H */ cvms[2] *= 2.598381814318037e+06; /*O2 */ cvms[3] *= 4.888768810227566e+06; /*OH */ cvms[4] *= 4.615239012974499e+06; /*H2O */ cvms[5] *= 2.519031701678171e+06; /*HO2 */ cvms[6] *= 2.444384405113783e+06; /*H2O2 */ cvms[7] *= 5.530081023953346e+06; /*CH3 */ cvms[8] *= 5.182630712527496e+06; /*CH4 */ cvms[9] *= 2.968349425484326e+06; /*CO */ cvms[10] *= 1.889234139098090e+06; /*CO2 */ cvms[11] *= 2.769058254894261e+06; /*CH2O */ cvms[12] *= 3.193192012977835e+06; /*C2H2 */ cvms[13] *= 2.963733033722604e+06; /*C2H4 */ cvms[14] *= 2.765040511976673e+06; /*C2H6 */ cvms[15] *= 4.882097587813943e+06; /*NH3 */ cvms[16] *= 2.770939908885194e+06; /*NO */ cvms[17] *= 3.076506096762281e+06; /*HCN */ cvms[18] *= 2.968047434442088e+06; /*N2 */ } /*Returns the specific heats at constant pressure */ /*in mass units (Eq. 26) */ void CKCPMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict cpms) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ cp_R(cpms, tc); /*multiply by R/molecularweight */ cpms[0] *= 4.124383662212169e+07; /*H2 */ cpms[1] *= 8.248767324424338e+07; /*H */ cpms[2] *= 2.598381814318037e+06; /*O2 */ cpms[3] *= 4.888768810227566e+06; /*OH */ cpms[4] *= 4.615239012974499e+06; /*H2O */ cpms[5] *= 2.519031701678171e+06; /*HO2 */ cpms[6] *= 2.444384405113783e+06; /*H2O2 */ cpms[7] *= 5.530081023953346e+06; /*CH3 */ cpms[8] *= 5.182630712527496e+06; /*CH4 */ cpms[9] *= 2.968349425484326e+06; /*CO */ cpms[10] *= 1.889234139098090e+06; /*CO2 */ cpms[11] *= 2.769058254894261e+06; /*CH2O */ cpms[12] *= 3.193192012977835e+06; /*C2H2 */ cpms[13] *= 2.963733033722604e+06; /*C2H4 */ cpms[14] *= 2.765040511976673e+06; /*C2H6 */ cpms[15] *= 4.882097587813943e+06; /*NH3 */ cpms[16] *= 2.770939908885194e+06; /*NO */ cpms[17] *= 3.076506096762281e+06; /*HCN */ cpms[18] *= 2.968047434442088e+06; /*N2 */ } /*Returns internal energy in mass units (Eq 30.) */ void CKUMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ums) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ speciesInternalEnergy(ums, tc); for (int i = 0; i < 19; i++) { ums[i] *= RT*imw[i]; } } /*Returns enthalpy in mass units (Eq 27.) */ void CKHMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict hms) { double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ speciesEnthalpy(hms, tc); for (int i = 0; i < 19; i++) { hms[i] *= RT*imw[i]; } } /*Returns enthalpy in mass units (Eq 27.) */ void VCKHMS(int * restrict np, double * restrict T, int * iwrk, double * restrict rwrk, double * restrict hms) { double tc[5], h[19]; for (int i=0; i<(*np); i++) { tc[0] = 0.0; tc[1] = T[i]; tc[2] = T[i]*T[i]; tc[3] = T[i]*T[i]*T[i]; tc[4] = T[i]*T[i]*T[i]*T[i]; speciesEnthalpy(h, tc); hms[0*(*np)+i] = h[0]; hms[1*(*np)+i] = h[1]; hms[2*(*np)+i] = h[2]; hms[3*(*np)+i] = h[3]; hms[4*(*np)+i] = h[4]; hms[5*(*np)+i] = h[5]; hms[6*(*np)+i] = h[6]; hms[7*(*np)+i] = h[7]; hms[8*(*np)+i] = h[8]; hms[9*(*np)+i] = h[9]; hms[10*(*np)+i] = h[10]; hms[11*(*np)+i] = h[11]; hms[12*(*np)+i] = h[12]; hms[13*(*np)+i] = h[13]; hms[14*(*np)+i] = h[14]; hms[15*(*np)+i] = h[15]; hms[16*(*np)+i] = h[16]; hms[17*(*np)+i] = h[17]; hms[18*(*np)+i] = h[18]; } for (int n=0; n<19; n++) { for (int i=0; i<(*np); i++) { hms[n*(*np)+i] *= 8.31451e+07 * T[i] * imw[n]; } } } /*Returns gibbs in mass units (Eq 31.) */ void CKGMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict gms) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ gibbs(gms, tc); for (int i = 0; i < 19; i++) { gms[i] *= RT*imw[i]; } } /*Returns helmholtz in mass units (Eq 32.) */ void CKAMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict ams) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ helmholtz(ams, tc); for (int i = 0; i < 19; i++) { ams[i] *= RT*imw[i]; } } /*Returns the entropies in mass units (Eq 28.) */ void CKSMS(double * restrict T, int * iwrk, double * restrict rwrk, double * restrict sms) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ speciesEntropy(sms, tc); /*multiply by R/molecularweight */ sms[0] *= 4.124383662212169e+07; /*H2 */ sms[1] *= 8.248767324424338e+07; /*H */ sms[2] *= 2.598381814318037e+06; /*O2 */ sms[3] *= 4.888768810227566e+06; /*OH */ sms[4] *= 4.615239012974499e+06; /*H2O */ sms[5] *= 2.519031701678171e+06; /*HO2 */ sms[6] *= 2.444384405113783e+06; /*H2O2 */ sms[7] *= 5.530081023953346e+06; /*CH3 */ sms[8] *= 5.182630712527496e+06; /*CH4 */ sms[9] *= 2.968349425484326e+06; /*CO */ sms[10] *= 1.889234139098090e+06; /*CO2 */ sms[11] *= 2.769058254894261e+06; /*CH2O */ sms[12] *= 3.193192012977835e+06; /*C2H2 */ sms[13] *= 2.963733033722604e+06; /*C2H4 */ sms[14] *= 2.765040511976673e+06; /*C2H6 */ sms[15] *= 4.882097587813943e+06; /*NH3 */ sms[16] *= 2.770939908885194e+06; /*NO */ sms[17] *= 3.076506096762281e+06; /*HCN */ sms[18] *= 2.968047434442088e+06; /*N2 */ } /*Returns the mean specific heat at CP (Eq. 33) */ void CKCPBL(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict cpbl) { int id; /*loop counter */ double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double cpor[19]; /* temporary storage */ cp_R(cpor, tc); /*perform dot product */ for (id = 0; id < 19; ++id) { result += x[id]*cpor[id]; } *cpbl = result * 8.31451e+07; } /*Returns the mean specific heat at CP (Eq. 34) */ void CKCPBS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict cpbs) { double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double cpor[19], tresult[19]; /* temporary storage */ cp_R(cpor, tc); for (int i = 0; i < 19; i++) { tresult[i] = cpor[i]*y[i]*imw[i]; } for (int i = 0; i < 19; i++) { result += tresult[i]; } *cpbs = result * 8.31451e+07; } /*Returns the mean specific heat at CV (Eq. 35) */ void CKCVBL(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict cvbl) { int id; /*loop counter */ double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double cvor[19]; /* temporary storage */ cv_R(cvor, tc); /*perform dot product */ for (id = 0; id < 19; ++id) { result += x[id]*cvor[id]; } *cvbl = result * 8.31451e+07; } /*Returns the mean specific heat at CV (Eq. 36) */ void CKCVBS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict cvbs) { double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double cvor[19]; /* temporary storage */ cv_R(cvor, tc); /*multiply by y/molecularweight */ result += cvor[0]*y[0]*imw[0]; /*H2 */ result += cvor[1]*y[1]*imw[1]; /*H */ result += cvor[2]*y[2]*imw[2]; /*O2 */ result += cvor[3]*y[3]*imw[3]; /*OH */ result += cvor[4]*y[4]*imw[4]; /*H2O */ result += cvor[5]*y[5]*imw[5]; /*HO2 */ result += cvor[6]*y[6]*imw[6]; /*H2O2 */ result += cvor[7]*y[7]*imw[7]; /*CH3 */ result += cvor[8]*y[8]*imw[8]; /*CH4 */ result += cvor[9]*y[9]*imw[9]; /*CO */ result += cvor[10]*y[10]*imw[10]; /*CO2 */ result += cvor[11]*y[11]*imw[11]; /*CH2O */ result += cvor[12]*y[12]*imw[12]; /*C2H2 */ result += cvor[13]*y[13]*imw[13]; /*C2H4 */ result += cvor[14]*y[14]*imw[14]; /*C2H6 */ result += cvor[15]*y[15]*imw[15]; /*NH3 */ result += cvor[16]*y[16]*imw[16]; /*NO */ result += cvor[17]*y[17]*imw[17]; /*HCN */ result += cvor[18]*y[18]*imw[18]; /*N2 */ *cvbs = result * 8.31451e+07; } /*Returns the mean enthalpy of the mixture in molar units */ void CKHBML(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict hbml) { int id; /*loop counter */ double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double hml[19]; /* temporary storage */ double RT = 8.31451e+07*tT; /*R*T */ speciesEnthalpy(hml, tc); /*perform dot product */ for (id = 0; id < 19; ++id) { result += x[id]*hml[id]; } *hbml = result * RT; } /*Returns mean enthalpy of mixture in mass units */ void CKHBMS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict hbms) { double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double hml[19], tmp[19]; /* temporary storage */ double RT = 8.31451e+07*tT; /*R*T */ speciesEnthalpy(hml, tc); int id; for (id = 0; id < 19; ++id) { tmp[id] = y[id]*hml[id]*imw[id]; } for (id = 0; id < 19; ++id) { result += tmp[id]; } *hbms = result * RT; } /*get mean internal energy in molar units */ void CKUBML(double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict ubml) { int id; /*loop counter */ double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double uml[19]; /* temporary energy array */ double RT = 8.31451e+07*tT; /*R*T */ speciesInternalEnergy(uml, tc); /*perform dot product */ for (id = 0; id < 19; ++id) { result += x[id]*uml[id]; } *ubml = result * RT; } /*get mean internal energy in mass units */ void CKUBMS(double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict ubms) { double result = 0; double tT = *T; /*temporary temperature */ double tc[] = { 0, tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double ums[19]; /* temporary energy array */ double RT = 8.31451e+07*tT; /*R*T */ speciesInternalEnergy(ums, tc); /*perform dot product + scaling by wt */ result += y[0]*ums[0]*imw[0]; /*H2 */ result += y[1]*ums[1]*imw[1]; /*H */ result += y[2]*ums[2]*imw[2]; /*O2 */ result += y[3]*ums[3]*imw[3]; /*OH */ result += y[4]*ums[4]*imw[4]; /*H2O */ result += y[5]*ums[5]*imw[5]; /*HO2 */ result += y[6]*ums[6]*imw[6]; /*H2O2 */ result += y[7]*ums[7]*imw[7]; /*CH3 */ result += y[8]*ums[8]*imw[8]; /*CH4 */ result += y[9]*ums[9]*imw[9]; /*CO */ result += y[10]*ums[10]*imw[10]; /*CO2 */ result += y[11]*ums[11]*imw[11]; /*CH2O */ result += y[12]*ums[12]*imw[12]; /*C2H2 */ result += y[13]*ums[13]*imw[13]; /*C2H4 */ result += y[14]*ums[14]*imw[14]; /*C2H6 */ result += y[15]*ums[15]*imw[15]; /*NH3 */ result += y[16]*ums[16]*imw[16]; /*NO */ result += y[17]*ums[17]*imw[17]; /*HCN */ result += y[18]*ums[18]*imw[18]; /*N2 */ *ubms = result * RT; } /*get mixture entropy in molar units */ void CKSBML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict sbml) { int id; /*loop counter */ double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double sor[19]; /* temporary storage */ speciesEntropy(sor, tc); /*Compute Eq 42 */ for (id = 0; id < 19; ++id) { result += x[id]*(sor[id]-log((x[id]+1e-100))-logPratio); } *sbml = result * 8.31451e+07; } /*get mixture entropy in mass units */ void CKSBMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict sbms) { double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double sor[19]; /* temporary storage */ double x[19]; /* need a ytx conversion */ double YOW = 0; /*See Eq 4, 6 in CK Manual */ /*Compute inverse of mean molecular wt first */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ /*Now compute y to x conversion */ x[0] = y[0]/(2.015940*YOW); x[1] = y[1]/(1.007970*YOW); x[2] = y[2]/(31.998800*YOW); x[3] = y[3]/(17.007370*YOW); x[4] = y[4]/(18.015340*YOW); x[5] = y[5]/(33.006770*YOW); x[6] = y[6]/(34.014740*YOW); x[7] = y[7]/(15.035060*YOW); x[8] = y[8]/(16.043030*YOW); x[9] = y[9]/(28.010550*YOW); x[10] = y[10]/(44.009950*YOW); x[11] = y[11]/(30.026490*YOW); x[12] = y[12]/(26.038240*YOW); x[13] = y[13]/(28.054180*YOW); x[14] = y[14]/(30.070120*YOW); x[15] = y[15]/(17.030610*YOW); x[16] = y[16]/(30.006100*YOW); x[17] = y[17]/(27.025820*YOW); x[18] = y[18]/(28.013400*YOW); speciesEntropy(sor, tc); /*Perform computation in Eq 42 and 43 */ result += x[0]*(sor[0]-log((x[0]+1e-100))-logPratio); result += x[1]*(sor[1]-log((x[1]+1e-100))-logPratio); result += x[2]*(sor[2]-log((x[2]+1e-100))-logPratio); result += x[3]*(sor[3]-log((x[3]+1e-100))-logPratio); result += x[4]*(sor[4]-log((x[4]+1e-100))-logPratio); result += x[5]*(sor[5]-log((x[5]+1e-100))-logPratio); result += x[6]*(sor[6]-log((x[6]+1e-100))-logPratio); result += x[7]*(sor[7]-log((x[7]+1e-100))-logPratio); result += x[8]*(sor[8]-log((x[8]+1e-100))-logPratio); result += x[9]*(sor[9]-log((x[9]+1e-100))-logPratio); result += x[10]*(sor[10]-log((x[10]+1e-100))-logPratio); result += x[11]*(sor[11]-log((x[11]+1e-100))-logPratio); result += x[12]*(sor[12]-log((x[12]+1e-100))-logPratio); result += x[13]*(sor[13]-log((x[13]+1e-100))-logPratio); result += x[14]*(sor[14]-log((x[14]+1e-100))-logPratio); result += x[15]*(sor[15]-log((x[15]+1e-100))-logPratio); result += x[16]*(sor[16]-log((x[16]+1e-100))-logPratio); result += x[17]*(sor[17]-log((x[17]+1e-100))-logPratio); result += x[18]*(sor[18]-log((x[18]+1e-100))-logPratio); /*Scale by R/W */ *sbms = result * 8.31451e+07 * YOW; } /*Returns mean gibbs free energy in molar units */ void CKGBML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict gbml) { int id; /*loop counter */ double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ double gort[19]; /* temporary storage */ /*Compute g/RT */ gibbs(gort, tc); /*Compute Eq 44 */ for (id = 0; id < 19; ++id) { result += x[id]*(gort[id]+log((x[id]+1e-100))+logPratio); } *gbml = result * RT; } /*Returns mixture gibbs free energy in mass units */ void CKGBMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict gbms) { double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ double gort[19]; /* temporary storage */ double x[19]; /* need a ytx conversion */ double YOW = 0; /*To hold 1/molecularweight */ /*Compute inverse of mean molecular wt first */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ /*Now compute y to x conversion */ x[0] = y[0]/(2.015940*YOW); x[1] = y[1]/(1.007970*YOW); x[2] = y[2]/(31.998800*YOW); x[3] = y[3]/(17.007370*YOW); x[4] = y[4]/(18.015340*YOW); x[5] = y[5]/(33.006770*YOW); x[6] = y[6]/(34.014740*YOW); x[7] = y[7]/(15.035060*YOW); x[8] = y[8]/(16.043030*YOW); x[9] = y[9]/(28.010550*YOW); x[10] = y[10]/(44.009950*YOW); x[11] = y[11]/(30.026490*YOW); x[12] = y[12]/(26.038240*YOW); x[13] = y[13]/(28.054180*YOW); x[14] = y[14]/(30.070120*YOW); x[15] = y[15]/(17.030610*YOW); x[16] = y[16]/(30.006100*YOW); x[17] = y[17]/(27.025820*YOW); x[18] = y[18]/(28.013400*YOW); gibbs(gort, tc); /*Perform computation in Eq 44 */ result += x[0]*(gort[0]+log((x[0]+1e-100))+logPratio); result += x[1]*(gort[1]+log((x[1]+1e-100))+logPratio); result += x[2]*(gort[2]+log((x[2]+1e-100))+logPratio); result += x[3]*(gort[3]+log((x[3]+1e-100))+logPratio); result += x[4]*(gort[4]+log((x[4]+1e-100))+logPratio); result += x[5]*(gort[5]+log((x[5]+1e-100))+logPratio); result += x[6]*(gort[6]+log((x[6]+1e-100))+logPratio); result += x[7]*(gort[7]+log((x[7]+1e-100))+logPratio); result += x[8]*(gort[8]+log((x[8]+1e-100))+logPratio); result += x[9]*(gort[9]+log((x[9]+1e-100))+logPratio); result += x[10]*(gort[10]+log((x[10]+1e-100))+logPratio); result += x[11]*(gort[11]+log((x[11]+1e-100))+logPratio); result += x[12]*(gort[12]+log((x[12]+1e-100))+logPratio); result += x[13]*(gort[13]+log((x[13]+1e-100))+logPratio); result += x[14]*(gort[14]+log((x[14]+1e-100))+logPratio); result += x[15]*(gort[15]+log((x[15]+1e-100))+logPratio); result += x[16]*(gort[16]+log((x[16]+1e-100))+logPratio); result += x[17]*(gort[17]+log((x[17]+1e-100))+logPratio); result += x[18]*(gort[18]+log((x[18]+1e-100))+logPratio); /*Scale by RT/W */ *gbms = result * RT * YOW; } /*Returns mean helmholtz free energy in molar units */ void CKABML(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict abml) { int id; /*loop counter */ double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ double aort[19]; /* temporary storage */ /*Compute g/RT */ helmholtz(aort, tc); /*Compute Eq 44 */ for (id = 0; id < 19; ++id) { result += x[id]*(aort[id]+log((x[id]+1e-100))+logPratio); } *abml = result * RT; } /*Returns mixture helmholtz free energy in mass units */ void CKABMS(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict abms) { double result = 0; /*Log of normalized pressure in cgs units dynes/cm^2 by Patm */ double logPratio = log ( *P / 1013250.0 ); double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double RT = 8.31451e+07*tT; /*R*T */ double aort[19]; /* temporary storage */ double x[19]; /* need a ytx conversion */ double YOW = 0; /*To hold 1/molecularweight */ /*Compute inverse of mean molecular wt first */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ /*Now compute y to x conversion */ x[0] = y[0]/(2.015940*YOW); x[1] = y[1]/(1.007970*YOW); x[2] = y[2]/(31.998800*YOW); x[3] = y[3]/(17.007370*YOW); x[4] = y[4]/(18.015340*YOW); x[5] = y[5]/(33.006770*YOW); x[6] = y[6]/(34.014740*YOW); x[7] = y[7]/(15.035060*YOW); x[8] = y[8]/(16.043030*YOW); x[9] = y[9]/(28.010550*YOW); x[10] = y[10]/(44.009950*YOW); x[11] = y[11]/(30.026490*YOW); x[12] = y[12]/(26.038240*YOW); x[13] = y[13]/(28.054180*YOW); x[14] = y[14]/(30.070120*YOW); x[15] = y[15]/(17.030610*YOW); x[16] = y[16]/(30.006100*YOW); x[17] = y[17]/(27.025820*YOW); x[18] = y[18]/(28.013400*YOW); helmholtz(aort, tc); /*Perform computation in Eq 44 */ result += x[0]*(aort[0]+log((x[0]+1e-100))+logPratio); result += x[1]*(aort[1]+log((x[1]+1e-100))+logPratio); result += x[2]*(aort[2]+log((x[2]+1e-100))+logPratio); result += x[3]*(aort[3]+log((x[3]+1e-100))+logPratio); result += x[4]*(aort[4]+log((x[4]+1e-100))+logPratio); result += x[5]*(aort[5]+log((x[5]+1e-100))+logPratio); result += x[6]*(aort[6]+log((x[6]+1e-100))+logPratio); result += x[7]*(aort[7]+log((x[7]+1e-100))+logPratio); result += x[8]*(aort[8]+log((x[8]+1e-100))+logPratio); result += x[9]*(aort[9]+log((x[9]+1e-100))+logPratio); result += x[10]*(aort[10]+log((x[10]+1e-100))+logPratio); result += x[11]*(aort[11]+log((x[11]+1e-100))+logPratio); result += x[12]*(aort[12]+log((x[12]+1e-100))+logPratio); result += x[13]*(aort[13]+log((x[13]+1e-100))+logPratio); result += x[14]*(aort[14]+log((x[14]+1e-100))+logPratio); result += x[15]*(aort[15]+log((x[15]+1e-100))+logPratio); result += x[16]*(aort[16]+log((x[16]+1e-100))+logPratio); result += x[17]*(aort[17]+log((x[17]+1e-100))+logPratio); result += x[18]*(aort[18]+log((x[18]+1e-100))+logPratio); /*Scale by RT/W */ *abms = result * RT * YOW; } /*compute the production rate for each species */ /* void CKWC(double * restrict T, double * restrict C, int * iwrk, double * restrict rwrk, double * restrict wdot) */ /* { */ /* int id; /\*loop counter *\/ */ /* /\*convert to SI *\/ */ /* for (id = 0; id < 19; ++id) { */ /* C[id] *= 1.0e6; */ /* } */ /* /\*convert to chemkin units *\/ */ /* productionRate(wdot, C, *T); */ /* /\*convert to chemkin units *\/ */ /* for (id = 0; id < 19; ++id) { */ /* C[id] *= 1.0e-6; */ /* wdot[id] *= 1.0e-6; */ /* } */ /* } */ /*Returns the molar production rate of species */ /*Given P, T, and mass fractions */ void CKWYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double YOW = 0; double PWORT; /*Compute inverse of mean molecular wt first */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ /*PW/RT (see Eq. 7) */ PWORT = (*P)/(YOW * 8.31451e+07 * (*T)); /*multiply by 1e6 so c goes to SI */ PWORT *= 1e6; /*Now compute conversion (and go to SI) */ c[0] = PWORT * y[0]*imw[0]; c[1] = PWORT * y[1]*imw[1]; c[2] = PWORT * y[2]*imw[2]; c[3] = PWORT * y[3]*imw[3]; c[4] = PWORT * y[4]*imw[4]; c[5] = PWORT * y[5]*imw[5]; c[6] = PWORT * y[6]*imw[6]; c[7] = PWORT * y[7]*imw[7]; c[8] = PWORT * y[8]*imw[8]; c[9] = PWORT * y[9]*imw[9]; c[10] = PWORT * y[10]*imw[10]; c[11] = PWORT * y[11]*imw[11]; c[12] = PWORT * y[12]*imw[12]; c[13] = PWORT * y[13]*imw[13]; c[14] = PWORT * y[14]*imw[14]; c[15] = PWORT * y[15]*imw[15]; c[16] = PWORT * y[16]*imw[16]; c[17] = PWORT * y[17]*imw[17]; c[18] = PWORT * y[18]*imw[18]; /*convert to chemkin units */ productionRate(wdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { wdot[id] *= 1.0e-6; } } /*Returns the molar production rate of species */ /*Given P, T, and mole fractions */ void CKWXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double PORT = 1e6 * (*P)/(8.31451e+07 * (*T)); /*1e6 * P/RT so c goes to SI units */ /*Compute conversion, see Eq 10 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*PORT; } /*convert to chemkin units */ productionRate(wdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { wdot[id] *= 1.0e-6; } } /*Returns the molar production rate of species */ /*Given rho, T, and mass fractions */ void CKWYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict wdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ /*See Eq 8 with an extra 1e6 so c goes to SI */ c[0] = 1e6 * (*rho) * y[0]*imw[0]; c[1] = 1e6 * (*rho) * y[1]*imw[1]; c[2] = 1e6 * (*rho) * y[2]*imw[2]; c[3] = 1e6 * (*rho) * y[3]*imw[3]; c[4] = 1e6 * (*rho) * y[4]*imw[4]; c[5] = 1e6 * (*rho) * y[5]*imw[5]; c[6] = 1e6 * (*rho) * y[6]*imw[6]; c[7] = 1e6 * (*rho) * y[7]*imw[7]; c[8] = 1e6 * (*rho) * y[8]*imw[8]; c[9] = 1e6 * (*rho) * y[9]*imw[9]; c[10] = 1e6 * (*rho) * y[10]*imw[10]; c[11] = 1e6 * (*rho) * y[11]*imw[11]; c[12] = 1e6 * (*rho) * y[12]*imw[12]; c[13] = 1e6 * (*rho) * y[13]*imw[13]; c[14] = 1e6 * (*rho) * y[14]*imw[14]; c[15] = 1e6 * (*rho) * y[15]*imw[15]; c[16] = 1e6 * (*rho) * y[16]*imw[16]; c[17] = 1e6 * (*rho) * y[17]*imw[17]; c[18] = 1e6 * (*rho) * y[18]*imw[18]; /*call productionRate */ productionRate(wdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { wdot[id] *= 1.0e-6; } } /*Returns the molar production rate of species */ /*Given rho, T, and mass fractions */ void VCKWYR(int * restrict np, double * restrict rho, double * restrict T, double * restrict y, int * restrict iwrk, double * restrict rwrk, double * restrict wdot) { double c[19*(*np)]; /*temporary storage */ /*See Eq 8 with an extra 1e6 so c goes to SI */ for (int n=0; n<19; n++) { for (int i=0; i<(*np); i++) { c[n*(*np)+i] = 1.0e6 * rho[i] * y[n*(*np)+i] * imw[n]; } } /*call productionRate */ vproductionRate(*np, wdot, c, T); /*convert to chemkin units */ for (int i=0; i<19*(*np); i++) { wdot[i] *= 1.0e-6; } } /*Returns the molar production rate of species */ /*Given rho, T, and mole fractions */ void CKWXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict wdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double XW = 0; /*See Eq 4, 11 in CK Manual */ double ROW; /*Compute mean molecular wt first */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ /*Extra 1e6 factor to take c to SI */ ROW = 1e6*(*rho) / XW; /*Compute conversion, see Eq 11 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*ROW; } /*convert to chemkin units */ productionRate(wdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { wdot[id] *= 1.0e-6; } } /*Returns the rate of progress for each reaction */ void CKQC(double * restrict T, double * restrict C, int * iwrk, double * restrict rwrk, double * restrict qdot) { int id; /*loop counter */ /*convert to SI */ for (id = 0; id < 19; ++id) { C[id] *= 1.0e6; } /*convert to chemkin units */ progressRate(qdot, C, *T); /*convert to chemkin units */ for (id = 0; id < 19; ++id) { C[id] *= 1.0e-6; } for (id = 0; id < 0; ++id) { qdot[id] *= 1.0e-6; } } /*Returns the progress rates of each reactions */ /*Given P, T, and mole fractions */ void CKKFKR(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict q_f, double * restrict q_r) { int id; /*loop counter */ double c[19]; /*temporary storage */ double PORT = 1e6 * (*P)/(8.31451e+07 * (*T)); /*1e6 * P/RT so c goes to SI units */ /*Compute conversion, see Eq 10 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*PORT; } /*convert to chemkin units */ progressRateFR(q_f, q_r, c, *T); /*convert to chemkin units */ for (id = 0; id < 0; ++id) { q_f[id] *= 1.0e-6; q_r[id] *= 1.0e-6; } } /*Returns the progress rates of each reactions */ /*Given P, T, and mass fractions */ void CKQYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict qdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double YOW = 0; double PWORT; /*Compute inverse of mean molecular wt first */ YOW += y[0]*imw[0]; /*H2 */ YOW += y[1]*imw[1]; /*H */ YOW += y[2]*imw[2]; /*O2 */ YOW += y[3]*imw[3]; /*OH */ YOW += y[4]*imw[4]; /*H2O */ YOW += y[5]*imw[5]; /*HO2 */ YOW += y[6]*imw[6]; /*H2O2 */ YOW += y[7]*imw[7]; /*CH3 */ YOW += y[8]*imw[8]; /*CH4 */ YOW += y[9]*imw[9]; /*CO */ YOW += y[10]*imw[10]; /*CO2 */ YOW += y[11]*imw[11]; /*CH2O */ YOW += y[12]*imw[12]; /*C2H2 */ YOW += y[13]*imw[13]; /*C2H4 */ YOW += y[14]*imw[14]; /*C2H6 */ YOW += y[15]*imw[15]; /*NH3 */ YOW += y[16]*imw[16]; /*NO */ YOW += y[17]*imw[17]; /*HCN */ YOW += y[18]*imw[18]; /*N2 */ /*PW/RT (see Eq. 7) */ PWORT = (*P)/(YOW * 8.31451e+07 * (*T)); /*multiply by 1e6 so c goes to SI */ PWORT *= 1e6; /*Now compute conversion (and go to SI) */ c[0] = PWORT * y[0]*imw[0]; c[1] = PWORT * y[1]*imw[1]; c[2] = PWORT * y[2]*imw[2]; c[3] = PWORT * y[3]*imw[3]; c[4] = PWORT * y[4]*imw[4]; c[5] = PWORT * y[5]*imw[5]; c[6] = PWORT * y[6]*imw[6]; c[7] = PWORT * y[7]*imw[7]; c[8] = PWORT * y[8]*imw[8]; c[9] = PWORT * y[9]*imw[9]; c[10] = PWORT * y[10]*imw[10]; c[11] = PWORT * y[11]*imw[11]; c[12] = PWORT * y[12]*imw[12]; c[13] = PWORT * y[13]*imw[13]; c[14] = PWORT * y[14]*imw[14]; c[15] = PWORT * y[15]*imw[15]; c[16] = PWORT * y[16]*imw[16]; c[17] = PWORT * y[17]*imw[17]; c[18] = PWORT * y[18]*imw[18]; /*convert to chemkin units */ progressRate(qdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 0; ++id) { qdot[id] *= 1.0e-6; } } /*Returns the progress rates of each reactions */ /*Given P, T, and mole fractions */ void CKQXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict qdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double PORT = 1e6 * (*P)/(8.31451e+07 * (*T)); /*1e6 * P/RT so c goes to SI units */ /*Compute conversion, see Eq 10 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*PORT; } /*convert to chemkin units */ progressRate(qdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 0; ++id) { qdot[id] *= 1.0e-6; } } /*Returns the progress rates of each reactions */ /*Given rho, T, and mass fractions */ void CKQYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict qdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ /*See Eq 8 with an extra 1e6 so c goes to SI */ c[0] = 1e6 * (*rho) * y[0]*imw[0]; c[1] = 1e6 * (*rho) * y[1]*imw[1]; c[2] = 1e6 * (*rho) * y[2]*imw[2]; c[3] = 1e6 * (*rho) * y[3]*imw[3]; c[4] = 1e6 * (*rho) * y[4]*imw[4]; c[5] = 1e6 * (*rho) * y[5]*imw[5]; c[6] = 1e6 * (*rho) * y[6]*imw[6]; c[7] = 1e6 * (*rho) * y[7]*imw[7]; c[8] = 1e6 * (*rho) * y[8]*imw[8]; c[9] = 1e6 * (*rho) * y[9]*imw[9]; c[10] = 1e6 * (*rho) * y[10]*imw[10]; c[11] = 1e6 * (*rho) * y[11]*imw[11]; c[12] = 1e6 * (*rho) * y[12]*imw[12]; c[13] = 1e6 * (*rho) * y[13]*imw[13]; c[14] = 1e6 * (*rho) * y[14]*imw[14]; c[15] = 1e6 * (*rho) * y[15]*imw[15]; c[16] = 1e6 * (*rho) * y[16]*imw[16]; c[17] = 1e6 * (*rho) * y[17]*imw[17]; c[18] = 1e6 * (*rho) * y[18]*imw[18]; /*call progressRate */ progressRate(qdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 0; ++id) { qdot[id] *= 1.0e-6; } } /*Returns the progress rates of each reactions */ /*Given rho, T, and mole fractions */ void CKQXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict qdot) { int id; /*loop counter */ double c[19]; /*temporary storage */ double XW = 0; /*See Eq 4, 11 in CK Manual */ double ROW; /*Compute mean molecular wt first */ XW += x[0]*2.015940; /*H2 */ XW += x[1]*1.007970; /*H */ XW += x[2]*31.998800; /*O2 */ XW += x[3]*17.007370; /*OH */ XW += x[4]*18.015340; /*H2O */ XW += x[5]*33.006770; /*HO2 */ XW += x[6]*34.014740; /*H2O2 */ XW += x[7]*15.035060; /*CH3 */ XW += x[8]*16.043030; /*CH4 */ XW += x[9]*28.010550; /*CO */ XW += x[10]*44.009950; /*CO2 */ XW += x[11]*30.026490; /*CH2O */ XW += x[12]*26.038240; /*C2H2 */ XW += x[13]*28.054180; /*C2H4 */ XW += x[14]*30.070120; /*C2H6 */ XW += x[15]*17.030610; /*NH3 */ XW += x[16]*30.006100; /*NO */ XW += x[17]*27.025820; /*HCN */ XW += x[18]*28.013400; /*N2 */ /*Extra 1e6 factor to take c to SI */ ROW = 1e6*(*rho) / XW; /*Compute conversion, see Eq 11 */ for (id = 0; id < 19; ++id) { c[id] = x[id]*ROW; } /*convert to chemkin units */ progressRate(qdot, c, *T); /*convert to chemkin units */ for (id = 0; id < 0; ++id) { qdot[id] *= 1.0e-6; } } /*Returns the stoichiometric coefficients */ /*of the reaction mechanism. (Eq 50) */ void CKNU(int * kdim, int * iwrk, double * restrict rwrk, int * nuki) { int id; /*loop counter */ int kd = (*kdim); /*Zero nuki */ for (id = 0; id < 19 * kd; ++ id) { nuki[id] = 0; } } /*Returns the elemental composition */ /*of the speciesi (mdim is num of elements) */ void CKNCF(int * mdim, int * iwrk, double * restrict rwrk, int * ncf) { int id; /*loop counter */ int kd = (*mdim); /*Zero ncf */ for (id = 0; id < kd * 19; ++ id) { ncf[id] = 0; } /*H2 */ ncf[ 0 * kd + 1 ] = 2; /*H */ /*H */ ncf[ 1 * kd + 1 ] = 1; /*H */ /*O2 */ ncf[ 2 * kd + 0 ] = 2; /*O */ /*OH */ ncf[ 3 * kd + 0 ] = 1; /*O */ ncf[ 3 * kd + 1 ] = 1; /*H */ /*H2O */ ncf[ 4 * kd + 1 ] = 2; /*H */ ncf[ 4 * kd + 0 ] = 1; /*O */ /*HO2 */ ncf[ 5 * kd + 1 ] = 1; /*H */ ncf[ 5 * kd + 0 ] = 2; /*O */ /*H2O2 */ ncf[ 6 * kd + 1 ] = 2; /*H */ ncf[ 6 * kd + 0 ] = 2; /*O */ /*CH3 */ ncf[ 7 * kd + 2 ] = 1; /*C */ ncf[ 7 * kd + 1 ] = 3; /*H */ /*CH4 */ ncf[ 8 * kd + 2 ] = 1; /*C */ ncf[ 8 * kd + 1 ] = 4; /*H */ /*CO */ ncf[ 9 * kd + 2 ] = 1; /*C */ ncf[ 9 * kd + 0 ] = 1; /*O */ /*CO2 */ ncf[ 10 * kd + 2 ] = 1; /*C */ ncf[ 10 * kd + 0 ] = 2; /*O */ /*CH2O */ ncf[ 11 * kd + 1 ] = 2; /*H */ ncf[ 11 * kd + 2 ] = 1; /*C */ ncf[ 11 * kd + 0 ] = 1; /*O */ /*C2H2 */ ncf[ 12 * kd + 2 ] = 2; /*C */ ncf[ 12 * kd + 1 ] = 2; /*H */ /*C2H4 */ ncf[ 13 * kd + 2 ] = 2; /*C */ ncf[ 13 * kd + 1 ] = 4; /*H */ /*C2H6 */ ncf[ 14 * kd + 2 ] = 2; /*C */ ncf[ 14 * kd + 1 ] = 6; /*H */ /*NH3 */ ncf[ 15 * kd + 3 ] = 1; /*N */ ncf[ 15 * kd + 1 ] = 3; /*H */ /*NO */ ncf[ 16 * kd + 3 ] = 1; /*N */ ncf[ 16 * kd + 0 ] = 1; /*O */ /*HCN */ ncf[ 17 * kd + 1 ] = 1; /*H */ ncf[ 17 * kd + 2 ] = 1; /*C */ ncf[ 17 * kd + 3 ] = 1; /*N */ /*N2 */ ncf[ 18 * kd + 3 ] = 2; /*N */ } /*Returns the arrehenius coefficients */ /*for all reactions */ void CKABE(int * iwrk, double * restrict rwrk, double * restrict a, double * restrict b, double * restrict e) { for (int i=0; i<0; ++i) { a[i] = fwd_A[i]; b[i] = fwd_beta[i]; e[i] = fwd_Ea[i]; } return; } /*Returns the equil constants for each reaction */ void CKEQC(double * restrict T, double * restrict C, int * iwrk, double * restrict rwrk, double * restrict eqcon) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double gort[19]; /* temporary storage */ /*compute the Gibbs free energy */ gibbs(gort, tc); /*compute the equilibrium constants */ equilibriumConstants(eqcon, gort, tT); } /*Returns the equil constants for each reaction */ /*Given P, T, and mass fractions */ void CKEQYP(double * restrict P, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict eqcon) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double gort[19]; /* temporary storage */ /*compute the Gibbs free energy */ gibbs(gort, tc); /*compute the equilibrium constants */ equilibriumConstants(eqcon, gort, tT); } /*Returns the equil constants for each reaction */ /*Given P, T, and mole fractions */ void CKEQXP(double * restrict P, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict eqcon) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double gort[19]; /* temporary storage */ /*compute the Gibbs free energy */ gibbs(gort, tc); /*compute the equilibrium constants */ equilibriumConstants(eqcon, gort, tT); } /*Returns the equil constants for each reaction */ /*Given rho, T, and mass fractions */ void CKEQYR(double * restrict rho, double * restrict T, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict eqcon) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double gort[19]; /* temporary storage */ /*compute the Gibbs free energy */ gibbs(gort, tc); /*compute the equilibrium constants */ equilibriumConstants(eqcon, gort, tT); } /*Returns the equil constants for each reaction */ /*Given rho, T, and mole fractions */ void CKEQXR(double * restrict rho, double * restrict T, double * restrict x, int * iwrk, double * restrict rwrk, double * restrict eqcon) { double tT = *T; /*temporary temperature */ double tc[] = { log(tT), tT, tT*tT, tT*tT*tT, tT*tT*tT*tT }; /*temperature cache */ double gort[19]; /* temporary storage */ /*compute the Gibbs free energy */ gibbs(gort, tc); /*compute the equilibrium constants */ equilibriumConstants(eqcon, gort, tT); } static double T_save = -1; #ifdef _OPENMP #pragma omp threadprivate(T_save) #endif static double k_f_save[0]; #ifdef _OPENMP #pragma omp threadprivate(k_f_save) #endif static double Kc_save[0]; #ifdef _OPENMP #pragma omp threadprivate(Kc_save) #endif /*compute the production rate for each species */ void productionRate(double * restrict wdot, double * restrict sc, double T) { double tc[] = { log(T), T, T*T, T*T*T, T*T*T*T }; /*temperature cache */ double invT = 1.0 / tc[1]; if (T != T_save) { T_save = T; comp_k_f(tc,invT,k_f_save); comp_Kc(tc,invT,Kc_save); } double qdot, q_f[0], q_r[0]; comp_qfqr(q_f, q_r, sc, tc, invT); for (int i = 0; i < 19; ++i) { wdot[i] = 0.0; } return; } void comp_k_f(double * restrict tc, double invT, double * restrict k_f) { #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<0; ++i) { k_f[i] = prefactor_units[i] * fwd_A[i] * exp(fwd_beta[i] * tc[0] - activation_units[i] * fwd_Ea[i] * invT); }; return; } void comp_Kc(double * restrict tc, double invT, double * restrict Kc) { /*compute the Gibbs free energy */ double g_RT[19]; gibbs(g_RT, tc); #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<0; ++i) { Kc[i] = exp(Kc[i]); }; /*reference concentration: P_atm / (RT) in inverse mol/m^3 */ double refC = 101325 / 8.31451 * invT; double refCinv = 1 / refC; return; } void comp_qfqr(double * restrict qf, double * restrict qr, double * restrict sc, double * restrict tc, double invT) { double T = tc[1]; /*compute the mixture concentration */ double mixture = 0.0; for (int i = 0; i < 19; ++i) { mixture += sc[i]; } double Corr[0]; for (int i = 0; i < 0; ++i) { Corr[i] = 1.0; } for (int i=0; i<0; i++) { qf[i] *= Corr[i] * k_f_save[i]; qr[i] *= Corr[i] * k_f_save[i] / Kc_save[i]; } return; } /*compute the production rate for each species */ void vproductionRate(int npt, double * restrict wdot, double * restrict sc, double * restrict T) { double k_f_s[0*npt], Kc_s[0*npt], mixture[npt], g_RT[19*npt]; double tc[5*npt], invT[npt]; #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<npt; i++) { tc[0*npt+i] = log(T[i]); tc[1*npt+i] = T[i]; tc[2*npt+i] = T[i]*T[i]; tc[3*npt+i] = T[i]*T[i]*T[i]; tc[4*npt+i] = T[i]*T[i]*T[i]*T[i]; invT[i] = 1.0 / T[i]; } for (int i=0; i<npt; i++) { mixture[i] = 0.0; } for (int n=0; n<19; n++) { for (int i=0; i<npt; i++) { mixture[i] += sc[n*npt+i]; wdot[n*npt+i] = 0.0; } } vcomp_k_f(npt, k_f_s, tc, invT); vcomp_gibbs(npt, g_RT, tc); vcomp_Kc(npt, Kc_s, g_RT, invT); vcomp_wdot(npt, wdot, mixture, sc, k_f_s, Kc_s, tc, invT, T); } void vcomp_k_f(int npt, double * restrict k_f_s, double * restrict tc, double * restrict invT) { #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<npt; i++) { } } void vcomp_gibbs(int npt, double * restrict g_RT, double * restrict tc) { /*compute the Gibbs free energy */ for (int i=0; i<npt; i++) { double tg[5], g[19]; tg[0] = tc[0*npt+i]; tg[1] = tc[1*npt+i]; tg[2] = tc[2*npt+i]; tg[3] = tc[3*npt+i]; tg[4] = tc[4*npt+i]; gibbs(g, tg); g_RT[0*npt+i] = g[0]; g_RT[1*npt+i] = g[1]; g_RT[2*npt+i] = g[2]; g_RT[3*npt+i] = g[3]; g_RT[4*npt+i] = g[4]; g_RT[5*npt+i] = g[5]; g_RT[6*npt+i] = g[6]; g_RT[7*npt+i] = g[7]; g_RT[8*npt+i] = g[8]; g_RT[9*npt+i] = g[9]; g_RT[10*npt+i] = g[10]; g_RT[11*npt+i] = g[11]; g_RT[12*npt+i] = g[12]; g_RT[13*npt+i] = g[13]; g_RT[14*npt+i] = g[14]; g_RT[15*npt+i] = g[15]; g_RT[16*npt+i] = g[16]; g_RT[17*npt+i] = g[17]; g_RT[18*npt+i] = g[18]; } } void vcomp_Kc(int npt, double * restrict Kc_s, double * restrict g_RT, double * restrict invT) { #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<npt; i++) { /*reference concentration: P_atm / (RT) in inverse mol/m^3 */ double refC = (101325. / 8.31451) * invT[i]; double refCinv = 1.0 / refC; } } void vcomp_wdot(int npt, double * restrict wdot, double * restrict mixture, double * restrict sc, double * restrict k_f_s, double * restrict Kc_s, double * restrict tc, double * restrict invT, double * restrict T) { #ifdef __INTEL_COMPILER #pragma simd #endif for (int i=0; i<npt; i++) { double qdot, q_f, q_r, phi_f, phi_r, k_f, k_r, Kc; } } /*compute the reaction Jacobian */ void DWDOT(double * restrict J, double * restrict sc, double * restrict Tp, int * consP) { double c[19]; for (int k=0; k<19; k++) { c[k] = 1.e6 * sc[k]; } aJacobian(J, c, *Tp, *consP); /* dwdot[k]/dT */ for (int k=0; k<19; k++) { J[380+k] *= 1.e-6; } /* dTdot/d[X] */ for (int k=0; k<19; k++) { J[k*20+19] *= 1.e6; } return; } /*compute the reaction Jacobian */ void aJacobian(double * restrict J, double * restrict sc, double T, int consP) { for (int i=0; i<400; i++) { J[i] = 0.0; } double wdot[19]; for (int k=0; k<19; k++) { wdot[k] = 0.0; } double tc[] = { log(T), T, T*T, T*T*T, T*T*T*T }; /*temperature cache */ double invT = 1.0 / tc[1]; double invT2 = invT * invT; /*reference concentration: P_atm / (RT) in inverse mol/m^3 */ double refC = 101325 / 8.31451 / T; double refCinv = 1.0 / refC; /*compute the mixture concentration */ double mixture = 0.0; for (int k = 0; k < 19; ++k) { mixture += sc[k]; } /*compute the Gibbs free energy */ double g_RT[19]; gibbs(g_RT, tc); /*compute the species enthalpy */ double h_RT[19]; speciesEnthalpy(h_RT, tc); double phi_f, k_f, k_r, phi_r, Kc, q, q_nocor, Corr, alpha; double dlnkfdT, dlnk0dT, dlnKcdT, dkrdT, dqdT; double dqdci, dcdc_fac, dqdc[19]; double Pr, fPr, F, k_0, logPr; double logFcent, troe_c, troe_n, troePr_den, troePr, troe; double Fcent1, Fcent2, Fcent3, Fcent; double dlogFdc, dlogFdn, dlogFdcn_fac; double dlogPrdT, dlogfPrdT, dlogFdT, dlogFcentdT, dlogFdlogPr, dlnCorrdT; const double ln10 = log(10.0); const double log10e = 1.0/log(10.0); double c_R[19], dcRdT[19], e_RT[19]; double * eh_RT; if (consP) { cp_R(c_R, tc); dcvpRdT(dcRdT, tc); eh_RT = &h_RT[0]; } else { cv_R(c_R, tc); dcvpRdT(dcRdT, tc); speciesInternalEnergy(e_RT, tc); eh_RT = &e_RT[0]; } double cmix = 0.0, ehmix = 0.0, dcmixdT=0.0, dehmixdT=0.0; for (int k = 0; k < 19; ++k) { cmix += c_R[k]*sc[k]; dcmixdT += dcRdT[k]*sc[k]; ehmix += eh_RT[k]*wdot[k]; dehmixdT += invT*(c_R[k]-eh_RT[k])*wdot[k] + eh_RT[k]*J[380+k]; } double cmixinv = 1.0/cmix; double tmp1 = ehmix*cmixinv; double tmp3 = cmixinv*T; double tmp2 = tmp1*tmp3; double dehmixdc; /* dTdot/d[X] */ for (int k = 0; k < 19; ++k) { dehmixdc = 0.0; for (int m = 0; m < 19; ++m) { dehmixdc += eh_RT[m]*J[k*20+m]; } J[k*20+19] = tmp2*c_R[k] - tmp3*dehmixdc; } /* dTdot/dT */ J[399] = -tmp1 + tmp2*dcmixdT - tmp3*dehmixdT; } /*compute d(Cp/R)/dT and d(Cv/R)/dT at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void dcvpRdT(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +7.98052075e-03 -3.89563020e-05 * tc[1] +6.04716282e-08 * tc[2] -2.95044704e-11 * tc[3]; /*species 1: H */ species[1] = +7.05332819e-13 -3.99183928e-15 * tc[1] +6.90244896e-18 * tc[2] -3.71092933e-21 * tc[3]; /*species 2: O2 */ species[2] = -2.99673416e-03 +1.96946040e-05 * tc[1] -2.90438853e-08 * tc[2] +1.29749135e-11 * tc[3]; /*species 3: OH */ species[3] = -2.40131752e-03 +9.23587682e-06 * tc[1] -1.16434000e-08 * tc[2] +5.45645880e-12 * tc[3]; /*species 4: H2O */ species[4] = -2.03643410e-03 +1.30408042e-05 * tc[1] -1.64639119e-08 * tc[2] +7.08791268e-12 * tc[3]; /*species 5: HO2 */ species[5] = -4.74912051e-03 +4.23165782e-05 * tc[1] -7.28291682e-08 * tc[2] +3.71690050e-11 * tc[3]; /*species 6: H2O2 */ species[6] = -5.42822417e-04 +3.34671402e-05 * tc[1] -6.47312439e-08 * tc[2] +3.44981745e-11 * tc[3]; /*species 7: CH3 */ species[7] = +2.01095175e-03 +1.14604371e-05 * tc[1] -2.06135228e-08 * tc[2] +1.01754294e-11 * tc[3]; /*species 8: CH4 */ species[8] = -1.36709788e-02 +9.83601198e-05 * tc[1] -1.45422908e-07 * tc[2] +6.66775824e-11 * tc[3]; /*species 9: CO */ species[9] = -6.10353680e-04 +2.03362866e-06 * tc[1] +2.72101765e-09 * tc[2] -3.61769800e-12 * tc[3]; /*species 10: CO2 */ species[10] = +8.98459677e-03 -1.42471254e-05 * tc[1] +7.37757066e-09 * tc[2] -5.74798192e-13 * tc[3]; /*species 11: CH2O */ species[11] = -9.90833369e-03 +7.46440016e-05 * tc[1] -1.13785578e-07 * tc[2] +5.27090608e-11 * tc[3]; /*species 12: C2H2 */ species[12] = +2.33615629e-02 -7.10343630e-05 * tc[1] +8.40457311e-08 * tc[2] -3.40029190e-11 * tc[3]; /*species 13: C2H4 */ species[13] = -7.57052247e-03 +1.14198058e-04 * tc[1] -2.07476626e-07 * tc[2] +1.07953749e-10 * tc[3]; /*species 14: C2H6 */ species[14] = -5.50154270e-03 +1.19887658e-04 * tc[1] -2.12539886e-07 * tc[2] +1.07474308e-10 * tc[3]; /*species 15: NH3 */ species[15] = -4.66052300e-03 +4.34370260e-05 * tc[1] -6.84266610e-08 * tc[2] +3.30552184e-11 * tc[3]; /*species 16: NO */ species[16] = -4.63897600e-03 +2.20820440e-05 * tc[1] -2.80084062e-08 * tc[2] +1.12143080e-11 * tc[3]; /*species 17: HCN */ species[17] = +1.00511700e-02 -2.67035260e-05 * tc[1] +3.02770470e-08 * tc[2] -1.20356112e-11 * tc[3]; /*species 18: N2 */ species[18] = +1.40824040e-03 -7.92644400e-06 * tc[1] +1.69245450e-08 * tc[2] -9.77941600e-12 * tc[3]; } else { /*species 0: H2 */ species[0] = -4.94024731e-05 +9.98913556e-07 * tc[1] -5.38699182e-10 * tc[2] +8.01021504e-14 * tc[3]; /*species 1: H */ species[1] = -2.30842973e-11 +3.23123896e-14 * tc[1] -1.42054571e-17 * tc[2] +1.99278943e-21 * tc[3]; /*species 2: O2 */ species[2] = +1.48308754e-03 -1.51593334e-06 * tc[1] +6.28411665e-10 * tc[2] -8.66871176e-14 * tc[3]; /*species 3: OH */ species[3] = +5.48429716e-04 +2.53010456e-07 * tc[1] -2.63838467e-10 * tc[2] +4.69649504e-14 * tc[3]; /*species 4: H2O */ species[4] = +2.17691804e-03 -3.28145036e-07 * tc[1] -2.91125961e-10 * tc[2] +6.72803968e-14 * tc[3]; /*species 5: HO2 */ species[5] = +2.23982013e-03 -1.26731630e-06 * tc[1] +3.42739110e-10 * tc[2] -4.31634140e-14 * tc[3]; /*species 6: H2O2 */ species[6] = +4.90831694e-03 -3.80278450e-06 * tc[1] +1.11355796e-09 * tc[2] -1.15163322e-13 * tc[3]; /*species 7: CH3 */ species[7] = +7.23990037e-03 -5.97428696e-06 * tc[1] +1.78705393e-09 * tc[2] -1.86861758e-13 * tc[3]; /*species 8: CH4 */ species[8] = +1.33909467e-02 -1.14657162e-05 * tc[1] +3.66877605e-09 * tc[2] -4.07260920e-13 * tc[3]; /*species 9: CO */ species[9] = +2.06252743e-03 -1.99765154e-06 * tc[1] +6.90159024e-10 * tc[2] -8.14590864e-14 * tc[3]; /*species 10: CO2 */ species[10] = +4.41437026e-03 -4.42962808e-06 * tc[1] +1.57047056e-09 * tc[2] -1.88833666e-13 * tc[3]; /*species 11: CH2O */ species[11] = +9.20000082e-03 -8.84517626e-06 * tc[1] +3.01923636e-09 * tc[2] -3.53542256e-13 * tc[3]; /*species 12: C2H2 */ species[12] = +5.96166664e-03 -4.74589704e-06 * tc[1] +1.40223651e-09 * tc[2] -1.44494085e-13 * tc[3]; /*species 13: C2H4 */ species[13] = +1.46454151e-02 -1.34215583e-05 * tc[1] +4.41668769e-09 * tc[2] -5.02824244e-13 * tc[3]; /*species 14: C2H6 */ species[14] = +2.16852677e-02 -2.00512134e-05 * tc[1] +6.64236003e-09 * tc[2] -7.60011560e-13 * tc[3]; /*species 15: NH3 */ species[15] = +5.66625600e-03 -3.45573520e-06 * tc[1] +7.16014830e-10 * tc[2] -5.03151440e-14 * tc[3]; /*species 16: NO */ species[16] = +1.19110430e-03 -8.58340960e-07 * tc[1] +2.08373007e-10 * tc[2] -1.61344396e-14 * tc[3]; /*species 17: HCN */ species[17] = +3.14642280e-03 -2.12643700e-06 * tc[1] +4.98592710e-10 * tc[2] -3.91990280e-14 * tc[3]; /*species 18: N2 */ species[18] = +1.48797680e-03 -1.13695200e-06 * tc[1] +3.02911140e-10 * tc[2] -2.70134040e-14 * tc[3]; } return; } /*compute the progress rate for each reaction */ void progressRate(double * restrict qdot, double * restrict sc, double T) { double tc[] = { log(T), T, T*T, T*T*T, T*T*T*T }; /*temperature cache */ double invT = 1.0 / tc[1]; if (T != T_save) { T_save = T; comp_k_f(tc,invT,k_f_save); comp_Kc(tc,invT,Kc_save); } double q_f[0], q_r[0]; comp_qfqr(q_f, q_r, sc, tc, invT); for (int i = 0; i < 0; ++i) { qdot[i] = q_f[i] - q_r[i]; } return; } /*compute the progress rate for each reaction */ void progressRateFR(double * restrict q_f, double * restrict q_r, double * restrict sc, double T) { double tc[] = { log(T), T, T*T, T*T*T, T*T*T*T }; /*temperature cache */ double invT = 1.0 / tc[1]; if (T != T_save) { T_save = T; comp_k_f(tc,invT,k_f_save); comp_Kc(tc,invT,Kc_save); } comp_qfqr(q_f, q_r, sc, tc, invT); return; } /*compute the equilibrium constants for each reaction */ void equilibriumConstants(double * restrict kc, double * restrict g_RT, double T) { /*reference concentration: P_atm / (RT) in inverse mol/m^3 */ double refC = 101325 / 8.31451 / T; return; } /*compute the g/(RT) at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void gibbs(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; double invT = 1 / T; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = -9.179351730000000e+02 * invT +1.661320882000000e+00 -2.344331120000000e+00 * tc[0] -3.990260375000000e-03 * tc[1] +3.246358500000000e-06 * tc[2] -1.679767450000000e-09 * tc[3] +3.688058805000000e-13 * tc[4]; /*species 1: H */ species[1] = +2.547365990000000e+04 * invT +2.946682853000000e+00 -2.500000000000000e+00 * tc[0] -3.526664095000000e-13 * tc[1] +3.326532733333333e-16 * tc[2] -1.917346933333333e-19 * tc[3] +4.638661660000000e-23 * tc[4]; /*species 2: O2 */ species[2] = -1.063943560000000e+03 * invT +1.247806300000001e-01 -3.782456360000000e+00 * tc[0] +1.498367080000000e-03 * tc[1] -1.641217001666667e-06 * tc[2] +8.067745908333334e-10 * tc[3] -1.621864185000000e-13 * tc[4]; /*species 3: OH */ species[3] = +3.615080560000000e+03 * invT +4.095940888000000e+00 -3.992015430000000e+00 * tc[0] +1.200658760000000e-03 * tc[1] -7.696564016666666e-07 * tc[2] +3.234277775000000e-10 * tc[3] -6.820573500000000e-14 * tc[4]; /*species 4: H2O */ species[4] = -3.029372670000000e+04 * invT +5.047672768000000e+00 -4.198640560000000e+00 * tc[0] +1.018217050000000e-03 * tc[1] -1.086733685000000e-06 * tc[2] +4.573308850000000e-10 * tc[3] -8.859890850000000e-14 * tc[4]; /*species 5: HO2 */ species[5] = +2.948080400000000e+02 * invT +5.851355599999999e-01 -4.301798010000000e+00 * tc[0] +2.374560255000000e-03 * tc[1] -3.526381516666666e-06 * tc[2] +2.023032450000000e-09 * tc[3] -4.646125620000001e-13 * tc[4]; /*species 6: H2O2 */ species[6] = -1.770258210000000e+04 * invT +8.410619499999998e-01 -4.276112690000000e+00 * tc[0] +2.714112085000000e-04 * tc[1] -2.788928350000000e-06 * tc[2] +1.798090108333333e-09 * tc[3] -4.312271815000000e-13 * tc[4]; /*species 7: CH3 */ species[7] = +1.644499880000000e+04 * invT +2.069026070000000e+00 -3.673590400000000e+00 * tc[0] -1.005475875000000e-03 * tc[1] -9.550364266666668e-07 * tc[2] +5.725978541666666e-10 * tc[3] -1.271928670000000e-13 * tc[4]; /*species 8: CH4 */ species[8] = -1.024664760000000e+04 * invT +9.791179889999999e+00 -5.149876130000000e+00 * tc[0] +6.835489400000000e-03 * tc[1] -8.196676650000000e-06 * tc[2] +4.039525216666667e-09 * tc[3] -8.334697800000000e-13 * tc[4]; /*species 9: CO */ species[9] = -1.434408600000000e+04 * invT +7.112418999999992e-02 -3.579533470000000e+00 * tc[0] +3.051768400000000e-04 * tc[1] -1.694690550000000e-07 * tc[2] -7.558382366666667e-11 * tc[3] +4.522122495000000e-14 * tc[4]; /*species 10: CO2 */ species[10] = -4.837196970000000e+04 * invT -7.544278700000000e+00 -2.356773520000000e+00 * tc[0] -4.492298385000000e-03 * tc[1] +1.187260448333333e-06 * tc[2] -2.049325183333333e-10 * tc[3] +7.184977399999999e-15 * tc[4]; /*species 11: CH2O */ species[11] = -1.430895670000000e+04 * invT +4.190910250000000e+00 -4.793723150000000e+00 * tc[0] +4.954166845000000e-03 * tc[1] -6.220333466666666e-06 * tc[2] +3.160710508333333e-09 * tc[3] -6.588632600000000e-13 * tc[4]; /*species 12: C2H2 */ species[12] = +2.642898070000000e+04 * invT -1.313102400600000e+01 -8.086810940000000e-01 * tc[0] -1.168078145000000e-02 * tc[1] +5.919530250000000e-06 * tc[2] -2.334603641666667e-09 * tc[3] +4.250364870000000e-13 * tc[4]; /*species 13: C2H4 */ species[13] = +5.089775930000000e+03 * invT -1.381294799999999e-01 -3.959201480000000e+00 * tc[0] +3.785261235000000e-03 * tc[1] -9.516504866666667e-06 * tc[2] +5.763239608333333e-09 * tc[3] -1.349421865000000e-12 * tc[4]; /*species 14: C2H6 */ species[14] = -1.152220550000000e+04 * invT +1.624601760000000e+00 -4.291424920000000e+00 * tc[0] +2.750771350000000e-03 * tc[1] -9.990638133333334e-06 * tc[2] +5.903885708333334e-09 * tc[3] -1.343428855000000e-12 * tc[4]; /*species 15: NH3 */ species[15] = -6.741728500000000e+03 * invT +4.911400170000000e+00 -4.286027400000000e+00 * tc[0] +2.330261500000000e-03 * tc[1] -3.619752166666667e-06 * tc[2] +1.900740583333333e-09 * tc[3] -4.131902300000000e-13 * tc[4]; /*species 16: NO */ species[16] = +9.844623000000000e+03 * invT +1.937629900000000e+00 -4.218476300000000e+00 * tc[0] +2.319488000000000e-03 * tc[1] -1.840170333333333e-06 * tc[2] +7.780112833333333e-10 * tc[3] -1.401788500000000e-13 * tc[4]; /*species 17: HCN */ species[17] = +1.471263300000000e+04 * invT -6.657453300000000e+00 -2.258988600000000e+00 * tc[0] -5.025585000000000e-03 * tc[1] +2.225293833333333e-06 * tc[2] -8.410290833333334e-10 * tc[3] +1.504451400000000e-13 * tc[4]; /*species 18: N2 */ species[18] = -1.020899900000000e+03 * invT -6.516950000000001e-01 -3.298677000000000e+00 * tc[0] -7.041202000000000e-04 * tc[1] +6.605369999999999e-07 * tc[2] -4.701262500000001e-10 * tc[3] +1.222427000000000e-13 * tc[4]; } else { /*species 0: H2 */ species[0] = -9.501589220000000e+02 * invT +6.542302510000000e+00 -3.337279200000000e+00 * tc[0] +2.470123655000000e-05 * tc[1] -8.324279633333333e-08 * tc[2] +1.496386616666667e-11 * tc[3] -1.001276880000000e-15 * tc[4]; /*species 1: H */ species[1] = +2.547365990000000e+04 * invT +2.946682924000000e+00 -2.500000010000000e+00 * tc[0] +1.154214865000000e-11 * tc[1] -2.692699133333334e-15 * tc[2] +3.945960291666667e-19 * tc[3] -2.490986785000000e-23 * tc[4]; /*species 2: O2 */ species[2] = -1.088457720000000e+03 * invT -2.170693450000000e+00 -3.282537840000000e+00 * tc[0] -7.415437700000000e-04 * tc[1] +1.263277781666667e-07 * tc[2] -1.745587958333333e-11 * tc[3] +1.083588970000000e-15 * tc[4]; /*species 3: OH */ species[3] = +3.858657000000000e+03 * invT -1.383808430000000e+00 -3.092887670000000e+00 * tc[0] -2.742148580000000e-04 * tc[1] -2.108420466666667e-08 * tc[2] +7.328846300000000e-12 * tc[3] -5.870618800000000e-16 * tc[4]; /*species 4: H2O */ species[4] = -3.000429710000000e+04 * invT -1.932777610000000e+00 -3.033992490000000e+00 * tc[0] -1.088459020000000e-03 * tc[1] +2.734541966666666e-08 * tc[2] +8.086832250000000e-12 * tc[3] -8.410049600000000e-16 * tc[4]; /*species 5: HO2 */ species[5] = +1.118567130000000e+02 * invT +2.321087500000001e-01 -4.017210900000000e+00 * tc[0] -1.119910065000000e-03 * tc[1] +1.056096916666667e-07 * tc[2] -9.520530833333334e-12 * tc[3] +5.395426750000000e-16 * tc[4]; /*species 6: H2O2 */ species[6] = -1.786178770000000e+04 * invT +1.248846229999999e+00 -4.165002850000000e+00 * tc[0] -2.454158470000000e-03 * tc[1] +3.168987083333333e-07 * tc[2] -3.093216550000000e-11 * tc[3] +1.439541525000000e-15 * tc[4]; /*species 7: CH3 */ species[7] = +1.677558430000000e+04 * invT -6.194354070000000e+00 -2.285717720000000e+00 * tc[0] -3.619950185000000e-03 * tc[1] +4.978572466666667e-07 * tc[2] -4.964038700000000e-11 * tc[3] +2.335771970000000e-15 * tc[4]; /*species 8: CH4 */ species[8] = -9.468344590000001e+03 * invT -1.836246650500000e+01 -7.485149500000000e-02 * tc[0] -6.695473350000000e-03 * tc[1] +9.554763483333333e-07 * tc[2] -1.019104458333333e-10 * tc[3] +5.090761500000000e-15 * tc[4]; /*species 9: CO */ species[9] = -1.415187240000000e+04 * invT -5.103502110000000e+00 -2.715185610000000e+00 * tc[0] -1.031263715000000e-03 * tc[1] +1.664709618333334e-07 * tc[2] -1.917108400000000e-11 * tc[3] +1.018238580000000e-15 * tc[4]; /*species 10: CO2 */ species[10] = -4.875916600000000e+04 * invT +1.585822230000000e+00 -3.857460290000000e+00 * tc[0] -2.207185130000000e-03 * tc[1] +3.691356733333334e-07 * tc[2] -4.362418233333334e-11 * tc[3] +2.360420820000000e-15 * tc[4]; /*species 11: CH2O */ species[11] = -1.399583230000000e+04 * invT -1.189563292000000e+01 -1.760690080000000e+00 * tc[0] -4.600000410000000e-03 * tc[1] +7.370980216666666e-07 * tc[2] -8.386767666666666e-11 * tc[3] +4.419278200000001e-15 * tc[4]; /*species 12: C2H2 */ species[12] = +2.593599920000000e+04 * invT +5.377850850000001e+00 -4.147569640000000e+00 * tc[0] -2.980833320000000e-03 * tc[1] +3.954914200000000e-07 * tc[2] -3.895101425000000e-11 * tc[3] +1.806176065000000e-15 * tc[4]; /*species 13: C2H4 */ species[13] = +4.939886140000000e+03 * invT -8.269258140000002e+00 -2.036111160000000e+00 * tc[0] -7.322707550000000e-03 * tc[1] +1.118463191666667e-06 * tc[2] -1.226857691666667e-10 * tc[3] +6.285303050000000e-15 * tc[4]; /*species 14: C2H6 */ species[14] = -1.142639320000000e+04 * invT -1.404372920000000e+01 -1.071881500000000e+00 * tc[0] -1.084263385000000e-02 * tc[1] +1.670934450000000e-06 * tc[2] -1.845100008333333e-10 * tc[3] +9.500144500000000e-15 * tc[4]; /*species 15: NH3 */ species[15] = -6.544695800000000e+03 * invT -3.931840700000000e+00 -2.634452100000000e+00 * tc[0] -2.833128000000000e-03 * tc[1] +2.879779333333333e-07 * tc[2] -1.988930083333333e-11 * tc[3] +6.289392999999999e-16 * tc[4]; /*species 16: NO */ species[16] = +9.920974600000000e+03 * invT -3.108697100000001e+00 -3.260605600000000e+00 * tc[0] -5.955521500000000e-04 * tc[1] +7.152841333333333e-08 * tc[2] -5.788139083333334e-12 * tc[3] +2.016804950000000e-16 * tc[4]; /*species 17: HCN */ species[17] = +1.440729200000000e+04 * invT +2.226779100000000e+00 -3.802239200000000e+00 * tc[0] -1.573211400000000e-03 * tc[1] +1.772030833333333e-07 * tc[2] -1.384979750000000e-11 * tc[3] +4.899878500000000e-16 * tc[4]; /*species 18: N2 */ species[18] = -9.227977000000000e+02 * invT -3.053888000000000e+00 -2.926640000000000e+00 * tc[0] -7.439884000000000e-04 * tc[1] +9.474600000000001e-08 * tc[2] -8.414198333333333e-12 * tc[3] +3.376675500000000e-16 * tc[4]; } return; } /*compute the a/(RT) at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void helmholtz(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; double invT = 1 / T; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = -9.17935173e+02 * invT +6.61320882e-01 -2.34433112e+00 * tc[0] -3.99026037e-03 * tc[1] +3.24635850e-06 * tc[2] -1.67976745e-09 * tc[3] +3.68805881e-13 * tc[4]; /*species 1: H */ species[1] = +2.54736599e+04 * invT +1.94668285e+00 -2.50000000e+00 * tc[0] -3.52666409e-13 * tc[1] +3.32653273e-16 * tc[2] -1.91734693e-19 * tc[3] +4.63866166e-23 * tc[4]; /*species 2: O2 */ species[2] = -1.06394356e+03 * invT -8.75219370e-01 -3.78245636e+00 * tc[0] +1.49836708e-03 * tc[1] -1.64121700e-06 * tc[2] +8.06774591e-10 * tc[3] -1.62186418e-13 * tc[4]; /*species 3: OH */ species[3] = +3.61508056e+03 * invT +3.09594089e+00 -3.99201543e+00 * tc[0] +1.20065876e-03 * tc[1] -7.69656402e-07 * tc[2] +3.23427778e-10 * tc[3] -6.82057350e-14 * tc[4]; /*species 4: H2O */ species[4] = -3.02937267e+04 * invT +4.04767277e+00 -4.19864056e+00 * tc[0] +1.01821705e-03 * tc[1] -1.08673369e-06 * tc[2] +4.57330885e-10 * tc[3] -8.85989085e-14 * tc[4]; /*species 5: HO2 */ species[5] = +2.94808040e+02 * invT -4.14864440e-01 -4.30179801e+00 * tc[0] +2.37456025e-03 * tc[1] -3.52638152e-06 * tc[2] +2.02303245e-09 * tc[3] -4.64612562e-13 * tc[4]; /*species 6: H2O2 */ species[6] = -1.77025821e+04 * invT -1.58938050e-01 -4.27611269e+00 * tc[0] +2.71411208e-04 * tc[1] -2.78892835e-06 * tc[2] +1.79809011e-09 * tc[3] -4.31227182e-13 * tc[4]; /*species 7: CH3 */ species[7] = +1.64449988e+04 * invT +1.06902607e+00 -3.67359040e+00 * tc[0] -1.00547588e-03 * tc[1] -9.55036427e-07 * tc[2] +5.72597854e-10 * tc[3] -1.27192867e-13 * tc[4]; /*species 8: CH4 */ species[8] = -1.02466476e+04 * invT +8.79117989e+00 -5.14987613e+00 * tc[0] +6.83548940e-03 * tc[1] -8.19667665e-06 * tc[2] +4.03952522e-09 * tc[3] -8.33469780e-13 * tc[4]; /*species 9: CO */ species[9] = -1.43440860e+04 * invT -9.28875810e-01 -3.57953347e+00 * tc[0] +3.05176840e-04 * tc[1] -1.69469055e-07 * tc[2] -7.55838237e-11 * tc[3] +4.52212249e-14 * tc[4]; /*species 10: CO2 */ species[10] = -4.83719697e+04 * invT -8.54427870e+00 -2.35677352e+00 * tc[0] -4.49229839e-03 * tc[1] +1.18726045e-06 * tc[2] -2.04932518e-10 * tc[3] +7.18497740e-15 * tc[4]; /*species 11: CH2O */ species[11] = -1.43089567e+04 * invT +3.19091025e+00 -4.79372315e+00 * tc[0] +4.95416684e-03 * tc[1] -6.22033347e-06 * tc[2] +3.16071051e-09 * tc[3] -6.58863260e-13 * tc[4]; /*species 12: C2H2 */ species[12] = +2.64289807e+04 * invT -1.41310240e+01 -8.08681094e-01 * tc[0] -1.16807815e-02 * tc[1] +5.91953025e-06 * tc[2] -2.33460364e-09 * tc[3] +4.25036487e-13 * tc[4]; /*species 13: C2H4 */ species[13] = +5.08977593e+03 * invT -1.13812948e+00 -3.95920148e+00 * tc[0] +3.78526124e-03 * tc[1] -9.51650487e-06 * tc[2] +5.76323961e-09 * tc[3] -1.34942187e-12 * tc[4]; /*species 14: C2H6 */ species[14] = -1.15222055e+04 * invT +6.24601760e-01 -4.29142492e+00 * tc[0] +2.75077135e-03 * tc[1] -9.99063813e-06 * tc[2] +5.90388571e-09 * tc[3] -1.34342886e-12 * tc[4]; /*species 15: NH3 */ species[15] = -6.74172850e+03 * invT +3.91140017e+00 -4.28602740e+00 * tc[0] +2.33026150e-03 * tc[1] -3.61975217e-06 * tc[2] +1.90074058e-09 * tc[3] -4.13190230e-13 * tc[4]; /*species 16: NO */ species[16] = +9.84462300e+03 * invT +9.37629900e-01 -4.21847630e+00 * tc[0] +2.31948800e-03 * tc[1] -1.84017033e-06 * tc[2] +7.78011283e-10 * tc[3] -1.40178850e-13 * tc[4]; /*species 17: HCN */ species[17] = +1.47126330e+04 * invT -7.65745330e+00 -2.25898860e+00 * tc[0] -5.02558500e-03 * tc[1] +2.22529383e-06 * tc[2] -8.41029083e-10 * tc[3] +1.50445140e-13 * tc[4]; /*species 18: N2 */ species[18] = -1.02089990e+03 * invT -1.65169500e+00 -3.29867700e+00 * tc[0] -7.04120200e-04 * tc[1] +6.60537000e-07 * tc[2] -4.70126250e-10 * tc[3] +1.22242700e-13 * tc[4]; } else { /*species 0: H2 */ species[0] = -9.50158922e+02 * invT +5.54230251e+00 -3.33727920e+00 * tc[0] +2.47012365e-05 * tc[1] -8.32427963e-08 * tc[2] +1.49638662e-11 * tc[3] -1.00127688e-15 * tc[4]; /*species 1: H */ species[1] = +2.54736599e+04 * invT +1.94668292e+00 -2.50000001e+00 * tc[0] +1.15421486e-11 * tc[1] -2.69269913e-15 * tc[2] +3.94596029e-19 * tc[3] -2.49098679e-23 * tc[4]; /*species 2: O2 */ species[2] = -1.08845772e+03 * invT -3.17069345e+00 -3.28253784e+00 * tc[0] -7.41543770e-04 * tc[1] +1.26327778e-07 * tc[2] -1.74558796e-11 * tc[3] +1.08358897e-15 * tc[4]; /*species 3: OH */ species[3] = +3.85865700e+03 * invT -2.38380843e+00 -3.09288767e+00 * tc[0] -2.74214858e-04 * tc[1] -2.10842047e-08 * tc[2] +7.32884630e-12 * tc[3] -5.87061880e-16 * tc[4]; /*species 4: H2O */ species[4] = -3.00042971e+04 * invT -2.93277761e+00 -3.03399249e+00 * tc[0] -1.08845902e-03 * tc[1] +2.73454197e-08 * tc[2] +8.08683225e-12 * tc[3] -8.41004960e-16 * tc[4]; /*species 5: HO2 */ species[5] = +1.11856713e+02 * invT -7.67891250e-01 -4.01721090e+00 * tc[0] -1.11991006e-03 * tc[1] +1.05609692e-07 * tc[2] -9.52053083e-12 * tc[3] +5.39542675e-16 * tc[4]; /*species 6: H2O2 */ species[6] = -1.78617877e+04 * invT +2.48846230e-01 -4.16500285e+00 * tc[0] -2.45415847e-03 * tc[1] +3.16898708e-07 * tc[2] -3.09321655e-11 * tc[3] +1.43954153e-15 * tc[4]; /*species 7: CH3 */ species[7] = +1.67755843e+04 * invT -7.19435407e+00 -2.28571772e+00 * tc[0] -3.61995018e-03 * tc[1] +4.97857247e-07 * tc[2] -4.96403870e-11 * tc[3] +2.33577197e-15 * tc[4]; /*species 8: CH4 */ species[8] = -9.46834459e+03 * invT -1.93624665e+01 -7.48514950e-02 * tc[0] -6.69547335e-03 * tc[1] +9.55476348e-07 * tc[2] -1.01910446e-10 * tc[3] +5.09076150e-15 * tc[4]; /*species 9: CO */ species[9] = -1.41518724e+04 * invT -6.10350211e+00 -2.71518561e+00 * tc[0] -1.03126372e-03 * tc[1] +1.66470962e-07 * tc[2] -1.91710840e-11 * tc[3] +1.01823858e-15 * tc[4]; /*species 10: CO2 */ species[10] = -4.87591660e+04 * invT +5.85822230e-01 -3.85746029e+00 * tc[0] -2.20718513e-03 * tc[1] +3.69135673e-07 * tc[2] -4.36241823e-11 * tc[3] +2.36042082e-15 * tc[4]; /*species 11: CH2O */ species[11] = -1.39958323e+04 * invT -1.28956329e+01 -1.76069008e+00 * tc[0] -4.60000041e-03 * tc[1] +7.37098022e-07 * tc[2] -8.38676767e-11 * tc[3] +4.41927820e-15 * tc[4]; /*species 12: C2H2 */ species[12] = +2.59359992e+04 * invT +4.37785085e+00 -4.14756964e+00 * tc[0] -2.98083332e-03 * tc[1] +3.95491420e-07 * tc[2] -3.89510143e-11 * tc[3] +1.80617607e-15 * tc[4]; /*species 13: C2H4 */ species[13] = +4.93988614e+03 * invT -9.26925814e+00 -2.03611116e+00 * tc[0] -7.32270755e-03 * tc[1] +1.11846319e-06 * tc[2] -1.22685769e-10 * tc[3] +6.28530305e-15 * tc[4]; /*species 14: C2H6 */ species[14] = -1.14263932e+04 * invT -1.50437292e+01 -1.07188150e+00 * tc[0] -1.08426339e-02 * tc[1] +1.67093445e-06 * tc[2] -1.84510001e-10 * tc[3] +9.50014450e-15 * tc[4]; /*species 15: NH3 */ species[15] = -6.54469580e+03 * invT -4.93184070e+00 -2.63445210e+00 * tc[0] -2.83312800e-03 * tc[1] +2.87977933e-07 * tc[2] -1.98893008e-11 * tc[3] +6.28939300e-16 * tc[4]; /*species 16: NO */ species[16] = +9.92097460e+03 * invT -4.10869710e+00 -3.26060560e+00 * tc[0] -5.95552150e-04 * tc[1] +7.15284133e-08 * tc[2] -5.78813908e-12 * tc[3] +2.01680495e-16 * tc[4]; /*species 17: HCN */ species[17] = +1.44072920e+04 * invT +1.22677910e+00 -3.80223920e+00 * tc[0] -1.57321140e-03 * tc[1] +1.77203083e-07 * tc[2] -1.38497975e-11 * tc[3] +4.89987850e-16 * tc[4]; /*species 18: N2 */ species[18] = -9.22797700e+02 * invT -4.05388800e+00 -2.92664000e+00 * tc[0] -7.43988400e-04 * tc[1] +9.47460000e-08 * tc[2] -8.41419833e-12 * tc[3] +3.37667550e-16 * tc[4]; } return; } /*compute Cv/R at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void cv_R(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +1.34433112e+00 +7.98052075e-03 * tc[1] -1.94781510e-05 * tc[2] +2.01572094e-08 * tc[3] -7.37611761e-12 * tc[4]; /*species 1: H */ species[1] = +1.50000000e+00 +7.05332819e-13 * tc[1] -1.99591964e-15 * tc[2] +2.30081632e-18 * tc[3] -9.27732332e-22 * tc[4]; /*species 2: O2 */ species[2] = +2.78245636e+00 -2.99673416e-03 * tc[1] +9.84730201e-06 * tc[2] -9.68129509e-09 * tc[3] +3.24372837e-12 * tc[4]; /*species 3: OH */ species[3] = +2.99201543e+00 -2.40131752e-03 * tc[1] +4.61793841e-06 * tc[2] -3.88113333e-09 * tc[3] +1.36411470e-12 * tc[4]; /*species 4: H2O */ species[4] = +3.19864056e+00 -2.03643410e-03 * tc[1] +6.52040211e-06 * tc[2] -5.48797062e-09 * tc[3] +1.77197817e-12 * tc[4]; /*species 5: HO2 */ species[5] = +3.30179801e+00 -4.74912051e-03 * tc[1] +2.11582891e-05 * tc[2] -2.42763894e-08 * tc[3] +9.29225124e-12 * tc[4]; /*species 6: H2O2 */ species[6] = +3.27611269e+00 -5.42822417e-04 * tc[1] +1.67335701e-05 * tc[2] -2.15770813e-08 * tc[3] +8.62454363e-12 * tc[4]; /*species 7: CH3 */ species[7] = +2.67359040e+00 +2.01095175e-03 * tc[1] +5.73021856e-06 * tc[2] -6.87117425e-09 * tc[3] +2.54385734e-12 * tc[4]; /*species 8: CH4 */ species[8] = +4.14987613e+00 -1.36709788e-02 * tc[1] +4.91800599e-05 * tc[2] -4.84743026e-08 * tc[3] +1.66693956e-11 * tc[4]; /*species 9: CO */ species[9] = +2.57953347e+00 -6.10353680e-04 * tc[1] +1.01681433e-06 * tc[2] +9.07005884e-10 * tc[3] -9.04424499e-13 * tc[4]; /*species 10: CO2 */ species[10] = +1.35677352e+00 +8.98459677e-03 * tc[1] -7.12356269e-06 * tc[2] +2.45919022e-09 * tc[3] -1.43699548e-13 * tc[4]; /*species 11: CH2O */ species[11] = +3.79372315e+00 -9.90833369e-03 * tc[1] +3.73220008e-05 * tc[2] -3.79285261e-08 * tc[3] +1.31772652e-11 * tc[4]; /*species 12: C2H2 */ species[12] = -1.91318906e-01 +2.33615629e-02 * tc[1] -3.55171815e-05 * tc[2] +2.80152437e-08 * tc[3] -8.50072974e-12 * tc[4]; /*species 13: C2H4 */ species[13] = +2.95920148e+00 -7.57052247e-03 * tc[1] +5.70990292e-05 * tc[2] -6.91588753e-08 * tc[3] +2.69884373e-11 * tc[4]; /*species 14: C2H6 */ species[14] = +3.29142492e+00 -5.50154270e-03 * tc[1] +5.99438288e-05 * tc[2] -7.08466285e-08 * tc[3] +2.68685771e-11 * tc[4]; /*species 15: NH3 */ species[15] = +3.28602740e+00 -4.66052300e-03 * tc[1] +2.17185130e-05 * tc[2] -2.28088870e-08 * tc[3] +8.26380460e-12 * tc[4]; /*species 16: NO */ species[16] = +3.21847630e+00 -4.63897600e-03 * tc[1] +1.10410220e-05 * tc[2] -9.33613540e-09 * tc[3] +2.80357700e-12 * tc[4]; /*species 17: HCN */ species[17] = +1.25898860e+00 +1.00511700e-02 * tc[1] -1.33517630e-05 * tc[2] +1.00923490e-08 * tc[3] -3.00890280e-12 * tc[4]; /*species 18: N2 */ species[18] = +2.29867700e+00 +1.40824040e-03 * tc[1] -3.96322200e-06 * tc[2] +5.64151500e-09 * tc[3] -2.44485400e-12 * tc[4]; } else { /*species 0: H2 */ species[0] = +2.33727920e+00 -4.94024731e-05 * tc[1] +4.99456778e-07 * tc[2] -1.79566394e-10 * tc[3] +2.00255376e-14 * tc[4]; /*species 1: H */ species[1] = +1.50000001e+00 -2.30842973e-11 * tc[1] +1.61561948e-14 * tc[2] -4.73515235e-18 * tc[3] +4.98197357e-22 * tc[4]; /*species 2: O2 */ species[2] = +2.28253784e+00 +1.48308754e-03 * tc[1] -7.57966669e-07 * tc[2] +2.09470555e-10 * tc[3] -2.16717794e-14 * tc[4]; /*species 3: OH */ species[3] = +2.09288767e+00 +5.48429716e-04 * tc[1] +1.26505228e-07 * tc[2] -8.79461556e-11 * tc[3] +1.17412376e-14 * tc[4]; /*species 4: H2O */ species[4] = +2.03399249e+00 +2.17691804e-03 * tc[1] -1.64072518e-07 * tc[2] -9.70419870e-11 * tc[3] +1.68200992e-14 * tc[4]; /*species 5: HO2 */ species[5] = +3.01721090e+00 +2.23982013e-03 * tc[1] -6.33658150e-07 * tc[2] +1.14246370e-10 * tc[3] -1.07908535e-14 * tc[4]; /*species 6: H2O2 */ species[6] = +3.16500285e+00 +4.90831694e-03 * tc[1] -1.90139225e-06 * tc[2] +3.71185986e-10 * tc[3] -2.87908305e-14 * tc[4]; /*species 7: CH3 */ species[7] = +1.28571772e+00 +7.23990037e-03 * tc[1] -2.98714348e-06 * tc[2] +5.95684644e-10 * tc[3] -4.67154394e-14 * tc[4]; /*species 8: CH4 */ species[8] = -9.25148505e-01 +1.33909467e-02 * tc[1] -5.73285809e-06 * tc[2] +1.22292535e-09 * tc[3] -1.01815230e-13 * tc[4]; /*species 9: CO */ species[9] = +1.71518561e+00 +2.06252743e-03 * tc[1] -9.98825771e-07 * tc[2] +2.30053008e-10 * tc[3] -2.03647716e-14 * tc[4]; /*species 10: CO2 */ species[10] = +2.85746029e+00 +4.41437026e-03 * tc[1] -2.21481404e-06 * tc[2] +5.23490188e-10 * tc[3] -4.72084164e-14 * tc[4]; /*species 11: CH2O */ species[11] = +7.60690080e-01 +9.20000082e-03 * tc[1] -4.42258813e-06 * tc[2] +1.00641212e-09 * tc[3] -8.83855640e-14 * tc[4]; /*species 12: C2H2 */ species[12] = +3.14756964e+00 +5.96166664e-03 * tc[1] -2.37294852e-06 * tc[2] +4.67412171e-10 * tc[3] -3.61235213e-14 * tc[4]; /*species 13: C2H4 */ species[13] = +1.03611116e+00 +1.46454151e-02 * tc[1] -6.71077915e-06 * tc[2] +1.47222923e-09 * tc[3] -1.25706061e-13 * tc[4]; /*species 14: C2H6 */ species[14] = +7.18815000e-02 +2.16852677e-02 * tc[1] -1.00256067e-05 * tc[2] +2.21412001e-09 * tc[3] -1.90002890e-13 * tc[4]; /*species 15: NH3 */ species[15] = +1.63445210e+00 +5.66625600e-03 * tc[1] -1.72786760e-06 * tc[2] +2.38671610e-10 * tc[3] -1.25787860e-14 * tc[4]; /*species 16: NO */ species[16] = +2.26060560e+00 +1.19110430e-03 * tc[1] -4.29170480e-07 * tc[2] +6.94576690e-11 * tc[3] -4.03360990e-15 * tc[4]; /*species 17: HCN */ species[17] = +2.80223920e+00 +3.14642280e-03 * tc[1] -1.06321850e-06 * tc[2] +1.66197570e-10 * tc[3] -9.79975700e-15 * tc[4]; /*species 18: N2 */ species[18] = +1.92664000e+00 +1.48797680e-03 * tc[1] -5.68476000e-07 * tc[2] +1.00970380e-10 * tc[3] -6.75335100e-15 * tc[4]; } return; } /*compute Cp/R at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void cp_R(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +2.34433112e+00 +7.98052075e-03 * tc[1] -1.94781510e-05 * tc[2] +2.01572094e-08 * tc[3] -7.37611761e-12 * tc[4]; /*species 1: H */ species[1] = +2.50000000e+00 +7.05332819e-13 * tc[1] -1.99591964e-15 * tc[2] +2.30081632e-18 * tc[3] -9.27732332e-22 * tc[4]; /*species 2: O2 */ species[2] = +3.78245636e+00 -2.99673416e-03 * tc[1] +9.84730201e-06 * tc[2] -9.68129509e-09 * tc[3] +3.24372837e-12 * tc[4]; /*species 3: OH */ species[3] = +3.99201543e+00 -2.40131752e-03 * tc[1] +4.61793841e-06 * tc[2] -3.88113333e-09 * tc[3] +1.36411470e-12 * tc[4]; /*species 4: H2O */ species[4] = +4.19864056e+00 -2.03643410e-03 * tc[1] +6.52040211e-06 * tc[2] -5.48797062e-09 * tc[3] +1.77197817e-12 * tc[4]; /*species 5: HO2 */ species[5] = +4.30179801e+00 -4.74912051e-03 * tc[1] +2.11582891e-05 * tc[2] -2.42763894e-08 * tc[3] +9.29225124e-12 * tc[4]; /*species 6: H2O2 */ species[6] = +4.27611269e+00 -5.42822417e-04 * tc[1] +1.67335701e-05 * tc[2] -2.15770813e-08 * tc[3] +8.62454363e-12 * tc[4]; /*species 7: CH3 */ species[7] = +3.67359040e+00 +2.01095175e-03 * tc[1] +5.73021856e-06 * tc[2] -6.87117425e-09 * tc[3] +2.54385734e-12 * tc[4]; /*species 8: CH4 */ species[8] = +5.14987613e+00 -1.36709788e-02 * tc[1] +4.91800599e-05 * tc[2] -4.84743026e-08 * tc[3] +1.66693956e-11 * tc[4]; /*species 9: CO */ species[9] = +3.57953347e+00 -6.10353680e-04 * tc[1] +1.01681433e-06 * tc[2] +9.07005884e-10 * tc[3] -9.04424499e-13 * tc[4]; /*species 10: CO2 */ species[10] = +2.35677352e+00 +8.98459677e-03 * tc[1] -7.12356269e-06 * tc[2] +2.45919022e-09 * tc[3] -1.43699548e-13 * tc[4]; /*species 11: CH2O */ species[11] = +4.79372315e+00 -9.90833369e-03 * tc[1] +3.73220008e-05 * tc[2] -3.79285261e-08 * tc[3] +1.31772652e-11 * tc[4]; /*species 12: C2H2 */ species[12] = +8.08681094e-01 +2.33615629e-02 * tc[1] -3.55171815e-05 * tc[2] +2.80152437e-08 * tc[3] -8.50072974e-12 * tc[4]; /*species 13: C2H4 */ species[13] = +3.95920148e+00 -7.57052247e-03 * tc[1] +5.70990292e-05 * tc[2] -6.91588753e-08 * tc[3] +2.69884373e-11 * tc[4]; /*species 14: C2H6 */ species[14] = +4.29142492e+00 -5.50154270e-03 * tc[1] +5.99438288e-05 * tc[2] -7.08466285e-08 * tc[3] +2.68685771e-11 * tc[4]; /*species 15: NH3 */ species[15] = +4.28602740e+00 -4.66052300e-03 * tc[1] +2.17185130e-05 * tc[2] -2.28088870e-08 * tc[3] +8.26380460e-12 * tc[4]; /*species 16: NO */ species[16] = +4.21847630e+00 -4.63897600e-03 * tc[1] +1.10410220e-05 * tc[2] -9.33613540e-09 * tc[3] +2.80357700e-12 * tc[4]; /*species 17: HCN */ species[17] = +2.25898860e+00 +1.00511700e-02 * tc[1] -1.33517630e-05 * tc[2] +1.00923490e-08 * tc[3] -3.00890280e-12 * tc[4]; /*species 18: N2 */ species[18] = +3.29867700e+00 +1.40824040e-03 * tc[1] -3.96322200e-06 * tc[2] +5.64151500e-09 * tc[3] -2.44485400e-12 * tc[4]; } else { /*species 0: H2 */ species[0] = +3.33727920e+00 -4.94024731e-05 * tc[1] +4.99456778e-07 * tc[2] -1.79566394e-10 * tc[3] +2.00255376e-14 * tc[4]; /*species 1: H */ species[1] = +2.50000001e+00 -2.30842973e-11 * tc[1] +1.61561948e-14 * tc[2] -4.73515235e-18 * tc[3] +4.98197357e-22 * tc[4]; /*species 2: O2 */ species[2] = +3.28253784e+00 +1.48308754e-03 * tc[1] -7.57966669e-07 * tc[2] +2.09470555e-10 * tc[3] -2.16717794e-14 * tc[4]; /*species 3: OH */ species[3] = +3.09288767e+00 +5.48429716e-04 * tc[1] +1.26505228e-07 * tc[2] -8.79461556e-11 * tc[3] +1.17412376e-14 * tc[4]; /*species 4: H2O */ species[4] = +3.03399249e+00 +2.17691804e-03 * tc[1] -1.64072518e-07 * tc[2] -9.70419870e-11 * tc[3] +1.68200992e-14 * tc[4]; /*species 5: HO2 */ species[5] = +4.01721090e+00 +2.23982013e-03 * tc[1] -6.33658150e-07 * tc[2] +1.14246370e-10 * tc[3] -1.07908535e-14 * tc[4]; /*species 6: H2O2 */ species[6] = +4.16500285e+00 +4.90831694e-03 * tc[1] -1.90139225e-06 * tc[2] +3.71185986e-10 * tc[3] -2.87908305e-14 * tc[4]; /*species 7: CH3 */ species[7] = +2.28571772e+00 +7.23990037e-03 * tc[1] -2.98714348e-06 * tc[2] +5.95684644e-10 * tc[3] -4.67154394e-14 * tc[4]; /*species 8: CH4 */ species[8] = +7.48514950e-02 +1.33909467e-02 * tc[1] -5.73285809e-06 * tc[2] +1.22292535e-09 * tc[3] -1.01815230e-13 * tc[4]; /*species 9: CO */ species[9] = +2.71518561e+00 +2.06252743e-03 * tc[1] -9.98825771e-07 * tc[2] +2.30053008e-10 * tc[3] -2.03647716e-14 * tc[4]; /*species 10: CO2 */ species[10] = +3.85746029e+00 +4.41437026e-03 * tc[1] -2.21481404e-06 * tc[2] +5.23490188e-10 * tc[3] -4.72084164e-14 * tc[4]; /*species 11: CH2O */ species[11] = +1.76069008e+00 +9.20000082e-03 * tc[1] -4.42258813e-06 * tc[2] +1.00641212e-09 * tc[3] -8.83855640e-14 * tc[4]; /*species 12: C2H2 */ species[12] = +4.14756964e+00 +5.96166664e-03 * tc[1] -2.37294852e-06 * tc[2] +4.67412171e-10 * tc[3] -3.61235213e-14 * tc[4]; /*species 13: C2H4 */ species[13] = +2.03611116e+00 +1.46454151e-02 * tc[1] -6.71077915e-06 * tc[2] +1.47222923e-09 * tc[3] -1.25706061e-13 * tc[4]; /*species 14: C2H6 */ species[14] = +1.07188150e+00 +2.16852677e-02 * tc[1] -1.00256067e-05 * tc[2] +2.21412001e-09 * tc[3] -1.90002890e-13 * tc[4]; /*species 15: NH3 */ species[15] = +2.63445210e+00 +5.66625600e-03 * tc[1] -1.72786760e-06 * tc[2] +2.38671610e-10 * tc[3] -1.25787860e-14 * tc[4]; /*species 16: NO */ species[16] = +3.26060560e+00 +1.19110430e-03 * tc[1] -4.29170480e-07 * tc[2] +6.94576690e-11 * tc[3] -4.03360990e-15 * tc[4]; /*species 17: HCN */ species[17] = +3.80223920e+00 +3.14642280e-03 * tc[1] -1.06321850e-06 * tc[2] +1.66197570e-10 * tc[3] -9.79975700e-15 * tc[4]; /*species 18: N2 */ species[18] = +2.92664000e+00 +1.48797680e-03 * tc[1] -5.68476000e-07 * tc[2] +1.00970380e-10 * tc[3] -6.75335100e-15 * tc[4]; } return; } /*compute the e/(RT) at the given temperature */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void speciesInternalEnergy(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; double invT = 1 / T; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +1.34433112e+00 +3.99026037e-03 * tc[1] -6.49271700e-06 * tc[2] +5.03930235e-09 * tc[3] -1.47522352e-12 * tc[4] -9.17935173e+02 * invT; /*species 1: H */ species[1] = +1.50000000e+00 +3.52666409e-13 * tc[1] -6.65306547e-16 * tc[2] +5.75204080e-19 * tc[3] -1.85546466e-22 * tc[4] +2.54736599e+04 * invT; /*species 2: O2 */ species[2] = +2.78245636e+00 -1.49836708e-03 * tc[1] +3.28243400e-06 * tc[2] -2.42032377e-09 * tc[3] +6.48745674e-13 * tc[4] -1.06394356e+03 * invT; /*species 3: OH */ species[3] = +2.99201543e+00 -1.20065876e-03 * tc[1] +1.53931280e-06 * tc[2] -9.70283332e-10 * tc[3] +2.72822940e-13 * tc[4] +3.61508056e+03 * invT; /*species 4: H2O */ species[4] = +3.19864056e+00 -1.01821705e-03 * tc[1] +2.17346737e-06 * tc[2] -1.37199266e-09 * tc[3] +3.54395634e-13 * tc[4] -3.02937267e+04 * invT; /*species 5: HO2 */ species[5] = +3.30179801e+00 -2.37456025e-03 * tc[1] +7.05276303e-06 * tc[2] -6.06909735e-09 * tc[3] +1.85845025e-12 * tc[4] +2.94808040e+02 * invT; /*species 6: H2O2 */ species[6] = +3.27611269e+00 -2.71411208e-04 * tc[1] +5.57785670e-06 * tc[2] -5.39427032e-09 * tc[3] +1.72490873e-12 * tc[4] -1.77025821e+04 * invT; /*species 7: CH3 */ species[7] = +2.67359040e+00 +1.00547588e-03 * tc[1] +1.91007285e-06 * tc[2] -1.71779356e-09 * tc[3] +5.08771468e-13 * tc[4] +1.64449988e+04 * invT; /*species 8: CH4 */ species[8] = +4.14987613e+00 -6.83548940e-03 * tc[1] +1.63933533e-05 * tc[2] -1.21185757e-08 * tc[3] +3.33387912e-12 * tc[4] -1.02466476e+04 * invT; /*species 9: CO */ species[9] = +2.57953347e+00 -3.05176840e-04 * tc[1] +3.38938110e-07 * tc[2] +2.26751471e-10 * tc[3] -1.80884900e-13 * tc[4] -1.43440860e+04 * invT; /*species 10: CO2 */ species[10] = +1.35677352e+00 +4.49229839e-03 * tc[1] -2.37452090e-06 * tc[2] +6.14797555e-10 * tc[3] -2.87399096e-14 * tc[4] -4.83719697e+04 * invT; /*species 11: CH2O */ species[11] = +3.79372315e+00 -4.95416684e-03 * tc[1] +1.24406669e-05 * tc[2] -9.48213152e-09 * tc[3] +2.63545304e-12 * tc[4] -1.43089567e+04 * invT; /*species 12: C2H2 */ species[12] = -1.91318906e-01 +1.16807815e-02 * tc[1] -1.18390605e-05 * tc[2] +7.00381092e-09 * tc[3] -1.70014595e-12 * tc[4] +2.64289807e+04 * invT; /*species 13: C2H4 */ species[13] = +2.95920148e+00 -3.78526124e-03 * tc[1] +1.90330097e-05 * tc[2] -1.72897188e-08 * tc[3] +5.39768746e-12 * tc[4] +5.08977593e+03 * invT; /*species 14: C2H6 */ species[14] = +3.29142492e+00 -2.75077135e-03 * tc[1] +1.99812763e-05 * tc[2] -1.77116571e-08 * tc[3] +5.37371542e-12 * tc[4] -1.15222055e+04 * invT; /*species 15: NH3 */ species[15] = +3.28602740e+00 -2.33026150e-03 * tc[1] +7.23950433e-06 * tc[2] -5.70222175e-09 * tc[3] +1.65276092e-12 * tc[4] -6.74172850e+03 * invT; /*species 16: NO */ species[16] = +3.21847630e+00 -2.31948800e-03 * tc[1] +3.68034067e-06 * tc[2] -2.33403385e-09 * tc[3] +5.60715400e-13 * tc[4] +9.84462300e+03 * invT; /*species 17: HCN */ species[17] = +1.25898860e+00 +5.02558500e-03 * tc[1] -4.45058767e-06 * tc[2] +2.52308725e-09 * tc[3] -6.01780560e-13 * tc[4] +1.47126330e+04 * invT; /*species 18: N2 */ species[18] = +2.29867700e+00 +7.04120200e-04 * tc[1] -1.32107400e-06 * tc[2] +1.41037875e-09 * tc[3] -4.88970800e-13 * tc[4] -1.02089990e+03 * invT; } else { /*species 0: H2 */ species[0] = +2.33727920e+00 -2.47012365e-05 * tc[1] +1.66485593e-07 * tc[2] -4.48915985e-11 * tc[3] +4.00510752e-15 * tc[4] -9.50158922e+02 * invT; /*species 1: H */ species[1] = +1.50000001e+00 -1.15421486e-11 * tc[1] +5.38539827e-15 * tc[2] -1.18378809e-18 * tc[3] +9.96394714e-23 * tc[4] +2.54736599e+04 * invT; /*species 2: O2 */ species[2] = +2.28253784e+00 +7.41543770e-04 * tc[1] -2.52655556e-07 * tc[2] +5.23676387e-11 * tc[3] -4.33435588e-15 * tc[4] -1.08845772e+03 * invT; /*species 3: OH */ species[3] = +2.09288767e+00 +2.74214858e-04 * tc[1] +4.21684093e-08 * tc[2] -2.19865389e-11 * tc[3] +2.34824752e-15 * tc[4] +3.85865700e+03 * invT; /*species 4: H2O */ species[4] = +2.03399249e+00 +1.08845902e-03 * tc[1] -5.46908393e-08 * tc[2] -2.42604967e-11 * tc[3] +3.36401984e-15 * tc[4] -3.00042971e+04 * invT; /*species 5: HO2 */ species[5] = +3.01721090e+00 +1.11991006e-03 * tc[1] -2.11219383e-07 * tc[2] +2.85615925e-11 * tc[3] -2.15817070e-15 * tc[4] +1.11856713e+02 * invT; /*species 6: H2O2 */ species[6] = +3.16500285e+00 +2.45415847e-03 * tc[1] -6.33797417e-07 * tc[2] +9.27964965e-11 * tc[3] -5.75816610e-15 * tc[4] -1.78617877e+04 * invT; /*species 7: CH3 */ species[7] = +1.28571772e+00 +3.61995018e-03 * tc[1] -9.95714493e-07 * tc[2] +1.48921161e-10 * tc[3] -9.34308788e-15 * tc[4] +1.67755843e+04 * invT; /*species 8: CH4 */ species[8] = -9.25148505e-01 +6.69547335e-03 * tc[1] -1.91095270e-06 * tc[2] +3.05731338e-10 * tc[3] -2.03630460e-14 * tc[4] -9.46834459e+03 * invT; /*species 9: CO */ species[9] = +1.71518561e+00 +1.03126372e-03 * tc[1] -3.32941924e-07 * tc[2] +5.75132520e-11 * tc[3] -4.07295432e-15 * tc[4] -1.41518724e+04 * invT; /*species 10: CO2 */ species[10] = +2.85746029e+00 +2.20718513e-03 * tc[1] -7.38271347e-07 * tc[2] +1.30872547e-10 * tc[3] -9.44168328e-15 * tc[4] -4.87591660e+04 * invT; /*species 11: CH2O */ species[11] = +7.60690080e-01 +4.60000041e-03 * tc[1] -1.47419604e-06 * tc[2] +2.51603030e-10 * tc[3] -1.76771128e-14 * tc[4] -1.39958323e+04 * invT; /*species 12: C2H2 */ species[12] = +3.14756964e+00 +2.98083332e-03 * tc[1] -7.90982840e-07 * tc[2] +1.16853043e-10 * tc[3] -7.22470426e-15 * tc[4] +2.59359992e+04 * invT; /*species 13: C2H4 */ species[13] = +1.03611116e+00 +7.32270755e-03 * tc[1] -2.23692638e-06 * tc[2] +3.68057308e-10 * tc[3] -2.51412122e-14 * tc[4] +4.93988614e+03 * invT; /*species 14: C2H6 */ species[14] = +7.18815000e-02 +1.08426339e-02 * tc[1] -3.34186890e-06 * tc[2] +5.53530003e-10 * tc[3] -3.80005780e-14 * tc[4] -1.14263932e+04 * invT; /*species 15: NH3 */ species[15] = +1.63445210e+00 +2.83312800e-03 * tc[1] -5.75955867e-07 * tc[2] +5.96679025e-11 * tc[3] -2.51575720e-15 * tc[4] -6.54469580e+03 * invT; /*species 16: NO */ species[16] = +2.26060560e+00 +5.95552150e-04 * tc[1] -1.43056827e-07 * tc[2] +1.73644173e-11 * tc[3] -8.06721980e-16 * tc[4] +9.92097460e+03 * invT; /*species 17: HCN */ species[17] = +2.80223920e+00 +1.57321140e-03 * tc[1] -3.54406167e-07 * tc[2] +4.15493925e-11 * tc[3] -1.95995140e-15 * tc[4] +1.44072920e+04 * invT; /*species 18: N2 */ species[18] = +1.92664000e+00 +7.43988400e-04 * tc[1] -1.89492000e-07 * tc[2] +2.52425950e-11 * tc[3] -1.35067020e-15 * tc[4] -9.22797700e+02 * invT; } return; } /*compute the h/(RT) at the given temperature (Eq 20) */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void speciesEnthalpy(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; double invT = 1 / T; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +2.34433112e+00 +3.99026037e-03 * tc[1] -6.49271700e-06 * tc[2] +5.03930235e-09 * tc[3] -1.47522352e-12 * tc[4] -9.17935173e+02 * invT; /*species 1: H */ species[1] = +2.50000000e+00 +3.52666409e-13 * tc[1] -6.65306547e-16 * tc[2] +5.75204080e-19 * tc[3] -1.85546466e-22 * tc[4] +2.54736599e+04 * invT; /*species 2: O2 */ species[2] = +3.78245636e+00 -1.49836708e-03 * tc[1] +3.28243400e-06 * tc[2] -2.42032377e-09 * tc[3] +6.48745674e-13 * tc[4] -1.06394356e+03 * invT; /*species 3: OH */ species[3] = +3.99201543e+00 -1.20065876e-03 * tc[1] +1.53931280e-06 * tc[2] -9.70283332e-10 * tc[3] +2.72822940e-13 * tc[4] +3.61508056e+03 * invT; /*species 4: H2O */ species[4] = +4.19864056e+00 -1.01821705e-03 * tc[1] +2.17346737e-06 * tc[2] -1.37199266e-09 * tc[3] +3.54395634e-13 * tc[4] -3.02937267e+04 * invT; /*species 5: HO2 */ species[5] = +4.30179801e+00 -2.37456025e-03 * tc[1] +7.05276303e-06 * tc[2] -6.06909735e-09 * tc[3] +1.85845025e-12 * tc[4] +2.94808040e+02 * invT; /*species 6: H2O2 */ species[6] = +4.27611269e+00 -2.71411208e-04 * tc[1] +5.57785670e-06 * tc[2] -5.39427032e-09 * tc[3] +1.72490873e-12 * tc[4] -1.77025821e+04 * invT; /*species 7: CH3 */ species[7] = +3.67359040e+00 +1.00547588e-03 * tc[1] +1.91007285e-06 * tc[2] -1.71779356e-09 * tc[3] +5.08771468e-13 * tc[4] +1.64449988e+04 * invT; /*species 8: CH4 */ species[8] = +5.14987613e+00 -6.83548940e-03 * tc[1] +1.63933533e-05 * tc[2] -1.21185757e-08 * tc[3] +3.33387912e-12 * tc[4] -1.02466476e+04 * invT; /*species 9: CO */ species[9] = +3.57953347e+00 -3.05176840e-04 * tc[1] +3.38938110e-07 * tc[2] +2.26751471e-10 * tc[3] -1.80884900e-13 * tc[4] -1.43440860e+04 * invT; /*species 10: CO2 */ species[10] = +2.35677352e+00 +4.49229839e-03 * tc[1] -2.37452090e-06 * tc[2] +6.14797555e-10 * tc[3] -2.87399096e-14 * tc[4] -4.83719697e+04 * invT; /*species 11: CH2O */ species[11] = +4.79372315e+00 -4.95416684e-03 * tc[1] +1.24406669e-05 * tc[2] -9.48213152e-09 * tc[3] +2.63545304e-12 * tc[4] -1.43089567e+04 * invT; /*species 12: C2H2 */ species[12] = +8.08681094e-01 +1.16807815e-02 * tc[1] -1.18390605e-05 * tc[2] +7.00381092e-09 * tc[3] -1.70014595e-12 * tc[4] +2.64289807e+04 * invT; /*species 13: C2H4 */ species[13] = +3.95920148e+00 -3.78526124e-03 * tc[1] +1.90330097e-05 * tc[2] -1.72897188e-08 * tc[3] +5.39768746e-12 * tc[4] +5.08977593e+03 * invT; /*species 14: C2H6 */ species[14] = +4.29142492e+00 -2.75077135e-03 * tc[1] +1.99812763e-05 * tc[2] -1.77116571e-08 * tc[3] +5.37371542e-12 * tc[4] -1.15222055e+04 * invT; /*species 15: NH3 */ species[15] = +4.28602740e+00 -2.33026150e-03 * tc[1] +7.23950433e-06 * tc[2] -5.70222175e-09 * tc[3] +1.65276092e-12 * tc[4] -6.74172850e+03 * invT; /*species 16: NO */ species[16] = +4.21847630e+00 -2.31948800e-03 * tc[1] +3.68034067e-06 * tc[2] -2.33403385e-09 * tc[3] +5.60715400e-13 * tc[4] +9.84462300e+03 * invT; /*species 17: HCN */ species[17] = +2.25898860e+00 +5.02558500e-03 * tc[1] -4.45058767e-06 * tc[2] +2.52308725e-09 * tc[3] -6.01780560e-13 * tc[4] +1.47126330e+04 * invT; /*species 18: N2 */ species[18] = +3.29867700e+00 +7.04120200e-04 * tc[1] -1.32107400e-06 * tc[2] +1.41037875e-09 * tc[3] -4.88970800e-13 * tc[4] -1.02089990e+03 * invT; } else { /*species 0: H2 */ species[0] = +3.33727920e+00 -2.47012365e-05 * tc[1] +1.66485593e-07 * tc[2] -4.48915985e-11 * tc[3] +4.00510752e-15 * tc[4] -9.50158922e+02 * invT; /*species 1: H */ species[1] = +2.50000001e+00 -1.15421486e-11 * tc[1] +5.38539827e-15 * tc[2] -1.18378809e-18 * tc[3] +9.96394714e-23 * tc[4] +2.54736599e+04 * invT; /*species 2: O2 */ species[2] = +3.28253784e+00 +7.41543770e-04 * tc[1] -2.52655556e-07 * tc[2] +5.23676387e-11 * tc[3] -4.33435588e-15 * tc[4] -1.08845772e+03 * invT; /*species 3: OH */ species[3] = +3.09288767e+00 +2.74214858e-04 * tc[1] +4.21684093e-08 * tc[2] -2.19865389e-11 * tc[3] +2.34824752e-15 * tc[4] +3.85865700e+03 * invT; /*species 4: H2O */ species[4] = +3.03399249e+00 +1.08845902e-03 * tc[1] -5.46908393e-08 * tc[2] -2.42604967e-11 * tc[3] +3.36401984e-15 * tc[4] -3.00042971e+04 * invT; /*species 5: HO2 */ species[5] = +4.01721090e+00 +1.11991006e-03 * tc[1] -2.11219383e-07 * tc[2] +2.85615925e-11 * tc[3] -2.15817070e-15 * tc[4] +1.11856713e+02 * invT; /*species 6: H2O2 */ species[6] = +4.16500285e+00 +2.45415847e-03 * tc[1] -6.33797417e-07 * tc[2] +9.27964965e-11 * tc[3] -5.75816610e-15 * tc[4] -1.78617877e+04 * invT; /*species 7: CH3 */ species[7] = +2.28571772e+00 +3.61995018e-03 * tc[1] -9.95714493e-07 * tc[2] +1.48921161e-10 * tc[3] -9.34308788e-15 * tc[4] +1.67755843e+04 * invT; /*species 8: CH4 */ species[8] = +7.48514950e-02 +6.69547335e-03 * tc[1] -1.91095270e-06 * tc[2] +3.05731338e-10 * tc[3] -2.03630460e-14 * tc[4] -9.46834459e+03 * invT; /*species 9: CO */ species[9] = +2.71518561e+00 +1.03126372e-03 * tc[1] -3.32941924e-07 * tc[2] +5.75132520e-11 * tc[3] -4.07295432e-15 * tc[4] -1.41518724e+04 * invT; /*species 10: CO2 */ species[10] = +3.85746029e+00 +2.20718513e-03 * tc[1] -7.38271347e-07 * tc[2] +1.30872547e-10 * tc[3] -9.44168328e-15 * tc[4] -4.87591660e+04 * invT; /*species 11: CH2O */ species[11] = +1.76069008e+00 +4.60000041e-03 * tc[1] -1.47419604e-06 * tc[2] +2.51603030e-10 * tc[3] -1.76771128e-14 * tc[4] -1.39958323e+04 * invT; /*species 12: C2H2 */ species[12] = +4.14756964e+00 +2.98083332e-03 * tc[1] -7.90982840e-07 * tc[2] +1.16853043e-10 * tc[3] -7.22470426e-15 * tc[4] +2.59359992e+04 * invT; /*species 13: C2H4 */ species[13] = +2.03611116e+00 +7.32270755e-03 * tc[1] -2.23692638e-06 * tc[2] +3.68057308e-10 * tc[3] -2.51412122e-14 * tc[4] +4.93988614e+03 * invT; /*species 14: C2H6 */ species[14] = +1.07188150e+00 +1.08426339e-02 * tc[1] -3.34186890e-06 * tc[2] +5.53530003e-10 * tc[3] -3.80005780e-14 * tc[4] -1.14263932e+04 * invT; /*species 15: NH3 */ species[15] = +2.63445210e+00 +2.83312800e-03 * tc[1] -5.75955867e-07 * tc[2] +5.96679025e-11 * tc[3] -2.51575720e-15 * tc[4] -6.54469580e+03 * invT; /*species 16: NO */ species[16] = +3.26060560e+00 +5.95552150e-04 * tc[1] -1.43056827e-07 * tc[2] +1.73644173e-11 * tc[3] -8.06721980e-16 * tc[4] +9.92097460e+03 * invT; /*species 17: HCN */ species[17] = +3.80223920e+00 +1.57321140e-03 * tc[1] -3.54406167e-07 * tc[2] +4.15493925e-11 * tc[3] -1.95995140e-15 * tc[4] +1.44072920e+04 * invT; /*species 18: N2 */ species[18] = +2.92664000e+00 +7.43988400e-04 * tc[1] -1.89492000e-07 * tc[2] +2.52425950e-11 * tc[3] -1.35067020e-15 * tc[4] -9.22797700e+02 * invT; } return; } /*compute the S/R at the given temperature (Eq 21) */ /*tc contains precomputed powers of T, tc[0] = log(T) */ void speciesEntropy(double * restrict species, double * restrict tc) { /*temperature */ double T = tc[1]; /*species with midpoint at T=1000 kelvin */ if (T < 1000) { /*species 0: H2 */ species[0] = +2.34433112e+00 * tc[0] +7.98052075e-03 * tc[1] -9.73907550e-06 * tc[2] +6.71906980e-09 * tc[3] -1.84402940e-12 * tc[4] +6.83010238e-01 ; /*species 1: H */ species[1] = +2.50000000e+00 * tc[0] +7.05332819e-13 * tc[1] -9.97959820e-16 * tc[2] +7.66938773e-19 * tc[3] -2.31933083e-22 * tc[4] -4.46682853e-01 ; /*species 2: O2 */ species[2] = +3.78245636e+00 * tc[0] -2.99673416e-03 * tc[1] +4.92365101e-06 * tc[2] -3.22709836e-09 * tc[3] +8.10932092e-13 * tc[4] +3.65767573e+00 ; /*species 3: OH */ species[3] = +3.99201543e+00 * tc[0] -2.40131752e-03 * tc[1] +2.30896920e-06 * tc[2] -1.29371111e-09 * tc[3] +3.41028675e-13 * tc[4] -1.03925458e-01 ; /*species 4: H2O */ species[4] = +4.19864056e+00 * tc[0] -2.03643410e-03 * tc[1] +3.26020105e-06 * tc[2] -1.82932354e-09 * tc[3] +4.42994543e-13 * tc[4] -8.49032208e-01 ; /*species 5: HO2 */ species[5] = +4.30179801e+00 * tc[0] -4.74912051e-03 * tc[1] +1.05791445e-05 * tc[2] -8.09212980e-09 * tc[3] +2.32306281e-12 * tc[4] +3.71666245e+00 ; /*species 6: H2O2 */ species[6] = +4.27611269e+00 * tc[0] -5.42822417e-04 * tc[1] +8.36678505e-06 * tc[2] -7.19236043e-09 * tc[3] +2.15613591e-12 * tc[4] +3.43505074e+00 ; /*species 7: CH3 */ species[7] = +3.67359040e+00 * tc[0] +2.01095175e-03 * tc[1] +2.86510928e-06 * tc[2] -2.29039142e-09 * tc[3] +6.35964335e-13 * tc[4] +1.60456433e+00 ; /*species 8: CH4 */ species[8] = +5.14987613e+00 * tc[0] -1.36709788e-02 * tc[1] +2.45900299e-05 * tc[2] -1.61581009e-08 * tc[3] +4.16734890e-12 * tc[4] -4.64130376e+00 ; /*species 9: CO */ species[9] = +3.57953347e+00 * tc[0] -6.10353680e-04 * tc[1] +5.08407165e-07 * tc[2] +3.02335295e-10 * tc[3] -2.26106125e-13 * tc[4] +3.50840928e+00 ; /*species 10: CO2 */ species[10] = +2.35677352e+00 * tc[0] +8.98459677e-03 * tc[1] -3.56178134e-06 * tc[2] +8.19730073e-10 * tc[3] -3.59248870e-14 * tc[4] +9.90105222e+00 ; /*species 11: CH2O */ species[11] = +4.79372315e+00 * tc[0] -9.90833369e-03 * tc[1] +1.86610004e-05 * tc[2] -1.26428420e-08 * tc[3] +3.29431630e-12 * tc[4] +6.02812900e-01 ; /*species 12: C2H2 */ species[12] = +8.08681094e-01 * tc[0] +2.33615629e-02 * tc[1] -1.77585907e-05 * tc[2] +9.33841457e-09 * tc[3] -2.12518243e-12 * tc[4] +1.39397051e+01 ; /*species 13: C2H4 */ species[13] = +3.95920148e+00 * tc[0] -7.57052247e-03 * tc[1] +2.85495146e-05 * tc[2] -2.30529584e-08 * tc[3] +6.74710933e-12 * tc[4] +4.09733096e+00 ; /*species 14: C2H6 */ species[14] = +4.29142492e+00 * tc[0] -5.50154270e-03 * tc[1] +2.99719144e-05 * tc[2] -2.36155428e-08 * tc[3] +6.71714427e-12 * tc[4] +2.66682316e+00 ; /*species 15: NH3 */ species[15] = +4.28602740e+00 * tc[0] -4.66052300e-03 * tc[1] +1.08592565e-05 * tc[2] -7.60296233e-09 * tc[3] +2.06595115e-12 * tc[4] -6.25372770e-01 ; /*species 16: NO */ species[16] = +4.21847630e+00 * tc[0] -4.63897600e-03 * tc[1] +5.52051100e-06 * tc[2] -3.11204513e-09 * tc[3] +7.00894250e-13 * tc[4] +2.28084640e+00 ; /*species 17: HCN */ species[17] = +2.25898860e+00 * tc[0] +1.00511700e-02 * tc[1] -6.67588150e-06 * tc[2] +3.36411633e-09 * tc[3] -7.52225700e-13 * tc[4] +8.91644190e+00 ; /*species 18: N2 */ species[18] = +3.29867700e+00 * tc[0] +1.40824040e-03 * tc[1] -1.98161100e-06 * tc[2] +1.88050500e-09 * tc[3] -6.11213500e-13 * tc[4] +3.95037200e+00 ; } else { /*species 0: H2 */ species[0] = +3.33727920e+00 * tc[0] -4.94024731e-05 * tc[1] +2.49728389e-07 * tc[2] -5.98554647e-11 * tc[3] +5.00638440e-15 * tc[4] -3.20502331e+00 ; /*species 1: H */ species[1] = +2.50000001e+00 * tc[0] -2.30842973e-11 * tc[1] +8.07809740e-15 * tc[2] -1.57838412e-18 * tc[3] +1.24549339e-22 * tc[4] -4.46682914e-01 ; /*species 2: O2 */ species[2] = +3.28253784e+00 * tc[0] +1.48308754e-03 * tc[1] -3.78983334e-07 * tc[2] +6.98235183e-11 * tc[3] -5.41794485e-15 * tc[4] +5.45323129e+00 ; /*species 3: OH */ species[3] = +3.09288767e+00 * tc[0] +5.48429716e-04 * tc[1] +6.32526140e-08 * tc[2] -2.93153852e-11 * tc[3] +2.93530940e-15 * tc[4] +4.47669610e+00 ; /*species 4: H2O */ species[4] = +3.03399249e+00 * tc[0] +2.17691804e-03 * tc[1] -8.20362590e-08 * tc[2] -3.23473290e-11 * tc[3] +4.20502480e-15 * tc[4] +4.96677010e+00 ; /*species 5: HO2 */ species[5] = +4.01721090e+00 * tc[0] +2.23982013e-03 * tc[1] -3.16829075e-07 * tc[2] +3.80821233e-11 * tc[3] -2.69771337e-15 * tc[4] +3.78510215e+00 ; /*species 6: H2O2 */ species[6] = +4.16500285e+00 * tc[0] +4.90831694e-03 * tc[1] -9.50696125e-07 * tc[2] +1.23728662e-10 * tc[3] -7.19770763e-15 * tc[4] +2.91615662e+00 ; /*species 7: CH3 */ species[7] = +2.28571772e+00 * tc[0] +7.23990037e-03 * tc[1] -1.49357174e-06 * tc[2] +1.98561548e-10 * tc[3] -1.16788599e-14 * tc[4] +8.48007179e+00 ; /*species 8: CH4 */ species[8] = +7.48514950e-02 * tc[0] +1.33909467e-02 * tc[1] -2.86642905e-06 * tc[2] +4.07641783e-10 * tc[3] -2.54538075e-14 * tc[4] +1.84373180e+01 ; /*species 9: CO */ species[9] = +2.71518561e+00 * tc[0] +2.06252743e-03 * tc[1] -4.99412886e-07 * tc[2] +7.66843360e-11 * tc[3] -5.09119290e-15 * tc[4] +7.81868772e+00 ; /*species 10: CO2 */ species[10] = +3.85746029e+00 * tc[0] +4.41437026e-03 * tc[1] -1.10740702e-06 * tc[2] +1.74496729e-10 * tc[3] -1.18021041e-14 * tc[4] +2.27163806e+00 ; /*species 11: CH2O */ species[11] = +1.76069008e+00 * tc[0] +9.20000082e-03 * tc[1] -2.21129406e-06 * tc[2] +3.35470707e-10 * tc[3] -2.20963910e-14 * tc[4] +1.36563230e+01 ; /*species 12: C2H2 */ species[12] = +4.14756964e+00 * tc[0] +5.96166664e-03 * tc[1] -1.18647426e-06 * tc[2] +1.55804057e-10 * tc[3] -9.03088033e-15 * tc[4] -1.23028121e+00 ; /*species 13: C2H4 */ species[13] = +2.03611116e+00 * tc[0] +1.46454151e-02 * tc[1] -3.35538958e-06 * tc[2] +4.90743077e-10 * tc[3] -3.14265152e-14 * tc[4] +1.03053693e+01 ; /*species 14: C2H6 */ species[14] = +1.07188150e+00 * tc[0] +2.16852677e-02 * tc[1] -5.01280335e-06 * tc[2] +7.38040003e-10 * tc[3] -4.75007225e-14 * tc[4] +1.51156107e+01 ; /*species 15: NH3 */ species[15] = +2.63445210e+00 * tc[0] +5.66625600e-03 * tc[1] -8.63933800e-07 * tc[2] +7.95572033e-11 * tc[3] -3.14469650e-15 * tc[4] +6.56629280e+00 ; /*species 16: NO */ species[16] = +3.26060560e+00 * tc[0] +1.19110430e-03 * tc[1] -2.14585240e-07 * tc[2] +2.31525563e-11 * tc[3] -1.00840247e-15 * tc[4] +6.36930270e+00 ; /*species 17: HCN */ species[17] = +3.80223920e+00 * tc[0] +3.14642280e-03 * tc[1] -5.31609250e-07 * tc[2] +5.53991900e-11 * tc[3] -2.44993925e-15 * tc[4] +1.57546010e+00 ; /*species 18: N2 */ species[18] = +2.92664000e+00 * tc[0] +1.48797680e-03 * tc[1] -2.84238000e-07 * tc[2] +3.36567933e-11 * tc[3] -1.68833775e-15 * tc[4] +5.98052800e+00 ; } return; } /*save molecular weights into array */ void molecularWeight(double * restrict wt) { wt[0] = 2.015940; /*H2 */ wt[1] = 1.007970; /*H */ wt[2] = 31.998800; /*O2 */ wt[3] = 17.007370; /*OH */ wt[4] = 18.015340; /*H2O */ wt[5] = 33.006770; /*HO2 */ wt[6] = 34.014740; /*H2O2 */ wt[7] = 15.035060; /*CH3 */ wt[8] = 16.043030; /*CH4 */ wt[9] = 28.010550; /*CO */ wt[10] = 44.009950; /*CO2 */ wt[11] = 30.026490; /*CH2O */ wt[12] = 26.038240; /*C2H2 */ wt[13] = 28.054180; /*C2H4 */ wt[14] = 30.070120; /*C2H6 */ wt[15] = 17.030610; /*NH3 */ wt[16] = 30.006100; /*NO */ wt[17] = 27.025820; /*HCN */ wt[18] = 28.013400; /*N2 */ return; } /*save atomic weights into array */ void atomicWeight(double * restrict awt) { awt[0] = 15.999400; /*O */ awt[1] = 1.007970; /*H */ awt[2] = 12.011150; /*C */ awt[3] = 14.006700; /*N */ return; } /* get temperature given internal energy in mass units and mass fracs */ void GET_T_GIVEN_EY(double * restrict e, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict t, int * ierr) { #ifdef CONVERGENCE const int maxiter = 5000; const double tol = 1.e-12; #else const int maxiter = 200; const double tol = 1.e-6; #endif double ein = *e; double tmin = 90;/*max lower bound for thermo def */ double tmax = 4000;/*min upper bound for thermo def */ double e1,emin,emax,cv,t1,dt; int i;/* loop counter */ CKUBMS(&tmin, y, iwrk, rwrk, &emin); CKUBMS(&tmax, y, iwrk, rwrk, &emax); if (ein < emin) { /*Linear Extrapolation below tmin */ CKCVBS(&tmin, y, iwrk, rwrk, &cv); *t = tmin - (emin-ein)/cv; *ierr = 1; return; } if (ein > emax) { /*Linear Extrapolation above tmax */ CKCVBS(&tmax, y, iwrk, rwrk, &cv); *t = tmax - (emax-ein)/cv; *ierr = 1; return; } t1 = *t; if (t1 < tmin || t1 > tmax) { t1 = tmin + (tmax-tmin)/(emax-emin)*(ein-emin); } for (i = 0; i < maxiter; ++i) { CKUBMS(&t1,y,iwrk,rwrk,&e1); CKCVBS(&t1,y,iwrk,rwrk,&cv); dt = (ein - e1) / cv; if (dt > 100.) { dt = 100.; } else if (dt < -100.) { dt = -100.; } else if (fabs(dt) < tol) break; else if (t1+dt == t1) break; t1 += dt; } *t = t1; *ierr = 0; return; } /* get temperature given enthalpy in mass units and mass fracs */ void GET_T_GIVEN_HY(double * restrict h, double * restrict y, int * iwrk, double * restrict rwrk, double * restrict t, int * ierr) { #ifdef CONVERGENCE const int maxiter = 5000; const double tol = 1.e-12; #else const int maxiter = 200; const double tol = 1.e-6; #endif double hin = *h; double tmin = 90;/*max lower bound for thermo def */ double tmax = 4000;/*min upper bound for thermo def */ double h1,hmin,hmax,cp,t1,dt; int i;/* loop counter */ CKHBMS(&tmin, y, iwrk, rwrk, &hmin); CKHBMS(&tmax, y, iwrk, rwrk, &hmax); if (hin < hmin) { /*Linear Extrapolation below tmin */ CKCPBS(&tmin, y, iwrk, rwrk, &cp); *t = tmin - (hmin-hin)/cp; *ierr = 1; return; } if (hin > hmax) { /*Linear Extrapolation above tmax */ CKCPBS(&tmax, y, iwrk, rwrk, &cp); *t = tmax - (hmax-hin)/cp; *ierr = 1; return; } t1 = *t; if (t1 < tmin || t1 > tmax) { t1 = tmin + (tmax-tmin)/(hmax-hmin)*(hin-hmin); } for (i = 0; i < maxiter; ++i) { CKHBMS(&t1,y,iwrk,rwrk,&h1); CKCPBS(&t1,y,iwrk,rwrk,&cp); dt = (hin - h1) / cp; if (dt > 100.) { dt = 100.; } else if (dt < -100.) { dt = -100.; } else if (fabs(dt) < tol) break; else if (t1+dt == t1) break; t1 += dt; } *t = t1; *ierr = 0; return; } /*compute the critical parameters for each species */ void GET_CRITPARAMS(double * restrict Tci, double * restrict ai, double * restrict bi, double * restrict acentric_i) { double EPS[19]; double SIG[19]; double wt[19]; double avogadro = 6.02214199e23; double boltzmann = 1.3806503e-16; //we work in CGS double Rcst = 83.144598; //in bar [CGS] ! egtransetEPS(EPS); egtransetSIG(SIG); molecularWeight(wt); /*species 0: H2 */ /*Imported from NIST */ Tci[0] = 33.145000 ; ai[0] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[0],2.0) / (pow(2.015880,2.0) * 12.964000); bi[0] = 0.08664 * Rcst * Tci[0] / (2.015880 * 12.964000); acentric_i[0] = -0.219000 ; /*species 1: H */ Tci[1] = 1.316 * EPS[1] ; ai[1] = (5.55 * pow(avogadro,2.0) * EPS[1]*boltzmann * pow(1e-8*SIG[1],3.0) ) / (pow(wt[1],2.0)); bi[1] = 0.855 * avogadro * pow(1e-8*SIG[1],3.0) / (wt[1]); acentric_i[1] = 0.0 ; /*species 2: O2 */ /*Imported from NIST */ Tci[2] = 154.581000 ; ai[2] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[2],2.0) / (pow(31.998800,2.0) * 50.430466); bi[2] = 0.08664 * Rcst * Tci[2] / (31.998800 * 50.430466); acentric_i[2] = 0.022200 ; /*species 3: OH */ Tci[3] = 1.316 * EPS[3] ; ai[3] = (5.55 * pow(avogadro,2.0) * EPS[3]*boltzmann * pow(1e-8*SIG[3],3.0) ) / (pow(wt[3],2.0)); bi[3] = 0.855 * avogadro * pow(1e-8*SIG[3],3.0) / (wt[3]); acentric_i[3] = 0.0 ; /*species 4: H2O */ /*Imported from NIST */ Tci[4] = 647.096000 ; ai[4] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[4],2.0) / (pow(18.015340,2.0) * 220.640000); bi[4] = 0.08664 * Rcst * Tci[4] / (18.015340 * 220.640000); acentric_i[4] = 0.344300 ; /*species 5: HO2 */ Tci[5] = 1.316 * EPS[5] ; ai[5] = (5.55 * pow(avogadro,2.0) * EPS[5]*boltzmann * pow(1e-8*SIG[5],3.0) ) / (pow(wt[5],2.0)); bi[5] = 0.855 * avogadro * pow(1e-8*SIG[5],3.0) / (wt[5]); acentric_i[5] = 0.0 ; /*species 6: H2O2 */ Tci[6] = 1.316 * EPS[6] ; ai[6] = (5.55 * pow(avogadro,2.0) * EPS[6]*boltzmann * pow(1e-8*SIG[6],3.0) ) / (pow(wt[6],2.0)); bi[6] = 0.855 * avogadro * pow(1e-8*SIG[6],3.0) / (wt[6]); acentric_i[6] = 0.0 ; /*species 7: CH3 */ Tci[7] = 1.316 * EPS[7] ; ai[7] = (5.55 * pow(avogadro,2.0) * EPS[7]*boltzmann * pow(1e-8*SIG[7],3.0) ) / (pow(wt[7],2.0)); bi[7] = 0.855 * avogadro * pow(1e-8*SIG[7],3.0) / (wt[7]); acentric_i[7] = 0.0 ; /*species 8: CH4 */ /*Imported from NIST */ Tci[8] = 190.560000 ; ai[8] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[8],2.0) / (pow(16.043030,2.0) * 45.990000); bi[8] = 0.08664 * Rcst * Tci[8] / (16.043030 * 45.990000); acentric_i[8] = 0.011000 ; /*species 9: CO */ /*Imported from NIST */ Tci[9] = 132.850000 ; ai[9] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[9],2.0) / (pow(28.010000,2.0) * 34.940000); bi[9] = 0.08664 * Rcst * Tci[9] / (28.010000 * 34.940000); acentric_i[9] = 0.045000 ; /*species 10: CO2 */ /*Imported from NIST */ Tci[10] = 304.120000 ; ai[10] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[10],2.0) / (pow(44.009950,2.0) * 73.740000); bi[10] = 0.08664 * Rcst * Tci[10] / (44.009950 * 73.740000); acentric_i[10] = 0.225000 ; /*species 11: CH2O */ Tci[11] = 1.316 * EPS[11] ; ai[11] = (5.55 * pow(avogadro,2.0) * EPS[11]*boltzmann * pow(1e-8*SIG[11],3.0) ) / (pow(wt[11],2.0)); bi[11] = 0.855 * avogadro * pow(1e-8*SIG[11],3.0) / (wt[11]); acentric_i[11] = 0.0 ; /*species 12: C2H2 */ /*Imported from NIST */ Tci[12] = 308.300000 ; ai[12] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[12],2.0) / (pow(26.038000,2.0) * 61.140000); bi[12] = 0.08664 * Rcst * Tci[12] / (26.038000 * 61.140000); acentric_i[12] = 0.189000 ; /*species 13: C2H4 */ /*Imported from NIST */ Tci[13] = 282.340000 ; ai[13] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[13],2.0) / (pow(28.054000,2.0) * 50.410000); bi[13] = 0.08664 * Rcst * Tci[13] / (28.054000 * 50.410000); acentric_i[13] = 0.087000 ; /*species 14: C2H6 */ /*Imported from NIST */ Tci[14] = 305.320000 ; ai[14] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[14],2.0) / (pow(30.070120,2.0) * 48.720000); bi[14] = 0.08664 * Rcst * Tci[14] / (30.070120 * 48.720000); acentric_i[14] = 0.099000 ; /*species 15: NH3 */ Tci[15] = 1.316 * EPS[15] ; ai[15] = (5.55 * pow(avogadro,2.0) * EPS[15]*boltzmann * pow(1e-8*SIG[15],3.0) ) / (pow(wt[15],2.0)); bi[15] = 0.855 * avogadro * pow(1e-8*SIG[15],3.0) / (wt[15]); acentric_i[15] = 0.0 ; /*species 16: NO */ /*Imported from NIST */ Tci[16] = 180.000000 ; ai[16] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[16],2.0) / (pow(30.006000,2.0) * 64.800000); bi[16] = 0.08664 * Rcst * Tci[16] / (30.006000 * 64.800000); acentric_i[16] = 0.582000 ; /*species 17: HCN */ Tci[17] = 1.316 * EPS[17] ; ai[17] = (5.55 * pow(avogadro,2.0) * EPS[17]*boltzmann * pow(1e-8*SIG[17],3.0) ) / (pow(wt[17],2.0)); bi[17] = 0.855 * avogadro * pow(1e-8*SIG[17],3.0) / (wt[17]); acentric_i[17] = 0.0 ; /*species 18: N2 */ /*Imported from NIST */ Tci[18] = 126.192000 ; ai[18] = 1e6 * 0.42748 * pow(Rcst,2.0) * pow(Tci[18],2.0) / (pow(28.013400,2.0) * 33.958000); bi[18] = 0.08664 * Rcst * Tci[18] / (28.013400 * 33.958000); acentric_i[18] = 0.037200 ; return; } /* End of file */ #if defined(BL_FORT_USE_UPPERCASE) #define egtransetLENIMC EGTRANSETLENIMC #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetLENIMC egtransetlenimc #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetLENIMC egtransetlenimc_ #endif void egtransetLENIMC(int* LENIMC) { *LENIMC = 70;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetLENRMC EGTRANSETLENRMC #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetLENRMC egtransetlenrmc #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetLENRMC egtransetlenrmc_ #endif void egtransetLENRMC(int* LENRMC) { *LENRMC = 6086;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetNO EGTRANSETNO #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetNO egtransetno #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetNO egtransetno_ #endif void egtransetNO(int* NO) { *NO = 4;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetKK EGTRANSETKK #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetKK egtransetkk #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetKK egtransetkk_ #endif void egtransetKK(int* KK) { *KK = 17;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetNLITE EGTRANSETNLITE #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetNLITE egtransetnlite #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetNLITE egtransetnlite_ #endif void egtransetNLITE(int* NLITE) { *NLITE = 2;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetPATM EGTRANSETPATM #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetPATM egtransetpatm #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetPATM egtransetpatm_ #endif void egtransetPATM(double* PATM) { *PATM = 0.1013250000000000E+07;} #if defined(BL_FORT_USE_UPPERCASE) #define egtransetWT EGTRANSETWT #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetWT egtransetwt #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetWT egtransetwt_ #endif void egtransetWT(double* WT) { WT[ 0] = 0.2015939950942993E+01; WT[ 1] = 0.1007969975471497E+01; WT[ 2] = 0.3199880027770996E+02; WT[ 3] = 0.1700737011432648E+02; WT[ 4] = 0.1801534008979797E+02; WT[ 5] = 0.3300677025318146E+02; WT[ 6] = 0.3401474022865295E+02; WT[ 7] = 0.1503506028652191E+02; WT[ 8] = 0.1604303026199341E+02; WT[ 9] = 0.2801055049896240E+02; WT[ 10] = 0.4400995063781738E+02; WT[ 11] = 0.3002649044990540E+02; WT[ 12] = 0.2603824067115784E+02; WT[ 13] = 0.2805418062210083E+02; WT[ 14] = 0.3007012057304382E+02; WT[ 15] = 0.1703060948848724E+02; WT[ 16] = 0.1400669956207275E+02; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetEPS EGTRANSETEPS #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetEPS egtranseteps #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetEPS egtranseteps_ #endif void egtransetEPS(double* EPS) { EPS[ 0] = 0.3800000000000000E+02; EPS[ 1] = 0.1450000000000000E+03; EPS[ 2] = 0.1074000000000000E+03; EPS[ 3] = 0.8000000000000000E+02; EPS[ 4] = 0.5724000000000000E+03; EPS[ 5] = 0.1074000000000000E+03; EPS[ 6] = 0.1074000000000000E+03; EPS[ 7] = 0.1440000000000000E+03; EPS[ 8] = 0.1414000000000000E+03; EPS[ 9] = 0.9809999999999999E+02; EPS[ 10] = 0.2440000000000000E+03; EPS[ 11] = 0.4980000000000000E+03; EPS[ 12] = 0.2090000000000000E+03; EPS[ 13] = 0.2808000000000000E+03; EPS[ 14] = 0.2523000000000000E+03; EPS[ 15] = 0.4810000000000000E+03; EPS[ 16] = 0.7140000000000001E+02; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetSIG EGTRANSETSIG #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetSIG egtransetsig #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetSIG egtransetsig_ #endif void egtransetSIG(double* SIG) { SIG[ 0] = 0.2920000000000000E+01; SIG[ 1] = 0.2050000000000000E+01; SIG[ 2] = 0.3458000000000000E+01; SIG[ 3] = 0.2750000000000000E+01; SIG[ 4] = 0.2605000000000000E+01; SIG[ 5] = 0.3458000000000000E+01; SIG[ 6] = 0.3458000000000000E+01; SIG[ 7] = 0.3800000000000000E+01; SIG[ 8] = 0.3746000000000000E+01; SIG[ 9] = 0.3650000000000000E+01; SIG[ 10] = 0.3763000000000000E+01; SIG[ 11] = 0.3590000000000000E+01; SIG[ 12] = 0.4100000000000000E+01; SIG[ 13] = 0.3971000000000000E+01; SIG[ 14] = 0.4302000000000000E+01; SIG[ 15] = 0.2920000000000000E+01; SIG[ 16] = 0.3298000000000000E+01; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetDIP EGTRANSETDIP #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetDIP egtransetdip #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetDIP egtransetdip_ #endif void egtransetDIP(double* DIP) { DIP[ 0] = 0.0000000000000000E+00; DIP[ 1] = 0.0000000000000000E+00; DIP[ 2] = 0.0000000000000000E+00; DIP[ 3] = 0.0000000000000000E+00; DIP[ 4] = 0.1844000000000000E+01; DIP[ 5] = 0.0000000000000000E+00; DIP[ 6] = 0.0000000000000000E+00; DIP[ 7] = 0.0000000000000000E+00; DIP[ 8] = 0.0000000000000000E+00; DIP[ 9] = 0.0000000000000000E+00; DIP[ 10] = 0.0000000000000000E+00; DIP[ 11] = 0.0000000000000000E+00; DIP[ 12] = 0.0000000000000000E+00; DIP[ 13] = 0.0000000000000000E+00; DIP[ 14] = 0.0000000000000000E+00; DIP[ 15] = 0.1470000000000000E+01; DIP[ 16] = 0.0000000000000000E+00; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetPOL EGTRANSETPOL #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetPOL egtransetpol #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetPOL egtransetpol_ #endif void egtransetPOL(double* POL) { POL[ 0] = 0.7900000000000000E+00; POL[ 1] = 0.0000000000000000E+00; POL[ 2] = 0.1600000000000000E+01; POL[ 3] = 0.0000000000000000E+00; POL[ 4] = 0.0000000000000000E+00; POL[ 5] = 0.0000000000000000E+00; POL[ 6] = 0.0000000000000000E+00; POL[ 7] = 0.0000000000000000E+00; POL[ 8] = 0.2600000000000000E+01; POL[ 9] = 0.1950000000000000E+01; POL[ 10] = 0.2650000000000000E+01; POL[ 11] = 0.0000000000000000E+00; POL[ 12] = 0.0000000000000000E+00; POL[ 13] = 0.0000000000000000E+00; POL[ 14] = 0.0000000000000000E+00; POL[ 15] = 0.0000000000000000E+00; POL[ 16] = 0.0000000000000000E+00; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetZROT EGTRANSETZROT #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetZROT egtransetzrot #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetZROT egtransetzrot_ #endif void egtransetZROT(double* ZROT) { ZROT[ 0] = 0.2800000000000000E+03; ZROT[ 1] = 0.0000000000000000E+00; ZROT[ 2] = 0.3800000000000000E+01; ZROT[ 3] = 0.0000000000000000E+00; ZROT[ 4] = 0.4000000000000000E+01; ZROT[ 5] = 0.1000000000000000E+01; ZROT[ 6] = 0.3800000000000000E+01; ZROT[ 7] = 0.0000000000000000E+00; ZROT[ 8] = 0.1300000000000000E+02; ZROT[ 9] = 0.1800000000000000E+01; ZROT[ 10] = 0.2100000000000000E+01; ZROT[ 11] = 0.2000000000000000E+01; ZROT[ 12] = 0.2500000000000000E+01; ZROT[ 13] = 0.1500000000000000E+01; ZROT[ 14] = 0.1500000000000000E+01; ZROT[ 15] = 0.1000000000000000E+02; ZROT[ 16] = 0.0000000000000000E+00; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetNLIN EGTRANSETNLIN #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetNLIN egtransetnlin #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetNLIN egtransetnlin_ #endif void egtransetNLIN(int* NLIN) { NLIN[ 0] = 1; NLIN[ 1] = 0; NLIN[ 2] = 1; NLIN[ 3] = 1; NLIN[ 4] = 2; NLIN[ 5] = 2; NLIN[ 6] = 2; NLIN[ 7] = 1; NLIN[ 8] = 2; NLIN[ 9] = 1; NLIN[ 10] = 1; NLIN[ 11] = 2; NLIN[ 12] = 1; NLIN[ 13] = 2; NLIN[ 14] = 2; NLIN[ 15] = 2; NLIN[ 16] = 0; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetCOFLAM EGTRANSETCOFLAM #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetCOFLAM egtransetcoflam #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetCOFLAM egtransetcoflam_ #endif void egtransetCOFLAM(double* COFLAM) { COFLAM[ 0] = 0.4338938909590841E+01; COFLAM[ 1] = 0.1557129190255232E+01; COFLAM[ 2] = -0.1611482772000911E+00; COFLAM[ 3] = 0.9924831871819461E-02; COFLAM[ 4] = -0.1277787249296346E+01; COFLAM[ 5] = 0.3820054734917150E+01; COFLAM[ 6] = -0.4198233798779158E+00; COFLAM[ 7] = 0.1850208398735055E-01; COFLAM[ 8] = 0.5325069412912258E+00; COFLAM[ 9] = 0.1869914528199901E+01; COFLAM[ 10] = -0.1314362832820327E+00; COFLAM[ 11] = 0.5215120926063267E-02; COFLAM[ 12] = 0.9093696928027398E+01; COFLAM[ 13] = -0.1120775592691738E+01; COFLAM[ 14] = 0.2389873914448641E+00; COFLAM[ 15] = -0.9739555323602451E-02; COFLAM[ 16] = 0.1823299080601272E+02; COFLAM[ 17] = -0.6774533358601863E+01; COFLAM[ 18] = 0.1218719282523822E+01; COFLAM[ 19] = -0.6135010154070134E-01; COFLAM[ 20] = 0.3326317596296849E+01; COFLAM[ 21] = 0.4132335554940667E+00; COFLAM[ 22] = 0.1130570823333984E+00; COFLAM[ 23] = -0.7338162598088820E-02; COFLAM[ 24] = 0.2915877425653172E+01; COFLAM[ 25] = 0.4587330741194222E+00; COFLAM[ 26] = 0.1387858388240978E+00; COFLAM[ 27] = -0.9951989822150117E-02; COFLAM[ 28] = 0.1076771824317687E+02; COFLAM[ 29] = -0.3230785742845311E+01; COFLAM[ 30] = 0.7028613656761165E+00; COFLAM[ 31] = -0.3786794222679780E-01; COFLAM[ 32] = 0.1770109820287010E+02; COFLAM[ 33] = -0.6715184244214581E+01; COFLAM[ 34] = 0.1263352812473795E+01; COFLAM[ 35] = -0.6629210623948648E-01; COFLAM[ 36] = 0.8169761711928375E+01; COFLAM[ 37] = -0.1536354590024332E+01; COFLAM[ 38] = 0.3677852316201770E+00; COFLAM[ 39] = -0.1908151636745373E-01; COFLAM[ 40] = -0.8741249063434607E+01; COFLAM[ 41] = 0.4789682737843632E+01; COFLAM[ 42] = -0.4182583551792970E+00; COFLAM[ 43] = 0.1350148479415579E-01; COFLAM[ 44] = 0.1432241064124226E+02; COFLAM[ 45] = -0.6063127607975618E+01; COFLAM[ 46] = 0.1238070730356745E+01; COFLAM[ 47] = -0.6822324216312974E-01; COFLAM[ 48] = -0.1080654352351750E+02; COFLAM[ 49] = 0.5871580561001701E+01; COFLAM[ 50] = -0.5858009165203976E+00; COFLAM[ 51] = 0.2242112198055643E-01; COFLAM[ 52] = -0.4034386834241054E+01; COFLAM[ 53] = 0.1906845175798028E+01; COFLAM[ 54] = 0.1176313823060724E+00; COFLAM[ 55] = -0.1610854731203796E-01; COFLAM[ 56] = -0.2116070664089148E+01; COFLAM[ 57] = 0.9961322379018972E+00; COFLAM[ 58] = 0.2612385762947667E+00; COFLAM[ 59] = -0.2335852593974065E-01; COFLAM[ 60] = 0.1756249168236376E+02; COFLAM[ 61] = -0.6844841344645484E+01; COFLAM[ 62] = 0.1296574793469918E+01; COFLAM[ 63] = -0.6830286748937907E-01; COFLAM[ 64] = 0.1334087340220970E+01; COFLAM[ 65] = 0.1967564865885963E+01; COFLAM[ 66] = -0.1801563268324271E+00; COFLAM[ 67] = 0.8161858212342093E-02; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetCOFETA EGTRANSETCOFETA #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetCOFETA egtransetcofeta #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetCOFETA egtransetcofeta_ #endif void egtransetCOFETA(double* COFETA) { COFETA[ 0] = -0.1405365243967108E+02; COFETA[ 1] = 0.1093067315260161E+01; COFETA[ 2] = -0.6261814846952836E-01; COFETA[ 3] = 0.2905012497485487E-02; COFETA[ 4] = -0.2082770253853309E+02; COFETA[ 5] = 0.3820054734917064E+01; COFETA[ 6] = -0.4198233798779034E+00; COFETA[ 7] = 0.1850208398734995E-01; COFETA[ 8] = -0.1788787183918792E+02; COFETA[ 9] = 0.2980942390384383E+01; COFETA[ 10] = -0.3137212871769931E+00; COFETA[ 11] = 0.1402845871347659E-01; COFETA[ 12] = -0.1575591740228496E+02; COFETA[ 13] = 0.2214372539700379E+01; COFETA[ 14] = -0.2131246920584266E+00; COFETA[ 15] = 0.9629058498016490E-02; COFETA[ 16] = -0.1132071455875007E+02; COFETA[ 17] = -0.1024187591396996E+01; COFETA[ 18] = 0.3672551958155785E+00; COFETA[ 19] = -0.2140495811549247E-01; COFETA[ 20] = -0.1787236469476987E+02; COFETA[ 21] = 0.2980942390384401E+01; COFETA[ 22] = -0.3137212871769956E+00; COFETA[ 23] = 0.1402845871347671E-01; COFETA[ 24] = -0.1785732406117402E+02; COFETA[ 25] = 0.2980942390384431E+01; COFETA[ 26] = -0.3137212871770002E+00; COFETA[ 27] = 0.1402845871347693E-01; COFETA[ 28] = -0.2064817961278261E+02; COFETA[ 29] = 0.3796664365547116E+01; COFETA[ 30] = -0.4168591838616045E+00; COFETA[ 31] = 0.1837669926760990E-01; COFETA[ 32] = -0.2044795093120063E+02; COFETA[ 33] = 0.3746140041781780E+01; COFETA[ 34] = -0.4106325045512437E+00; COFETA[ 35] = 0.1812122592865459E-01; COFETA[ 36] = -0.1745394886003354E+02; COFETA[ 37] = 0.2749779734238378E+01; COFETA[ 38] = -0.2838005922559860E+00; COFETA[ 39] = 0.1273750763474062E-01; COFETA[ 40] = -0.2279534579079101E+02; COFETA[ 41] = 0.4622798720286126E+01; COFETA[ 42] = -0.4997444888565643E+00; COFETA[ 43] = 0.2095793339101399E-01; COFETA[ 44] = -0.1574565551467780E+02; COFETA[ 45] = 0.9879045622370226E+00; COFETA[ 46] = 0.7005046117242672E-01; COFETA[ 47] = -0.7652880399373136E-02; COFETA[ 48] = -0.2285054221476539E+02; COFETA[ 49] = 0.4573684124304381E+01; COFETA[ 50] = -0.5044627764440257E+00; COFETA[ 51] = 0.2162047229656920E-01; COFETA[ 52] = -0.2294894266555372E+02; COFETA[ 53] = 0.4436068808351478E+01; COFETA[ 54] = -0.4620857825400307E+00; COFETA[ 55] = 0.1877687773259413E-01; COFETA[ 56] = -0.2324874285445497E+02; COFETA[ 57] = 0.4594844249509825E+01; COFETA[ 58] = -0.4931221039570846E+00; COFETA[ 59] = 0.2054776726722393E-01; COFETA[ 60] = -0.1419898917157052E+02; COFETA[ 61] = 0.3629587083500767E+00; COFETA[ 62] = 0.1568120182105773E+00; COFETA[ 63] = -0.1151267609047790E-01; COFETA[ 64] = -0.1558423057668358E+02; COFETA[ 65] = 0.1967564865886029E+01; COFETA[ 66] = -0.1801563268324368E+00; COFETA[ 67] = 0.8161858212342565E-02; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetCOFD EGTRANSETCOFD #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetCOFD egtransetcofd #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetCOFD egtransetcofd_ #endif void egtransetCOFD(double* COFD) { COFD[ 0] = -0.1041995820481732E+02; COFD[ 1] = 0.2234441574336671E+01; COFD[ 2] = -0.8113717628974293E-01; COFD[ 3] = 0.3771369728593280E-02; COFD[ 4] = -0.1246996149641938E+02; COFD[ 5] = 0.3218029211436469E+01; COFD[ 6] = -0.2110489360993846E+00; COFD[ 7] = 0.9480877224339204E-02; COFD[ 8] = -0.1309173178181482E+02; COFD[ 9] = 0.3085278377844914E+01; COFD[ 10] = -0.1946824097426824E+00; COFD[ 11] = 0.8807381240537916E-02; COFD[ 12] = -0.1175032758512814E+02; COFD[ 13] = 0.2642045353939402E+01; COFD[ 14] = -0.1332637450759486E+00; COFD[ 15] = 0.5973546569611733E-02; COFD[ 16] = -0.1757366663670086E+02; COFD[ 17] = 0.4778618797909657E+01; COFD[ 18] = -0.3996041319366184E+00; COFD[ 19] = 0.1705904378841811E-01; COFD[ 20] = -0.1309613046501959E+02; COFD[ 21] = 0.3086801219615145E+01; COFD[ 22] = -0.1948957472387874E+00; COFD[ 23] = 0.8817294833761086E-02; COFD[ 24] = -0.1310029609771552E+02; COFD[ 25] = 0.3088245187916686E+01; COFD[ 26] = -0.1950980328845662E+00; COFD[ 27] = 0.8826694775135658E-02; COFD[ 28] = -0.1401582227027964E+02; COFD[ 29] = 0.3415426664334749E+01; COFD[ 30] = -0.2385853115052575E+00; COFD[ 31] = 0.1075469512610122E-01; COFD[ 32] = -0.1394568249588876E+02; COFD[ 33] = 0.3392701225291731E+01; COFD[ 34] = -0.2355263017693934E+00; COFD[ 35] = 0.1061747669734484E-01; COFD[ 36] = -0.1288505703505633E+02; COFD[ 37] = 0.2980129383938292E+01; COFD[ 38] = -0.1801545917674105E+00; COFD[ 39] = 0.8138117217492757E-02; COFD[ 40] = -0.1558361674716745E+02; COFD[ 41] = 0.3987098568284434E+01; COFD[ 42] = -0.3109866036899985E+00; COFD[ 43] = 0.1380795341338578E-01; COFD[ 44] = -0.1688564690991911E+02; COFD[ 45] = 0.4415865473479337E+01; COFD[ 46] = -0.3564104485793251E+00; COFD[ 47] = 0.1533855847922275E-01; COFD[ 48] = -0.1548207029093904E+02; COFD[ 49] = 0.3939084188623417E+01; COFD[ 50] = -0.3072761108436687E+00; COFD[ 51] = 0.1375770270895890E-01; COFD[ 52] = -0.1606152931877502E+02; COFD[ 53] = 0.4146430359164761E+01; COFD[ 54] = -0.3312210923439469E+00; COFD[ 55] = 0.1466430884967795E-01; COFD[ 56] = -0.1596236229610858E+02; COFD[ 57] = 0.4079842750882008E+01; COFD[ 58] = -0.3231960602071978E+00; COFD[ 59] = 0.1434305777680907E-01; COFD[ 60] = -0.1682806034335371E+02; COFD[ 61] = 0.4485450500929320E+01; COFD[ 62] = -0.3655695289846634E+00; COFD[ 63] = 0.1574614737371121E-01; COFD[ 64] = -0.1163276178298392E+02; COFD[ 65] = 0.2530205071288130E+01; COFD[ 66] = -0.1183776350934922E+00; COFD[ 67] = 0.5312988352557955E-02; COFD[ 68] = -0.1246996149641938E+02; COFD[ 69] = 0.3218029211436469E+01; COFD[ 70] = -0.2110489360993846E+00; COFD[ 71] = 0.9480877224339204E-02; COFD[ 72] = -0.1523325703608638E+02; COFD[ 73] = 0.4393426193693418E+01; COFD[ 74] = -0.3557313428561681E+00; COFD[ 75] = 0.1541554803417400E-01; COFD[ 76] = -0.1615679289714481E+02; COFD[ 77] = 0.4416835307133869E+01; COFD[ 78] = -0.3582737234170646E+00; COFD[ 79] = 0.1548663572743747E-01; COFD[ 80] = -0.1489056810719442E+02; COFD[ 81] = 0.4079672697171075E+01; COFD[ 82] = -0.3197193422647769E+00; COFD[ 83] = 0.1404463618351796E-01; COFD[ 84] = -0.1615075966577466E+02; COFD[ 85] = 0.4076548482999812E+01; COFD[ 86] = -0.2637510941604614E+00; COFD[ 87] = 0.9371841080052064E-02; COFD[ 88] = -0.1616058613782880E+02; COFD[ 89] = 0.4418087193226073E+01; COFD[ 90] = -0.3584223903851448E+00; COFD[ 91] = 0.1549243249303281E-01; COFD[ 92] = -0.1616421015670871E+02; COFD[ 93] = 0.4419285820914456E+01; COFD[ 94] = -0.3585647608630650E+00; COFD[ 95] = 0.1549798503551403E-01; COFD[ 96] = -0.1668220221378553E+02; COFD[ 97] = 0.4517665522196412E+01; COFD[ 98] = -0.3643177404654742E+00; COFD[ 99] = 0.1544861119982853E-01; COFD[ 100] = -0.1661124059439949E+02; COFD[ 101] = 0.4499983815327449E+01; COFD[ 102] = -0.3624203284397300E+00; COFD[ 103] = 0.1538350856590451E-01; COFD[ 104] = -0.1640877269708571E+02; COFD[ 105] = 0.4519498926662536E+01; COFD[ 106] = -0.3750329779403845E+00; COFD[ 107] = 0.1635855421757920E-01; COFD[ 108] = -0.1664237108262573E+02; COFD[ 109] = 0.4321207774376617E+01; COFD[ 110] = -0.3181315549506706E+00; COFD[ 111] = 0.1258308183870717E-01; COFD[ 112] = -0.1567567878102999E+02; COFD[ 113] = 0.3706302510623138E+01; COFD[ 114] = -0.2096236244277931E+00; COFD[ 115] = 0.6748353057110522E-02; COFD[ 116] = -0.1685361380845761E+02; COFD[ 117] = 0.4411251776453823E+01; COFD[ 118] = -0.3350756131548513E+00; COFD[ 119] = 0.1353157937321782E-01; COFD[ 120] = -0.1635823810097287E+02; COFD[ 121] = 0.4123977007004703E+01; COFD[ 122] = -0.2854728908229589E+00; COFD[ 123] = 0.1088433914065527E-01; COFD[ 124] = -0.1646195534760534E+02; COFD[ 125] = 0.4141822899037704E+01; COFD[ 126] = -0.2892308013569180E+00; COFD[ 127] = 0.1109614462742981E-01; COFD[ 128] = -0.1626359848098758E+02; COFD[ 129] = 0.4116788683843708E+01; COFD[ 130] = -0.2733289330957227E+00; COFD[ 131] = 0.9943035956817482E-02; COFD[ 132] = -0.1522605770447405E+02; COFD[ 133] = 0.4154863253653862E+01; COFD[ 134] = -0.3321404775716639E+00; COFD[ 135] = 0.1469592836326692E-01; COFD[ 136] = -0.1309173178181482E+02; COFD[ 137] = 0.3085278377844914E+01; COFD[ 138] = -0.1946824097426824E+00; COFD[ 139] = 0.8807381240537916E-02; COFD[ 140] = -0.1615679289714481E+02; COFD[ 141] = 0.4416835307133869E+01; COFD[ 142] = -0.3582737234170646E+00; COFD[ 143] = 0.1548663572743747E-01; COFD[ 144] = -0.1633859102926806E+02; COFD[ 145] = 0.3804061718963007E+01; COFD[ 146] = -0.2844545503177112E+00; COFD[ 147] = 0.1254577088876504E-01; COFD[ 148] = -0.1549441379638191E+02; COFD[ 149] = 0.3661937775617350E+01; COFD[ 150] = -0.2686571425887965E+00; COFD[ 151] = 0.1197472750180553E-01; COFD[ 152] = -0.1922081039841695E+02; COFD[ 153] = 0.4711535347815869E+01; COFD[ 154] = -0.3619579159000997E+00; COFD[ 155] = 0.1426886476331241E-01; COFD[ 156] = -0.1634649054694938E+02; COFD[ 157] = 0.3804144246517877E+01; COFD[ 158] = -0.2844651891354975E+00; COFD[ 159] = 0.1254622626209081E-01; COFD[ 160] = -0.1635443062264980E+02; COFD[ 161] = 0.3804381702146611E+01; COFD[ 162] = -0.2844957999638338E+00; COFD[ 163] = 0.1254753649276844E-01; COFD[ 164] = -0.1710012222365139E+02; COFD[ 165] = 0.4123808736773267E+01; COFD[ 166] = -0.3236376370297240E+00; COFD[ 167] = 0.1414381001550686E-01; COFD[ 168] = -0.1705130515010214E+02; COFD[ 169] = 0.4103994885241071E+01; COFD[ 170] = -0.3212499365446575E+00; COFD[ 171] = 0.1404820978963865E-01; COFD[ 172] = -0.1615768146554276E+02; COFD[ 173] = 0.3734150883385773E+01; COFD[ 174] = -0.2760989842105895E+00; COFD[ 175] = 0.1221438663500826E-01; COFD[ 176] = -0.1871735010457793E+02; COFD[ 177] = 0.4573421885700214E+01; COFD[ 178] = -0.3757214086933051E+00; COFD[ 179] = 0.1614451502251515E-01; COFD[ 180] = -0.1977364410044468E+02; COFD[ 181] = 0.4876531592391508E+01; COFD[ 182] = -0.3981741984755758E+00; COFD[ 183] = 0.1643476290195535E-01; COFD[ 184] = -0.1830650296367939E+02; COFD[ 185] = 0.4452394507404697E+01; COFD[ 186] = -0.3624991200767191E+00; COFD[ 187] = 0.1567286266089603E-01; COFD[ 188] = -0.1904759289384530E+02; COFD[ 189] = 0.4700929573683383E+01; COFD[ 190] = -0.3903608191209737E+00; COFD[ 191] = 0.1670229359855150E-01; COFD[ 192] = -0.1883799365221673E+02; COFD[ 193] = 0.4594611640098751E+01; COFD[ 194] = -0.3781168670160998E+00; COFD[ 195] = 0.1623467419613562E-01; COFD[ 196] = -0.1934710272078301E+02; COFD[ 197] = 0.4822779400529180E+01; COFD[ 198] = -0.3871228449439424E+00; COFD[ 199] = 0.1578686341252481E-01; COFD[ 200] = -0.1527049784849730E+02; COFD[ 201] = 0.3538365317994180E+01; COFD[ 202] = -0.2526814234121028E+00; COFD[ 203] = 0.1128573168209360E-01; COFD[ 204] = -0.1175032758512814E+02; COFD[ 205] = 0.2642045353939402E+01; COFD[ 206] = -0.1332637450759486E+00; COFD[ 207] = 0.5973546569611733E-02; COFD[ 208] = -0.1489056810719442E+02; COFD[ 209] = 0.4079672697171075E+01; COFD[ 210] = -0.3197193422647769E+00; COFD[ 211] = 0.1404463618351796E-01; COFD[ 212] = -0.1549441379638191E+02; COFD[ 213] = 0.3661937775617350E+01; COFD[ 214] = -0.2686571425887965E+00; COFD[ 215] = 0.1197472750180553E-01; COFD[ 216] = -0.1408727594805337E+02; COFD[ 217] = 0.3263692027745076E+01; COFD[ 218] = -0.2164586669743292E+00; COFD[ 219] = 0.9693817632062094E-02; COFD[ 220] = -0.1876923157317771E+02; COFD[ 221] = 0.4853854184816717E+01; COFD[ 222] = -0.3998497982364926E+00; COFD[ 223] = 0.1669227468405473E-01; COFD[ 224] = -0.1551249966394157E+02; COFD[ 225] = 0.3667301435894143E+01; COFD[ 226] = -0.2693892845913942E+00; COFD[ 227] = 0.1200791993248851E-01; COFD[ 228] = -0.1553013778710249E+02; COFD[ 229] = 0.3672587405633829E+01; COFD[ 230] = -0.2701107938194129E+00; COFD[ 231] = 0.1204062933869048E-01; COFD[ 232] = -0.1596628118290846E+02; COFD[ 233] = 0.3841273000042274E+01; COFD[ 234] = -0.2898297027626218E+00; COFD[ 235] = 0.1280193859902638E-01; COFD[ 236] = -0.1591206444980951E+02; COFD[ 237] = 0.3820917505869285E+01; COFD[ 238] = -0.2872227297192593E+00; COFD[ 239] = 0.1269037691099738E-01; COFD[ 240] = -0.1524511379647520E+02; COFD[ 241] = 0.3553053597674808E+01; COFD[ 242] = -0.2545212965294182E+00; COFD[ 243] = 0.1136271070888101E-01; COFD[ 244] = -0.1768659705517047E+02; COFD[ 245] = 0.4367905899188474E+01; COFD[ 246] = -0.3516645879639785E+00; COFD[ 247] = 0.1520186726409712E-01; COFD[ 248] = -0.1891518602118661E+02; COFD[ 249] = 0.4756739681751712E+01; COFD[ 250] = -0.3886685070061102E+00; COFD[ 251] = 0.1625748441332711E-01; COFD[ 252] = -0.1730907989620245E+02; COFD[ 253] = 0.4243749180870270E+01; COFD[ 254] = -0.3387466685616417E+00; COFD[ 255] = 0.1477905643158847E-01; COFD[ 256] = -0.1795985745949001E+02; COFD[ 257] = 0.4461091096847464E+01; COFD[ 258] = -0.3624212969270659E+00; COFD[ 259] = 0.1561553586311572E-01; COFD[ 260] = -0.1782798069130013E+02; COFD[ 261] = 0.4381516462622495E+01; COFD[ 262] = -0.3532970918753254E+00; COFD[ 263] = 0.1526804966457564E-01; COFD[ 264] = -0.1863707722655403E+02; COFD[ 265] = 0.4806992114833483E+01; COFD[ 266] = -0.3984196894018535E+00; COFD[ 267] = 0.1681856268295304E-01; COFD[ 268] = -0.1395220381010925E+02; COFD[ 269] = 0.3159688299904867E+01; COFD[ 270] = -0.2028455188834762E+00; COFD[ 271] = 0.9099190221367019E-02; COFD[ 272] = -0.1757366663670086E+02; COFD[ 273] = 0.4778618797909657E+01; COFD[ 274] = -0.3996041319366184E+00; COFD[ 275] = 0.1705904378841811E-01; COFD[ 276] = -0.1615075966577466E+02; COFD[ 277] = 0.4076548482999812E+01; COFD[ 278] = -0.2637510941604614E+00; COFD[ 279] = 0.9371841080052064E-02; COFD[ 280] = -0.1922081039841695E+02; COFD[ 281] = 0.4711535347815869E+01; COFD[ 282] = -0.3619579159000997E+00; COFD[ 283] = 0.1426886476331241E-01; COFD[ 284] = -0.1876923157317771E+02; COFD[ 285] = 0.4853854184816717E+01; COFD[ 286] = -0.3998497982364926E+00; COFD[ 287] = 0.1669227468405473E-01; COFD[ 288] = -0.1159394277352764E+02; COFD[ 289] = 0.8274415074083117E+00; COFD[ 290] = 0.2507810870995229E+00; COFD[ 291] = -0.1608920912964349E-01; COFD[ 292] = -0.1918278409127273E+02; COFD[ 293] = 0.4757442212360504E+01; COFD[ 294] = -0.3754949936858373E+00; COFD[ 295] = 0.1515864657024127E-01; COFD[ 296] = -0.1917291211841810E+02; COFD[ 297] = 0.4750317181782021E+01; COFD[ 298] = -0.3743997734248102E+00; COFD[ 299] = 0.1510405742415517E-01; COFD[ 300] = -0.1924307146615256E+02; COFD[ 301] = 0.4719749979653547E+01; COFD[ 302] = -0.3616169791891675E+00; COFD[ 303] = 0.1420601032870719E-01; COFD[ 304] = -0.1899850780979201E+02; COFD[ 305] = 0.4543165455349725E+01; COFD[ 306] = -0.3288657155661528E+00; COFD[ 307] = 0.1239537851241695E-01; COFD[ 308] = -0.1935427072301072E+02; COFD[ 309] = 0.4779618521455131E+01; COFD[ 310] = -0.3741503724582112E+00; COFD[ 311] = 0.1493019768764606E-01; COFD[ 312] = -0.1719414340129819E+02; COFD[ 313] = 0.3490298819499314E+01; COFD[ 314] = -0.1625329575445097E+00; COFD[ 315] = 0.4043757780510787E-02; COFD[ 316] = -0.1468058225757294E+02; COFD[ 317] = 0.2298576535112391E+01; COFD[ 318] = 0.1810975986268222E-01; COFD[ 319] = -0.4731609614535192E-02; COFD[ 320] = -0.1868831150678477E+02; COFD[ 321] = 0.4247585976166683E+01; COFD[ 322] = -0.2815735628073077E+00; COFD[ 323] = 0.1000602366593966E-01; COFD[ 324] = -0.1767910948230725E+02; COFD[ 325] = 0.3722086580781685E+01; COFD[ 326] = -0.1980254146986777E+00; COFD[ 327] = 0.5799038224028695E-02; COFD[ 328] = -0.1813805288510309E+02; COFD[ 329] = 0.3907124675584541E+01; COFD[ 330] = -0.2273991439446390E+00; COFD[ 331] = 0.7280601459305962E-02; COFD[ 332] = -0.1316791411191276E+02; COFD[ 333] = 0.1635596276910710E+01; COFD[ 334] = 0.1248562922809231E+00; COFD[ 335] = -0.1002143991895203E-01; COFD[ 336] = -0.1875637020961290E+02; COFD[ 337] = 0.4821872691746870E+01; COFD[ 338] = -0.3987313751514457E+00; COFD[ 339] = 0.1676685214877852E-01; COFD[ 340] = -0.1309613046501959E+02; COFD[ 341] = 0.3086801219615145E+01; COFD[ 342] = -0.1948957472387874E+00; COFD[ 343] = 0.8817294833761086E-02; COFD[ 344] = -0.1616058613782880E+02; COFD[ 345] = 0.4418087193226073E+01; COFD[ 346] = -0.3584223903851448E+00; COFD[ 347] = 0.1549243249303281E-01; COFD[ 348] = -0.1634649054694938E+02; COFD[ 349] = 0.3804144246517877E+01; COFD[ 350] = -0.2844651891354975E+00; COFD[ 351] = 0.1254622626209081E-01; COFD[ 352] = -0.1551249966394157E+02; COFD[ 353] = 0.3667301435894143E+01; COFD[ 354] = -0.2693892845913942E+00; COFD[ 355] = 0.1200791993248851E-01; COFD[ 356] = -0.1918278409127273E+02; COFD[ 357] = 0.4757442212360504E+01; COFD[ 358] = -0.3754949936858373E+00; COFD[ 359] = 0.1515864657024127E-01; COFD[ 360] = -0.1635409817368614E+02; COFD[ 361] = 0.3804061718963002E+01; COFD[ 362] = -0.2844545503177105E+00; COFD[ 363] = 0.1254577088876500E-01; COFD[ 364] = -0.1636175579013954E+02; COFD[ 365] = 0.3804139357106159E+01; COFD[ 366] = -0.2844645588307625E+00; COFD[ 367] = 0.1254619928317991E-01; COFD[ 368] = -0.1710991586467964E+02; COFD[ 369] = 0.4125646326528441E+01; COFD[ 370] = -0.3238554740258663E+00; COFD[ 371] = 0.1415227419625766E-01; COFD[ 372] = -0.1706120101779605E+02; COFD[ 373] = 0.4105791991868936E+01; COFD[ 374] = -0.3214635787029052E+00; COFD[ 375] = 0.1405654084975138E-01; COFD[ 376] = -0.1616672146196606E+02; COFD[ 377] = 0.3734919571093601E+01; COFD[ 378] = -0.2762018861637152E+00; COFD[ 379] = 0.1221896274296108E-01; COFD[ 380] = -0.1872670165824808E+02; COFD[ 381] = 0.4573903479896379E+01; COFD[ 382] = -0.3758340786206700E+00; COFD[ 383] = 0.1615161324401359E-01; COFD[ 384] = -0.1978049689264223E+02; COFD[ 385] = 0.4876281709421428E+01; COFD[ 386] = -0.3981401304053240E+00; COFD[ 387] = 0.1643325343977014E-01; COFD[ 388] = -0.1831322697803230E+02; COFD[ 389] = 0.4452261161272578E+01; COFD[ 390] = -0.3624715246876605E+00; COFD[ 391] = 0.1567121551911240E-01; COFD[ 392] = -0.1905419842832635E+02; COFD[ 393] = 0.4700662819460902E+01; COFD[ 394] = -0.3903206776226419E+00; COFD[ 395] = 0.1670032573134212E-01; COFD[ 396] = -0.1884529530697174E+02; COFD[ 397] = 0.4594634055023398E+01; COFD[ 398] = -0.3781333057516071E+00; COFD[ 399] = 0.1623599168682821E-01; COFD[ 400] = -0.1919185322703664E+02; COFD[ 401] = 0.4784033288807873E+01; COFD[ 402] = -0.3849459064100618E+00; COFD[ 403] = 0.1580648990064550E-01; COFD[ 404] = -0.1528586419146581E+02; COFD[ 405] = 0.3542872339374690E+01; COFD[ 406] = -0.2532972672017028E+00; COFD[ 407] = 0.1131367837559019E-01; COFD[ 408] = -0.1310029609771552E+02; COFD[ 409] = 0.3088245187916686E+01; COFD[ 410] = -0.1950980328845662E+00; COFD[ 411] = 0.8826694775135658E-02; COFD[ 412] = -0.1616421015670871E+02; COFD[ 413] = 0.4419285820914456E+01; COFD[ 414] = -0.3585647608630650E+00; COFD[ 415] = 0.1549798503551403E-01; COFD[ 416] = -0.1635443062264980E+02; COFD[ 417] = 0.3804381702146611E+01; COFD[ 418] = -0.2844957999638338E+00; COFD[ 419] = 0.1254753649276844E-01; COFD[ 420] = -0.1553013778710249E+02; COFD[ 421] = 0.3672587405633829E+01; COFD[ 422] = -0.2701107938194129E+00; COFD[ 423] = 0.1204062933869048E-01; COFD[ 424] = -0.1917291211841810E+02; COFD[ 425] = 0.4750317181782021E+01; COFD[ 426] = -0.3743997734248102E+00; COFD[ 427] = 0.1510405742415517E-01; COFD[ 428] = -0.1636175579013954E+02; COFD[ 429] = 0.3804139357106159E+01; COFD[ 430] = -0.2844645588307625E+00; COFD[ 431] = 0.1254619928317991E-01; COFD[ 432] = -0.1636913880728208E+02; COFD[ 433] = 0.3804061718963007E+01; COFD[ 434] = -0.2844545503177112E+00; COFD[ 435] = 0.1254577088876504E-01; COFD[ 436] = -0.1711940058927942E+02; COFD[ 437] = 0.4127460426680499E+01; COFD[ 438] = -0.3240705310922555E+00; COFD[ 439] = 0.1416063080699452E-01; COFD[ 440] = -0.1707080539569448E+02; COFD[ 441] = 0.4107575519112949E+01; COFD[ 442] = -0.3216756148320791E+00; COFD[ 443] = 0.1406480989264605E-01; COFD[ 444] = -0.1617584857259722E+02; COFD[ 445] = 0.3735860038531880E+01; COFD[ 446] = -0.2763277124196010E+00; COFD[ 447] = 0.1222455543181157E-01; COFD[ 448] = -0.1873560076291526E+02; COFD[ 449] = 0.4574325021189105E+01; COFD[ 450] = -0.3759338652876284E+00; COFD[ 451] = 0.1615792922437573E-01; COFD[ 452] = -0.1978644159772173E+02; COFD[ 453] = 0.4875758120324897E+01; COFD[ 454] = -0.3980631994813040E+00; COFD[ 455] = 0.1642957450530744E-01; COFD[ 456] = -0.1831968967523493E+02; COFD[ 457] = 0.4452134774757628E+01; COFD[ 458] = -0.3624420830935042E+00; COFD[ 459] = 0.1566936578675393E-01; COFD[ 460] = -0.1906036212420135E+02; COFD[ 461] = 0.4700323443044125E+01; COFD[ 462] = -0.3902665913786998E+00; COFD[ 463] = 0.1669755465043006E-01; COFD[ 464] = -0.1885218260686505E+02; COFD[ 465] = 0.4594596529989258E+01; COFD[ 466] = -0.3781371531513473E+00; COFD[ 467] = 0.1623655159949430E-01; COFD[ 468] = -0.1918517200292939E+02; COFD[ 469] = 0.4778400021399422E+01; COFD[ 470] = -0.3840658172050402E+00; COFD[ 471] = 0.1576203256152660E-01; COFD[ 472] = -0.1530075071186979E+02; COFD[ 473] = 0.3547276678457322E+01; COFD[ 474] = -0.2538990508478524E+00; COFD[ 475] = 0.1134098602286849E-01; COFD[ 476] = -0.1401582227027964E+02; COFD[ 477] = 0.3415426664334749E+01; COFD[ 478] = -0.2385853115052575E+00; COFD[ 479] = 0.1075469512610122E-01; COFD[ 480] = -0.1668220221378553E+02; COFD[ 481] = 0.4517665522196412E+01; COFD[ 482] = -0.3643177404654742E+00; COFD[ 483] = 0.1544861119982853E-01; COFD[ 484] = -0.1710012222365139E+02; COFD[ 485] = 0.4123808736773267E+01; COFD[ 486] = -0.3236376370297240E+00; COFD[ 487] = 0.1414381001550686E-01; COFD[ 488] = -0.1596628118290846E+02; COFD[ 489] = 0.3841273000042274E+01; COFD[ 490] = -0.2898297027626218E+00; COFD[ 491] = 0.1280193859902638E-01; COFD[ 492] = -0.1924307146615256E+02; COFD[ 493] = 0.4719749979653547E+01; COFD[ 494] = -0.3616169791891675E+00; COFD[ 495] = 0.1420601032870719E-01; COFD[ 496] = -0.1710991586467964E+02; COFD[ 497] = 0.4125646326528441E+01; COFD[ 498] = -0.3238554740258663E+00; COFD[ 499] = 0.1415227419625766E-01; COFD[ 500] = -0.1711940058927942E+02; COFD[ 501] = 0.4127460426680499E+01; COFD[ 502] = -0.3240705310922555E+00; COFD[ 503] = 0.1416063080699452E-01; COFD[ 504] = -0.1776945810612460E+02; COFD[ 505] = 0.4375557614241441E+01; COFD[ 506] = -0.3535212257934470E+00; COFD[ 507] = 0.1532421336526862E-01; COFD[ 508] = -0.1770845512212784E+02; COFD[ 509] = 0.4353002298484032E+01; COFD[ 510] = -0.3507494100853503E+00; COFD[ 511] = 0.1521052013931193E-01; COFD[ 512] = -0.1695356550477676E+02; COFD[ 513] = 0.4068213336589554E+01; COFD[ 514] = -0.3177710408064736E+00; COFD[ 515] = 0.1394701157712223E-01; COFD[ 516] = -0.1913993542632300E+02; COFD[ 517] = 0.4730620081114692E+01; COFD[ 518] = -0.3883890489649657E+00; COFD[ 519] = 0.1637150502726411E-01; COFD[ 520] = -0.1958734834972716E+02; COFD[ 521] = 0.4743227463757541E+01; COFD[ 522] = -0.3686474607497347E+00; COFD[ 523] = 0.1466232449273593E-01; COFD[ 524] = -0.1892132288088230E+02; COFD[ 525] = 0.4686257416133524E+01; COFD[ 526] = -0.3876178620425971E+00; COFD[ 527] = 0.1654627973246352E-01; COFD[ 528] = -0.1934401530563503E+02; COFD[ 529] = 0.4788242539311199E+01; COFD[ 530] = -0.3933254249328604E+00; COFD[ 531] = 0.1648505821153991E-01; COFD[ 532] = -0.1926514266945471E+02; COFD[ 533] = 0.4743728688652060E+01; COFD[ 534] = -0.3899270700585402E+00; COFD[ 535] = 0.1643466452124135E-01; COFD[ 536] = -0.1944043258564383E+02; COFD[ 537] = 0.4828743160693618E+01; COFD[ 538] = -0.3828021863328961E+00; COFD[ 539] = 0.1540186987470838E-01; COFD[ 540] = -0.1573476318984406E+02; COFD[ 541] = 0.3712839423735899E+01; COFD[ 542] = -0.2734220687823376E+00; COFD[ 543] = 0.1210212757075583E-01; COFD[ 544] = -0.1394568249588876E+02; COFD[ 545] = 0.3392701225291731E+01; COFD[ 546] = -0.2355263017693934E+00; COFD[ 547] = 0.1061747669734484E-01; COFD[ 548] = -0.1661124059439949E+02; COFD[ 549] = 0.4499983815327449E+01; COFD[ 550] = -0.3624203284397300E+00; COFD[ 551] = 0.1538350856590451E-01; COFD[ 552] = -0.1705130515010214E+02; COFD[ 553] = 0.4103994885241071E+01; COFD[ 554] = -0.3212499365446575E+00; COFD[ 555] = 0.1404820978963865E-01; COFD[ 556] = -0.1591206444980951E+02; COFD[ 557] = 0.3820917505869285E+01; COFD[ 558] = -0.2872227297192593E+00; COFD[ 559] = 0.1269037691099738E-01; COFD[ 560] = -0.1899850780979201E+02; COFD[ 561] = 0.4543165455349725E+01; COFD[ 562] = -0.3288657155661528E+00; COFD[ 563] = 0.1239537851241695E-01; COFD[ 564] = -0.1706120101779605E+02; COFD[ 565] = 0.4105791991868936E+01; COFD[ 566] = -0.3214635787029052E+00; COFD[ 567] = 0.1405654084975138E-01; COFD[ 568] = -0.1707080539569448E+02; COFD[ 569] = 0.4107575519112949E+01; COFD[ 570] = -0.3216756148320791E+00; COFD[ 571] = 0.1406480989264605E-01; COFD[ 572] = -0.1770845512212784E+02; COFD[ 573] = 0.4353002298484032E+01; COFD[ 574] = -0.3507494100853503E+00; COFD[ 575] = 0.1521052013931193E-01; COFD[ 576] = -0.1766523778708329E+02; COFD[ 577] = 0.4337952155636497E+01; COFD[ 578] = -0.3490538655747895E+00; COFD[ 579] = 0.1514793254733080E-01; COFD[ 580] = -0.1690087953694522E+02; COFD[ 581] = 0.4046945935955795E+01; COFD[ 582] = -0.3151742473102278E+00; COFD[ 583] = 0.1384162361172659E-01; COFD[ 584] = -0.1913011857829392E+02; COFD[ 585] = 0.4728539523227080E+01; COFD[ 586] = -0.3887605628634140E+00; COFD[ 587] = 0.1641451966125198E-01; COFD[ 588] = -0.1962180466510501E+02; COFD[ 589] = 0.4762356031601866E+01; COFD[ 590] = -0.3720986023672735E+00; COFD[ 591] = 0.1485121157223651E-01; COFD[ 592] = -0.1887963312848053E+02; COFD[ 593] = 0.4671422222663214E+01; COFD[ 594] = -0.3861362810478654E+00; COFD[ 595] = 0.1650068107616750E-01; COFD[ 596] = -0.1933004429336219E+02; COFD[ 597] = 0.4785693509382203E+01; COFD[ 598] = -0.3936420075604487E+00; COFD[ 599] = 0.1652573779841039E-01; COFD[ 600] = -0.1926485085357470E+02; COFD[ 601] = 0.4746666060969545E+01; COFD[ 602] = -0.3910387566978661E+00; COFD[ 603] = 0.1651352760050653E-01; COFD[ 604] = -0.1941730561245821E+02; COFD[ 605] = 0.4788578363438019E+01; COFD[ 606] = -0.3737994268951498E+00; COFD[ 607] = 0.1486050997611076E-01; COFD[ 608] = -0.1569001110440693E+02; COFD[ 609] = 0.3696584277188425E+01; COFD[ 610] = -0.2713867054547939E+00; COFD[ 611] = 0.1201712146112774E-01; COFD[ 612] = -0.1288505703505633E+02; COFD[ 613] = 0.2980129383938292E+01; COFD[ 614] = -0.1801545917674105E+00; COFD[ 615] = 0.8138117217492757E-02; COFD[ 616] = -0.1640877269708571E+02; COFD[ 617] = 0.4519498926662536E+01; COFD[ 618] = -0.3750329779403845E+00; COFD[ 619] = 0.1635855421757920E-01; COFD[ 620] = -0.1615768146554276E+02; COFD[ 621] = 0.3734150883385773E+01; COFD[ 622] = -0.2760989842105895E+00; COFD[ 623] = 0.1221438663500826E-01; COFD[ 624] = -0.1524511379647520E+02; COFD[ 625] = 0.3553053597674808E+01; COFD[ 626] = -0.2545212965294182E+00; COFD[ 627] = 0.1136271070888101E-01; COFD[ 628] = -0.1935427072301072E+02; COFD[ 629] = 0.4779618521455131E+01; COFD[ 630] = -0.3741503724582112E+00; COFD[ 631] = 0.1493019768764606E-01; COFD[ 632] = -0.1616672146196606E+02; COFD[ 633] = 0.3734919571093601E+01; COFD[ 634] = -0.2762018861637152E+00; COFD[ 635] = 0.1221896274296108E-01; COFD[ 636] = -0.1617584857259722E+02; COFD[ 637] = 0.3735860038531880E+01; COFD[ 638] = -0.2763277124196010E+00; COFD[ 639] = 0.1222455543181157E-01; COFD[ 640] = -0.1695356550477676E+02; COFD[ 641] = 0.4068213336589554E+01; COFD[ 642] = -0.3177710408064736E+00; COFD[ 643] = 0.1394701157712223E-01; COFD[ 644] = -0.1690087953694522E+02; COFD[ 645] = 0.4046945935955795E+01; COFD[ 646] = -0.3151742473102278E+00; COFD[ 647] = 0.1384162361172659E-01; COFD[ 648] = -0.1594065528219861E+02; COFD[ 649] = 0.3646923650815759E+01; COFD[ 650] = -0.2651273478800260E+00; COFD[ 651] = 0.1175431470196917E-01; COFD[ 652] = -0.1856069485825941E+02; COFD[ 653] = 0.4522343094041945E+01; COFD[ 654] = -0.3705240910138461E+00; COFD[ 655] = 0.1597653817363581E-01; COFD[ 656] = -0.1966898676800112E+02; COFD[ 657] = 0.4852357825322780E+01; COFD[ 658] = -0.3976302929205434E+00; COFD[ 659] = 0.1651454081234691E-01; COFD[ 660] = -0.1805980237913599E+02; COFD[ 661] = 0.4360474000056099E+01; COFD[ 662] = -0.3516356776422001E+00; COFD[ 663] = 0.1524545596600636E-01; COFD[ 664] = -0.1878468158135861E+02; COFD[ 665] = 0.4605034135660564E+01; COFD[ 666] = -0.3792399254380860E+00; COFD[ 667] = 0.1627418668274144E-01; COFD[ 668] = -0.1869955819260176E+02; COFD[ 669] = 0.4551222122230642E+01; COFD[ 670] = -0.3741499971521470E+00; COFD[ 671] = 0.1613010818331805E-01; COFD[ 672] = -0.1934447945708759E+02; COFD[ 673] = 0.4835867901258055E+01; COFD[ 674] = -0.3919040198993948E+00; COFD[ 675] = 0.1611935633959806E-01; COFD[ 676] = -0.1499765769172950E+02; COFD[ 677] = 0.3419142531858579E+01; COFD[ 678] = -0.2369480887688776E+00; COFD[ 679] = 0.1059345659536257E-01; COFD[ 680] = -0.1558361674716745E+02; COFD[ 681] = 0.3987098568284434E+01; COFD[ 682] = -0.3109866036899985E+00; COFD[ 683] = 0.1380795341338578E-01; COFD[ 684] = -0.1664237108262573E+02; COFD[ 685] = 0.4321207774376617E+01; COFD[ 686] = -0.3181315549506706E+00; COFD[ 687] = 0.1258308183870717E-01; COFD[ 688] = -0.1871735010457793E+02; COFD[ 689] = 0.4573421885700214E+01; COFD[ 690] = -0.3757214086933051E+00; COFD[ 691] = 0.1614451502251515E-01; COFD[ 692] = -0.1768659705517047E+02; COFD[ 693] = 0.4367905899188474E+01; COFD[ 694] = -0.3516645879639785E+00; COFD[ 695] = 0.1520186726409712E-01; COFD[ 696] = -0.1719414340129819E+02; COFD[ 697] = 0.3490298819499314E+01; COFD[ 698] = -0.1625329575445097E+00; COFD[ 699] = 0.4043757780510787E-02; COFD[ 700] = -0.1872670165824808E+02; COFD[ 701] = 0.4573903479896379E+01; COFD[ 702] = -0.3758340786206700E+00; COFD[ 703] = 0.1615161324401359E-01; COFD[ 704] = -0.1873560076291526E+02; COFD[ 705] = 0.4574325021189105E+01; COFD[ 706] = -0.3759338652876284E+00; COFD[ 707] = 0.1615792922437573E-01; COFD[ 708] = -0.1913993542632300E+02; COFD[ 709] = 0.4730620081114692E+01; COFD[ 710] = -0.3883890489649657E+00; COFD[ 711] = 0.1637150502726411E-01; COFD[ 712] = -0.1913011857829392E+02; COFD[ 713] = 0.4728539523227080E+01; COFD[ 714] = -0.3887605628634140E+00; COFD[ 715] = 0.1641451966125198E-01; COFD[ 716] = -0.1856069485825941E+02; COFD[ 717] = 0.4522343094041945E+01; COFD[ 718] = -0.3705240910138461E+00; COFD[ 719] = 0.1597653817363581E-01; COFD[ 720] = -0.2016579860319706E+02; COFD[ 721] = 0.4877618917687775E+01; COFD[ 722] = -0.3948460761426021E+00; COFD[ 723] = 0.1615166256107893E-01; COFD[ 724] = -0.1928397124960116E+02; COFD[ 725] = 0.4312110001899904E+01; COFD[ 726] = -0.2907322088872635E+00; COFD[ 727] = 0.1043236734543387E-01; COFD[ 728] = -0.1989540745008587E+02; COFD[ 729] = 0.4834853238941779E+01; COFD[ 730] = -0.3932322467650001E+00; COFD[ 731] = 0.1623552876595314E-01; COFD[ 732] = -0.2005638433296784E+02; COFD[ 733] = 0.4810333449107644E+01; COFD[ 734] = -0.3802752927546432E+00; COFD[ 735] = 0.1528555688791561E-01; COFD[ 736] = -0.2016849050066446E+02; COFD[ 737] = 0.4851147993946014E+01; COFD[ 738] = -0.3897545968990269E+00; COFD[ 739] = 0.1586327845280228E-01; COFD[ 740] = -0.1833717188007337E+02; COFD[ 741] = 0.4039707350126803E+01; COFD[ 742] = -0.2488565303881858E+00; COFD[ 743] = 0.8361653792794556E-02; COFD[ 744] = -0.1761289252565630E+02; COFD[ 745] = 0.4327706010171974E+01; COFD[ 746] = -0.3490300604788930E+00; COFD[ 747] = 0.1519713199892770E-01; COFD[ 748] = -0.1688564690991911E+02; COFD[ 749] = 0.4415865473479337E+01; COFD[ 750] = -0.3564104485793251E+00; COFD[ 751] = 0.1533855847922275E-01; COFD[ 752] = -0.1567567878102999E+02; COFD[ 753] = 0.3706302510623138E+01; COFD[ 754] = -0.2096236244277931E+00; COFD[ 755] = 0.6748353057110522E-02; COFD[ 756] = -0.1977364410044468E+02; COFD[ 757] = 0.4876531592391508E+01; COFD[ 758] = -0.3981741984755758E+00; COFD[ 759] = 0.1643476290195535E-01; COFD[ 760] = -0.1891518602118661E+02; COFD[ 761] = 0.4756739681751712E+01; COFD[ 762] = -0.3886685070061102E+00; COFD[ 763] = 0.1625748441332711E-01; COFD[ 764] = -0.1468058225757294E+02; COFD[ 765] = 0.2298576535112391E+01; COFD[ 766] = 0.1810975986268222E-01; COFD[ 767] = -0.4731609614535192E-02; COFD[ 768] = -0.1978049689264223E+02; COFD[ 769] = 0.4876281709421428E+01; COFD[ 770] = -0.3981401304053240E+00; COFD[ 771] = 0.1643325343977014E-01; COFD[ 772] = -0.1978644159772173E+02; COFD[ 773] = 0.4875758120324897E+01; COFD[ 774] = -0.3980631994813040E+00; COFD[ 775] = 0.1642957450530744E-01; COFD[ 776] = -0.1958734834972716E+02; COFD[ 777] = 0.4743227463757541E+01; COFD[ 778] = -0.3686474607497347E+00; COFD[ 779] = 0.1466232449273593E-01; COFD[ 780] = -0.1962180466510501E+02; COFD[ 781] = 0.4762356031601866E+01; COFD[ 782] = -0.3720986023672735E+00; COFD[ 783] = 0.1485121157223651E-01; COFD[ 784] = -0.1966898676800112E+02; COFD[ 785] = 0.4852357825322780E+01; COFD[ 786] = -0.3976302929205434E+00; COFD[ 787] = 0.1651454081234691E-01; COFD[ 788] = -0.1928397124960116E+02; COFD[ 789] = 0.4312110001899904E+01; COFD[ 790] = -0.2907322088872635E+00; COFD[ 791] = 0.1043236734543387E-01; COFD[ 792] = -0.1603997666374001E+02; COFD[ 793] = 0.2734208547161103E+01; COFD[ 794] = -0.4628114204507498E-01; COFD[ 795] = -0.1672840630334733E-02; COFD[ 796] = -0.1961392673202087E+02; COFD[ 797] = 0.4524886156774725E+01; COFD[ 798] = -0.3261423023221592E+00; COFD[ 799] = 0.1226835649915157E-01; COFD[ 800] = -0.1890313414494545E+02; COFD[ 801] = 0.4121436960338011E+01; COFD[ 802] = -0.2594362965642011E+00; COFD[ 803] = 0.8823603190561257E-02; COFD[ 804] = -0.1932385614900669E+02; COFD[ 805] = 0.4295315571390907E+01; COFD[ 806] = -0.2874898966822066E+00; COFD[ 807] = 0.1025198769300411E-01; COFD[ 808] = -0.1580770444028599E+02; COFD[ 809] = 0.2799524263213967E+01; COFD[ 810] = -0.5666575630034967E-01; COFD[ 811] = -0.1137221314445150E-02; COFD[ 812] = -0.1888662285046225E+02; COFD[ 813] = 0.4736242637853255E+01; COFD[ 814] = -0.3893357605389257E+00; COFD[ 815] = 0.1642422988902124E-01; COFD[ 816] = -0.1548207029093904E+02; COFD[ 817] = 0.3939084188623417E+01; COFD[ 818] = -0.3072761108436687E+00; COFD[ 819] = 0.1375770270895890E-01; COFD[ 820] = -0.1685361380845761E+02; COFD[ 821] = 0.4411251776453823E+01; COFD[ 822] = -0.3350756131548513E+00; COFD[ 823] = 0.1353157937321782E-01; COFD[ 824] = -0.1830650296367939E+02; COFD[ 825] = 0.4452394507404697E+01; COFD[ 826] = -0.3624991200767191E+00; COFD[ 827] = 0.1567286266089603E-01; COFD[ 828] = -0.1730907989620245E+02; COFD[ 829] = 0.4243749180870270E+01; COFD[ 830] = -0.3387466685616417E+00; COFD[ 831] = 0.1477905643158847E-01; COFD[ 832] = -0.1868831150678477E+02; COFD[ 833] = 0.4247585976166683E+01; COFD[ 834] = -0.2815735628073077E+00; COFD[ 835] = 0.1000602366593966E-01; COFD[ 836] = -0.1831322697803230E+02; COFD[ 837] = 0.4452261161272578E+01; COFD[ 838] = -0.3624715246876605E+00; COFD[ 839] = 0.1567121551911240E-01; COFD[ 840] = -0.1831968967523493E+02; COFD[ 841] = 0.4452134774757628E+01; COFD[ 842] = -0.3624420830935042E+00; COFD[ 843] = 0.1566936578675393E-01; COFD[ 844] = -0.1892132288088230E+02; COFD[ 845] = 0.4686257416133524E+01; COFD[ 846] = -0.3876178620425971E+00; COFD[ 847] = 0.1654627973246352E-01; COFD[ 848] = -0.1887963312848053E+02; COFD[ 849] = 0.4671422222663214E+01; COFD[ 850] = -0.3861362810478654E+00; COFD[ 851] = 0.1650068107616750E-01; COFD[ 852] = -0.1805980237913599E+02; COFD[ 853] = 0.4360474000056099E+01; COFD[ 854] = -0.3516356776422001E+00; COFD[ 855] = 0.1524545596600636E-01; COFD[ 856] = -0.1989540745008587E+02; COFD[ 857] = 0.4834853238941779E+01; COFD[ 858] = -0.3932322467650001E+00; COFD[ 859] = 0.1623552876595314E-01; COFD[ 860] = -0.1961392673202087E+02; COFD[ 861] = 0.4524886156774725E+01; COFD[ 862] = -0.3261423023221592E+00; COFD[ 863] = 0.1226835649915157E-01; COFD[ 864] = -0.1977017209130380E+02; COFD[ 865] = 0.4847119688172202E+01; COFD[ 866] = -0.4003461404722360E+00; COFD[ 867] = 0.1676917774316241E-01; COFD[ 868] = -0.2005922850303636E+02; COFD[ 869] = 0.4881576631488546E+01; COFD[ 870] = -0.3958945479488925E+00; COFD[ 871] = 0.1621878544379618E-01; COFD[ 872] = -0.2004561228963652E+02; COFD[ 873] = 0.4868786155445560E+01; COFD[ 874] = -0.3974311326078929E+00; COFD[ 875] = 0.1641238256860971E-01; COFD[ 876] = -0.1912297200146966E+02; COFD[ 877] = 0.4463559909783323E+01; COFD[ 878] = -0.3178210889061098E+00; COFD[ 879] = 0.1189219041826154E-01; COFD[ 880] = -0.1703791763653080E+02; COFD[ 881] = 0.4110925857281930E+01; COFD[ 882] = -0.3221728744644342E+00; COFD[ 883] = 0.1408821528952375E-01; COFD[ 884] = -0.1606152931877502E+02; COFD[ 885] = 0.4146430359164761E+01; COFD[ 886] = -0.3312210923439469E+00; COFD[ 887] = 0.1466430884967795E-01; COFD[ 888] = -0.1635823810097287E+02; COFD[ 889] = 0.4123977007004703E+01; COFD[ 890] = -0.2854728908229589E+00; COFD[ 891] = 0.1088433914065527E-01; COFD[ 892] = -0.1904759289384530E+02; COFD[ 893] = 0.4700929573683383E+01; COFD[ 894] = -0.3903608191209737E+00; COFD[ 895] = 0.1670229359855150E-01; COFD[ 896] = -0.1795985745949001E+02; COFD[ 897] = 0.4461091096847464E+01; COFD[ 898] = -0.3624212969270659E+00; COFD[ 899] = 0.1561553586311572E-01; COFD[ 900] = -0.1767910948230725E+02; COFD[ 901] = 0.3722086580781685E+01; COFD[ 902] = -0.1980254146986777E+00; COFD[ 903] = 0.5799038224028695E-02; COFD[ 904] = -0.1905419842832635E+02; COFD[ 905] = 0.4700662819460902E+01; COFD[ 906] = -0.3903206776226419E+00; COFD[ 907] = 0.1670032573134212E-01; COFD[ 908] = -0.1906036212420135E+02; COFD[ 909] = 0.4700323443044125E+01; COFD[ 910] = -0.3902665913786998E+00; COFD[ 911] = 0.1669755465043006E-01; COFD[ 912] = -0.1934401530563503E+02; COFD[ 913] = 0.4788242539311199E+01; COFD[ 914] = -0.3933254249328604E+00; COFD[ 915] = 0.1648505821153991E-01; COFD[ 916] = -0.1933004429336219E+02; COFD[ 917] = 0.4785693509382203E+01; COFD[ 918] = -0.3936420075604487E+00; COFD[ 919] = 0.1652573779841039E-01; COFD[ 920] = -0.1878468158135861E+02; COFD[ 921] = 0.4605034135660564E+01; COFD[ 922] = -0.3792399254380860E+00; COFD[ 923] = 0.1627418668274144E-01; COFD[ 924] = -0.2005638433296784E+02; COFD[ 925] = 0.4810333449107644E+01; COFD[ 926] = -0.3802752927546432E+00; COFD[ 927] = 0.1528555688791561E-01; COFD[ 928] = -0.1890313414494545E+02; COFD[ 929] = 0.4121436960338011E+01; COFD[ 930] = -0.2594362965642011E+00; COFD[ 931] = 0.8823603190561257E-02; COFD[ 932] = -0.2005922850303636E+02; COFD[ 933] = 0.4881576631488546E+01; COFD[ 934] = -0.3958945479488925E+00; COFD[ 935] = 0.1621878544379618E-01; COFD[ 936] = -0.1999234499569811E+02; COFD[ 937] = 0.4757309526477115E+01; COFD[ 938] = -0.3684627400545891E+00; COFD[ 939] = 0.1457942336558470E-01; COFD[ 940] = -0.2015885283044970E+02; COFD[ 941] = 0.4822728985557825E+01; COFD[ 942] = -0.3812000138893480E+00; COFD[ 943] = 0.1529926403243838E-01; COFD[ 944] = -0.1846533503760062E+02; COFD[ 945] = 0.4088215083590887E+01; COFD[ 946] = -0.2553371937407484E+00; COFD[ 947] = 0.8657586372083866E-02; COFD[ 948] = -0.1776457707271082E+02; COFD[ 949] = 0.4365715498242292E+01; COFD[ 950] = -0.3517547303197583E+00; COFD[ 951] = 0.1522394939239619E-01; COFD[ 952] = -0.1596236229610858E+02; COFD[ 953] = 0.4079842750882008E+01; COFD[ 954] = -0.3231960602071978E+00; COFD[ 955] = 0.1434305777680907E-01; COFD[ 956] = -0.1646195534760534E+02; COFD[ 957] = 0.4141822899037704E+01; COFD[ 958] = -0.2892308013569180E+00; COFD[ 959] = 0.1109614462742981E-01; COFD[ 960] = -0.1883799365221673E+02; COFD[ 961] = 0.4594611640098751E+01; COFD[ 962] = -0.3781168670160998E+00; COFD[ 963] = 0.1623467419613562E-01; COFD[ 964] = -0.1782798069130013E+02; COFD[ 965] = 0.4381516462622495E+01; COFD[ 966] = -0.3532970918753254E+00; COFD[ 967] = 0.1526804966457564E-01; COFD[ 968] = -0.1813805288510309E+02; COFD[ 969] = 0.3907124675584541E+01; COFD[ 970] = -0.2273991439446390E+00; COFD[ 971] = 0.7280601459305962E-02; COFD[ 972] = -0.1884529530697174E+02; COFD[ 973] = 0.4594634055023398E+01; COFD[ 974] = -0.3781333057516071E+00; COFD[ 975] = 0.1623599168682821E-01; COFD[ 976] = -0.1885218260686505E+02; COFD[ 977] = 0.4594596529989258E+01; COFD[ 978] = -0.3781371531513473E+00; COFD[ 979] = 0.1623655159949430E-01; COFD[ 980] = -0.1926514266945471E+02; COFD[ 981] = 0.4743728688652060E+01; COFD[ 982] = -0.3899270700585402E+00; COFD[ 983] = 0.1643466452124135E-01; COFD[ 984] = -0.1926485085357470E+02; COFD[ 985] = 0.4746666060969545E+01; COFD[ 986] = -0.3910387566978661E+00; COFD[ 987] = 0.1651352760050653E-01; COFD[ 988] = -0.1869955819260176E+02; COFD[ 989] = 0.4551222122230642E+01; COFD[ 990] = -0.3741499971521470E+00; COFD[ 991] = 0.1613010818331805E-01; COFD[ 992] = -0.2016849050066446E+02; COFD[ 993] = 0.4851147993946014E+01; COFD[ 994] = -0.3897545968990269E+00; COFD[ 995] = 0.1586327845280228E-01; COFD[ 996] = -0.1932385614900669E+02; COFD[ 997] = 0.4295315571390907E+01; COFD[ 998] = -0.2874898966822066E+00; COFD[ 999] = 0.1025198769300411E-01; COFD[ 1000] = -0.2004561228963652E+02; COFD[ 1001] = 0.4868786155445560E+01; COFD[ 1002] = -0.3974311326078929E+00; COFD[ 1003] = 0.1641238256860971E-01; COFD[ 1004] = -0.2015885283044970E+02; COFD[ 1005] = 0.4822728985557825E+01; COFD[ 1006] = -0.3812000138893480E+00; COFD[ 1007] = 0.1529926403243838E-01; COFD[ 1008] = -0.2024931478123324E+02; COFD[ 1009] = 0.4856999247129295E+01; COFD[ 1010] = -0.3896182557523967E+00; COFD[ 1011] = 0.1582188160996442E-01; COFD[ 1012] = -0.1871694128239326E+02; COFD[ 1013] = 0.4183824876778368E+01; COFD[ 1014] = -0.2717303313431965E+00; COFD[ 1015] = 0.9517448825356330E-02; COFD[ 1016] = -0.1776451185181849E+02; COFD[ 1017] = 0.4347765208885912E+01; COFD[ 1018] = -0.3515930667599710E+00; COFD[ 1019] = 0.1530764063925441E-01; COFD[ 1020] = -0.1682806034335371E+02; COFD[ 1021] = 0.4485450500929320E+01; COFD[ 1022] = -0.3655695289846634E+00; COFD[ 1023] = 0.1574614737371121E-01; COFD[ 1024] = -0.1626359848098758E+02; COFD[ 1025] = 0.4116788683843708E+01; COFD[ 1026] = -0.2733289330957227E+00; COFD[ 1027] = 0.9943035956817482E-02; COFD[ 1028] = -0.1934710272078301E+02; COFD[ 1029] = 0.4822779400529180E+01; COFD[ 1030] = -0.3871228449439424E+00; COFD[ 1031] = 0.1578686341252481E-01; COFD[ 1032] = -0.1863707722655403E+02; COFD[ 1033] = 0.4806992114833483E+01; COFD[ 1034] = -0.3984196894018535E+00; COFD[ 1035] = 0.1681856268295304E-01; COFD[ 1036] = -0.1316791411191276E+02; COFD[ 1037] = 0.1635596276910710E+01; COFD[ 1038] = 0.1248562922809231E+00; COFD[ 1039] = -0.1002143991895203E-01; COFD[ 1040] = -0.1919185322703664E+02; COFD[ 1041] = 0.4784033288807873E+01; COFD[ 1042] = -0.3849459064100618E+00; COFD[ 1043] = 0.1580648990064550E-01; COFD[ 1044] = -0.1918517200292939E+02; COFD[ 1045] = 0.4778400021399422E+01; COFD[ 1046] = -0.3840658172050402E+00; COFD[ 1047] = 0.1576203256152660E-01; COFD[ 1048] = -0.1944043258564383E+02; COFD[ 1049] = 0.4828743160693618E+01; COFD[ 1050] = -0.3828021863328961E+00; COFD[ 1051] = 0.1540186987470838E-01; COFD[ 1052] = -0.1941730561245821E+02; COFD[ 1053] = 0.4788578363438019E+01; COFD[ 1054] = -0.3737994268951498E+00; COFD[ 1055] = 0.1486050997611076E-01; COFD[ 1056] = -0.1934447945708759E+02; COFD[ 1057] = 0.4835867901258055E+01; COFD[ 1058] = -0.3919040198993948E+00; COFD[ 1059] = 0.1611935633959806E-01; COFD[ 1060] = -0.1833717188007337E+02; COFD[ 1061] = 0.4039707350126803E+01; COFD[ 1062] = -0.2488565303881858E+00; COFD[ 1063] = 0.8361653792794556E-02; COFD[ 1064] = -0.1580770444028599E+02; COFD[ 1065] = 0.2799524263213967E+01; COFD[ 1066] = -0.5666575630034967E-01; COFD[ 1067] = -0.1137221314445150E-02; COFD[ 1068] = -0.1912297200146966E+02; COFD[ 1069] = 0.4463559909783323E+01; COFD[ 1070] = -0.3178210889061098E+00; COFD[ 1071] = 0.1189219041826154E-01; COFD[ 1072] = -0.1846533503760062E+02; COFD[ 1073] = 0.4088215083590887E+01; COFD[ 1074] = -0.2553371937407484E+00; COFD[ 1075] = 0.8657586372083866E-02; COFD[ 1076] = -0.1871694128239326E+02; COFD[ 1077] = 0.4183824876778368E+01; COFD[ 1078] = -0.2717303313431965E+00; COFD[ 1079] = 0.9517448825356330E-02; COFD[ 1080] = -0.1451532645593394E+02; COFD[ 1081] = 0.2310965406901932E+01; COFD[ 1082] = 0.1872493495986990E-01; COFD[ 1083] = -0.4810190587113683E-02; COFD[ 1084] = -0.1862683104563700E+02; COFD[ 1085] = 0.4778876685436832E+01; COFD[ 1086] = -0.3977561689282376E+00; COFD[ 1087] = 0.1691190324024170E-01; COFD[ 1088] = -0.1163276178298392E+02; COFD[ 1089] = 0.2530205071288130E+01; COFD[ 1090] = -0.1183776350934922E+00; COFD[ 1091] = 0.5312988352557955E-02; COFD[ 1092] = -0.1522605770447405E+02; COFD[ 1093] = 0.4154863253653862E+01; COFD[ 1094] = -0.3321404775716639E+00; COFD[ 1095] = 0.1469592836326692E-01; COFD[ 1096] = -0.1527049784849730E+02; COFD[ 1097] = 0.3538365317994180E+01; COFD[ 1098] = -0.2526814234121028E+00; COFD[ 1099] = 0.1128573168209360E-01; COFD[ 1100] = -0.1395220381010925E+02; COFD[ 1101] = 0.3159688299904867E+01; COFD[ 1102] = -0.2028455188834762E+00; COFD[ 1103] = 0.9099190221367019E-02; COFD[ 1104] = -0.1875637020961290E+02; COFD[ 1105] = 0.4821872691746870E+01; COFD[ 1106] = -0.3987313751514457E+00; COFD[ 1107] = 0.1676685214877852E-01; COFD[ 1108] = -0.1528586419146581E+02; COFD[ 1109] = 0.3542872339374690E+01; COFD[ 1110] = -0.2532972672017028E+00; COFD[ 1111] = 0.1131367837559019E-01; COFD[ 1112] = -0.1530075071186979E+02; COFD[ 1113] = 0.3547276678457322E+01; COFD[ 1114] = -0.2538990508478524E+00; COFD[ 1115] = 0.1134098602286849E-01; COFD[ 1116] = -0.1573476318984406E+02; COFD[ 1117] = 0.3712839423735899E+01; COFD[ 1118] = -0.2734220687823376E+00; COFD[ 1119] = 0.1210212757075583E-01; COFD[ 1120] = -0.1569001110440693E+02; COFD[ 1121] = 0.3696584277188425E+01; COFD[ 1122] = -0.2713867054547939E+00; COFD[ 1123] = 0.1201712146112774E-01; COFD[ 1124] = -0.1499765769172950E+02; COFD[ 1125] = 0.3419142531858579E+01; COFD[ 1126] = -0.2369480887688776E+00; COFD[ 1127] = 0.1059345659536257E-01; COFD[ 1128] = -0.1761289252565630E+02; COFD[ 1129] = 0.4327706010171974E+01; COFD[ 1130] = -0.3490300604788930E+00; COFD[ 1131] = 0.1519713199892770E-01; COFD[ 1132] = -0.1888662285046225E+02; COFD[ 1133] = 0.4736242637853255E+01; COFD[ 1134] = -0.3893357605389257E+00; COFD[ 1135] = 0.1642422988902124E-01; COFD[ 1136] = -0.1703791763653080E+02; COFD[ 1137] = 0.4110925857281930E+01; COFD[ 1138] = -0.3221728744644342E+00; COFD[ 1139] = 0.1408821528952375E-01; COFD[ 1140] = -0.1776457707271082E+02; COFD[ 1141] = 0.4365715498242292E+01; COFD[ 1142] = -0.3517547303197583E+00; COFD[ 1143] = 0.1522394939239619E-01; COFD[ 1144] = -0.1776451185181849E+02; COFD[ 1145] = 0.4347765208885912E+01; COFD[ 1146] = -0.3515930667599710E+00; COFD[ 1147] = 0.1530764063925441E-01; COFD[ 1148] = -0.1862683104563700E+02; COFD[ 1149] = 0.4778876685436832E+01; COFD[ 1150] = -0.3977561689282376E+00; COFD[ 1151] = 0.1691190324024170E-01; COFD[ 1152] = -0.1377266831742670E+02; COFD[ 1153] = 0.3040578783767133E+01; COFD[ 1154] = -0.1869754178307637E+00; COFD[ 1155] = 0.8394057441551481E-02; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetKTDIF EGTRANSETKTDIF #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetKTDIF egtransetktdif #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetKTDIF egtransetktdif_ #endif void egtransetKTDIF(int* KTDIF) { KTDIF[ 0] = 1; KTDIF[ 1] = 2; }; #if defined(BL_FORT_USE_UPPERCASE) #define egtransetCOFTD EGTRANSETCOFTD #elif defined(BL_FORT_USE_LOWERCASE) #define egtransetCOFTD egtransetcoftd #elif defined(BL_FORT_USE_UNDERSCORE) #define egtransetCOFTD egtransetcoftd_ #endif void egtransetCOFTD(double* COFTD) { COFTD[ 0] = 0.0000000000000000E+00; COFTD[ 1] = 0.0000000000000000E+00; COFTD[ 2] = 0.0000000000000000E+00; COFTD[ 3] = 0.0000000000000000E+00; COFTD[ 4] = -0.1267157358260665E+00; COFTD[ 5] = -0.1025304929454753E-03; COFTD[ 6] = 0.5456049480958656E-07; COFTD[ 7] = -0.8851811492383965E-11; COFTD[ 8] = 0.3818642928024142E+00; COFTD[ 9] = 0.1841173676342166E-03; COFTD[ 10] = -0.9796176034833310E-07; COFTD[ 11] = 0.1625422476308086E-10; COFTD[ 12] = 0.3754754585061315E+00; COFTD[ 13] = 0.9735779997691615E-04; COFTD[ 14] = -0.4943935849608963E-07; COFTD[ 15] = 0.8333052020411856E-11; COFTD[ 16] = 0.1951583360602999E-02; COFTD[ 17] = 0.6694708047799631E-03; COFTD[ 18] = -0.3121487146752215E-06; COFTD[ 19] = 0.4529499206739157E-10; COFTD[ 20] = 0.3833421804573635E+00; COFTD[ 21] = 0.1848299369679226E-03; COFTD[ 22] = -0.9834089104739220E-07; COFTD[ 23] = 0.1631713171345801E-10; COFTD[ 24] = 0.3847373793384187E+00; COFTD[ 25] = 0.1855026375847330E-03; COFTD[ 26] = -0.9869880913766751E-07; COFTD[ 27] = 0.1637651897911576E-10; COFTD[ 28] = 0.2912627324548178E+00; COFTD[ 29] = 0.2330450691123891E-03; COFTD[ 30] = -0.1240401108265922E-06; COFTD[ 31] = 0.2013458793291140E-10; COFTD[ 32] = 0.2989740640904121E+00; COFTD[ 33] = 0.2322310123534718E-03; COFTD[ 34] = -0.1236750374915925E-06; COFTD[ 35] = 0.2010297352068701E-10; COFTD[ 36] = 0.3874054384854359E+00; COFTD[ 37] = 0.1568838091395251E-03; COFTD[ 38] = -0.8293099098207665E-07; COFTD[ 39] = 0.1384603182952203E-10; COFTD[ 40] = 0.2471291249759435E+00; COFTD[ 41] = 0.4493957116165469E-03; COFTD[ 42] = -0.2320307603798581E-06; COFTD[ 43] = 0.3625788270902565E-10; COFTD[ 44] = 0.8921833323260459E-01; COFTD[ 45] = 0.6385973457264696E-03; COFTD[ 46] = -0.3105267185106736E-06; COFTD[ 47] = 0.4632182714912095E-10; COFTD[ 48] = 0.2613831106363483E+00; COFTD[ 49] = 0.3741001421151409E-03; COFTD[ 50] = -0.1952756438202893E-06; COFTD[ 51] = 0.3084446425883240E-10; COFTD[ 52] = 0.2066211976818736E+00; COFTD[ 53] = 0.4698391340071242E-03; COFTD[ 54] = -0.2399965709388047E-06; COFTD[ 55] = 0.3714866667604425E-10; COFTD[ 56] = 0.2301782357423144E+00; COFTD[ 57] = 0.4411239723719602E-03; COFTD[ 58] = -0.2271927867378409E-06; COFTD[ 59] = 0.3542100728590062E-10; COFTD[ 60] = 0.5978875014515522E-01; COFTD[ 61] = 0.6004068868355234E-03; COFTD[ 62] = -0.2889528616835724E-06; COFTD[ 63] = 0.4280270387409600E-10; COFTD[ 64] = 0.3671545750621259E+00; COFTD[ 65] = 0.7074871807561138E-04; COFTD[ 66] = -0.3401390884461344E-07; COFTD[ 67] = 0.5718817519581169E-11; COFTD[ 68] = 0.1267157358260665E+00; COFTD[ 69] = 0.1025304929454753E-03; COFTD[ 70] = -0.5456049480958656E-07; COFTD[ 71] = 0.8851811492383965E-11; COFTD[ 72] = 0.0000000000000000E+00; COFTD[ 73] = 0.0000000000000000E+00; COFTD[ 74] = 0.0000000000000000E+00; COFTD[ 75] = 0.0000000000000000E+00; COFTD[ 76] = 0.1397457852745939E+00; COFTD[ 77] = 0.6298108591719154E-03; COFTD[ 78] = -0.3116940342118423E-06; COFTD[ 79] = 0.4707558637232602E-10; COFTD[ 80] = 0.1945605631423317E+00; COFTD[ 81] = 0.5079167441644920E-03; COFTD[ 82] = -0.2577206587518775E-06; COFTD[ 83] = 0.3967209139227169E-10; COFTD[ 84] = -0.1609284370381552E+00; COFTD[ 85] = 0.8016856147508327E-03; COFTD[ 86] = -0.3249766388129991E-06; COFTD[ 87] = 0.4319581912733095E-10; COFTD[ 88] = 0.1400151641499396E+00; COFTD[ 89] = 0.6310249046659604E-03; COFTD[ 90] = -0.3122948665605463E-06; COFTD[ 91] = 0.4716633092314242E-10; COFTD[ 92] = 0.1402690373253105E+00; COFTD[ 93] = 0.6321690685660495E-03; COFTD[ 94] = -0.3128611144373887E-06; COFTD[ 95] = 0.4725185213275378E-10; COFTD[ 96] = 0.6875565922217064E-01; COFTD[ 97] = 0.6631049392258758E-03; COFTD[ 98] = -0.3194849555055448E-06; COFTD[ 99] = 0.4736101303399774E-10; COFTD[ 100] = 0.7315173371679451E-01; COFTD[ 101] = 0.6642955892285024E-03; COFTD[ 102] = -0.3206112835377731E-06; COFTD[ 103] = 0.4758315870108564E-10; COFTD[ 104] = 0.1587269043383360E+00; COFTD[ 105] = 0.5967534238686169E-03; COFTD[ 106] = -0.2976737939540804E-06; COFTD[ 107] = 0.4521938974583591E-10; COFTD[ 108] = -0.3849651678153934E-01; COFTD[ 109] = 0.8347949814005065E-03; COFTD[ 110] = -0.3810312564452182E-06; COFTD[ 111] = 0.5455319374182929E-10; COFTD[ 112] = -0.1529552889766811E+00; COFTD[ 113] = 0.8501473210897147E-03; COFTD[ 114] = -0.3529415371202759E-06; COFTD[ 115] = 0.4763453033863902E-10; COFTD[ 116] = -0.6479936638152356E-02; COFTD[ 117] = 0.7836066032604117E-03; COFTD[ 118] = -0.3637347512791469E-06; COFTD[ 119] = 0.5263072586686018E-10; COFTD[ 120] = -0.6410089132874891E-01; COFTD[ 121] = 0.8311312698059269E-03; COFTD[ 122] = -0.3732877529348841E-06; COFTD[ 123] = 0.5291055177769992E-10; COFTD[ 124] = -0.4419302611803710E-01; COFTD[ 125] = 0.8219675155377782E-03; COFTD[ 126] = -0.3737680415530062E-06; COFTD[ 127] = 0.5338781013168227E-10; COFTD[ 128] = -0.1412627145163882E+00; COFTD[ 129] = 0.8094401725653276E-03; COFTD[ 130] = -0.3379215246058519E-06; COFTD[ 131] = 0.4576856099561897E-10; COFTD[ 132] = 0.2126392909101736E+00; COFTD[ 133] = 0.4604824955661828E-03; COFTD[ 134] = -0.2357734960762928E-06; COFTD[ 135] = 0.3656872132522026E-10; }; #if 0 \\ \\ \\ This is the mechanism file \\ \\ ELEMENTS O H C N END SPECIES H2 H O2 OH H2O HO2 H2O2 CH3 CH4 CO CO2 CH2O C2H2 C2H4 C2H6 NH3 NO HCN N2 END REACTIONS END \\ \\ \\ This is the therm file \\ \\ THERMO 300.000 1000.000 5000.000 ! GRI-Mech Version 3.0 Thermodynamics released 7/30/99 ! NASA Polynomial format for CHEMKIN-II ! see README file for disclaimer O L 1/90O 1 G 200.000 3500.000 1000.000 1 2.56942078E+00-8.59741137E-05 4.19484589E-08-1.00177799E-11 1.22833691E-15 2 2.92175791E+04 4.78433864E+00 3.16826710E+00-3.27931884E-03 6.64306396E-06 3 -6.12806624E-09 2.11265971E-12 2.91222592E+04 2.05193346E+00 4 O2 TPIS89O 2 G 200.000 3500.000 1000.000 1 3.28253784E+00 1.48308754E-03-7.57966669E-07 2.09470555E-10-2.16717794E-14 2 -1.08845772E+03 5.45323129E+00 3.78245636E+00-2.99673416E-03 9.84730201E-06 3 -9.68129509E-09 3.24372837E-12-1.06394356E+03 3.65767573E+00 4 H L 7/88H 1 G 200.000 3500.000 1000.000 1 2.50000001E+00-2.30842973E-11 1.61561948E-14-4.73515235E-18 4.98197357E-22 2 2.54736599E+04-4.46682914E-01 2.50000000E+00 7.05332819E-13-1.99591964E-15 3 2.30081632E-18-9.27732332E-22 2.54736599E+04-4.46682853E-01 4 H2 TPIS78H 2 G 200.000 3500.000 1000.000 1 3.33727920E+00-4.94024731E-05 4.99456778E-07-1.79566394E-10 2.00255376E-14 2 -9.50158922E+02-3.20502331E+00 2.34433112E+00 7.98052075E-03-1.94781510E-05 3 2.01572094E-08-7.37611761E-12-9.17935173E+02 6.83010238E-01 4 OH RUS 78O 1H 1 G 200.000 3500.000 1000.000 1 3.09288767E+00 5.48429716E-04 1.26505228E-07-8.79461556E-11 1.17412376E-14 2 3.85865700E+03 4.47669610E+00 3.99201543E+00-2.40131752E-03 4.61793841E-06 3 -3.88113333E-09 1.36411470E-12 3.61508056E+03-1.03925458E-01 4 H2O L 8/89H 2O 1 G 200.000 3500.000 1000.000 1 3.03399249E+00 2.17691804E-03-1.64072518E-07-9.70419870E-11 1.68200992E-14 2 -3.00042971E+04 4.96677010E+00 4.19864056E+00-2.03643410E-03 6.52040211E-06 3 -5.48797062E-09 1.77197817E-12-3.02937267E+04-8.49032208E-01 4 HO2 L 5/89H 1O 2 G 200.000 3500.000 1000.000 1 4.01721090E+00 2.23982013E-03-6.33658150E-07 1.14246370E-10-1.07908535E-14 2 1.11856713E+02 3.78510215E+00 4.30179801E+00-4.74912051E-03 2.11582891E-05 3 -2.42763894E-08 9.29225124E-12 2.94808040E+02 3.71666245E+00 4 H2O2 L 7/88H 2O 2 G 200.000 3500.000 1000.000 1 4.16500285E+00 4.90831694E-03-1.90139225E-06 3.71185986E-10-2.87908305E-14 2 -1.78617877E+04 2.91615662E+00 4.27611269E+00-5.42822417E-04 1.67335701E-05 3 -2.15770813E-08 8.62454363E-12-1.77025821E+04 3.43505074E+00 4 C L11/88C 1 G 200.000 3500.000 1000.000 1 2.49266888E+00 4.79889284E-05-7.24335020E-08 3.74291029E-11-4.87277893E-15 2 8.54512953E+04 4.80150373E+00 2.55423955E+00-3.21537724E-04 7.33792245E-07 3 -7.32234889E-10 2.66521446E-13 8.54438832E+04 4.53130848E+00 4 CH TPIS79C 1H 1 G 200.000 3500.000 1000.000 1 2.87846473E+00 9.70913681E-04 1.44445655E-07-1.30687849E-10 1.76079383E-14 2 7.10124364E+04 5.48497999E+00 3.48981665E+00 3.23835541E-04-1.68899065E-06 3 3.16217327E-09-1.40609067E-12 7.07972934E+04 2.08401108E+00 4 CH2 L S/93C 1H 2 G 200.000 3500.000 1000.000 1 2.87410113E+00 3.65639292E-03-1.40894597E-06 2.60179549E-10-1.87727567E-14 2 4.62636040E+04 6.17119324E+00 3.76267867E+00 9.68872143E-04 2.79489841E-06 3 -3.85091153E-09 1.68741719E-12 4.60040401E+04 1.56253185E+00 4 CH2(S) L S/93C 1H 2 G 200.000 3500.000 1000.000 1 2.29203842E+00 4.65588637E-03-2.01191947E-06 4.17906000E-10-3.39716365E-14 2 5.09259997E+04 8.62650169E+00 4.19860411E+00-2.36661419E-03 8.23296220E-06 3 -6.68815981E-09 1.94314737E-12 5.04968163E+04-7.69118967E-01 4 CH3 L11/89C 1H 3 G 200.000 3500.000 1000.000 1 2.28571772E+00 7.23990037E-03-2.98714348E-06 5.95684644E-10-4.67154394E-14 2 1.67755843E+04 8.48007179E+00 3.67359040E+00 2.01095175E-03 5.73021856E-06 3 -6.87117425E-09 2.54385734E-12 1.64449988E+04 1.60456433E+00 4 CH4 L 8/88C 1H 4 G 200.000 3500.000 1000.000 1 7.48514950E-02 1.33909467E-02-5.73285809E-06 1.22292535E-09-1.01815230E-13 2 -9.46834459E+03 1.84373180E+01 5.14987613E+00-1.36709788E-02 4.91800599E-05 3 -4.84743026E-08 1.66693956E-11-1.02466476E+04-4.64130376E+00 4 CO TPIS79C 1O 1 G 200.000 3500.000 1000.000 1 2.71518561E+00 2.06252743E-03-9.98825771E-07 2.30053008E-10-2.03647716E-14 2 -1.41518724E+04 7.81868772E+00 3.57953347E+00-6.10353680E-04 1.01681433E-06 3 9.07005884E-10-9.04424499E-13-1.43440860E+04 3.50840928E+00 4 CO2 L 7/88C 1O 2 G 200.000 3500.000 1000.000 1 3.85746029E+00 4.41437026E-03-2.21481404E-06 5.23490188E-10-4.72084164E-14 2 -4.87591660E+04 2.27163806E+00 2.35677352E+00 8.98459677E-03-7.12356269E-06 3 2.45919022E-09-1.43699548E-13-4.83719697E+04 9.90105222E+00 4 HCO L12/89H 1C 1O 1 G 200.000 3500.000 1000.000 1 2.77217438E+00 4.95695526E-03-2.48445613E-06 5.89161778E-10-5.33508711E-14 2 4.01191815E+03 9.79834492E+00 4.22118584E+00-3.24392532E-03 1.37799446E-05 3 -1.33144093E-08 4.33768865E-12 3.83956496E+03 3.39437243E+00 4 CH2O L 8/88H 2C 1O 1 G 200.000 3500.000 1000.000 1 1.76069008E+00 9.20000082E-03-4.42258813E-06 1.00641212E-09-8.83855640E-14 2 -1.39958323E+04 1.36563230E+01 4.79372315E+00-9.90833369E-03 3.73220008E-05 3 -3.79285261E-08 1.31772652E-11-1.43089567E+04 6.02812900E-01 4 CH2OH GUNL93C 1H 3O 1 G 200.000 3500.000 1000.000 1 3.69266569E+00 8.64576797E-03-3.75101120E-06 7.87234636E-10-6.48554201E-14 2 -3.24250627E+03 5.81043215E+00 3.86388918E+00 5.59672304E-03 5.93271791E-06 3 -1.04532012E-08 4.36967278E-12-3.19391367E+03 5.47302243E+00 4 CH3O 121686C 1H 3O 1 G 300.00 3000.00 1000.000 1 0.03770799E+02 0.07871497E-01-0.02656384E-04 0.03944431E-08-0.02112616E-12 2 0.12783252E+03 0.02929575E+02 0.02106204E+02 0.07216595E-01 0.05338472E-04 3 -0.07377636E-07 0.02075610E-10 0.09786011E+04 0.13152177E+02 4 CH3OH L 8/88C 1H 4O 1 G 200.000 3500.000 1000.000 1 1.78970791E+00 1.40938292E-02-6.36500835E-06 1.38171085E-09-1.17060220E-13 2 -2.53748747E+04 1.45023623E+01 5.71539582E+00-1.52309129E-02 6.52441155E-05 3 -7.10806889E-08 2.61352698E-11-2.56427656E+04-1.50409823E+00 4 C2H L 1/91C 2H 1 G 200.000 3500.000 1000.000 1 3.16780652E+00 4.75221902E-03-1.83787077E-06 3.04190252E-10-1.77232770E-14 2 6.71210650E+04 6.63589475E+00 2.88965733E+00 1.34099611E-02-2.84769501E-05 3 2.94791045E-08-1.09331511E-11 6.68393932E+04 6.22296438E+00 4 C2H2 L 1/91C 2H 2 G 200.000 3500.000 1000.000 1 4.14756964E+00 5.96166664E-03-2.37294852E-06 4.67412171E-10-3.61235213E-14 2 2.59359992E+04-1.23028121E+00 8.08681094E-01 2.33615629E-02-3.55171815E-05 3 2.80152437E-08-8.50072974E-12 2.64289807E+04 1.39397051E+01 4 C2H3 L 2/92C 2H 3 G 200.000 3500.000 1000.000 1 3.01672400E+00 1.03302292E-02-4.68082349E-06 1.01763288E-09-8.62607041E-14 2 3.46128739E+04 7.78732378E+00 3.21246645E+00 1.51479162E-03 2.59209412E-05 3 -3.57657847E-08 1.47150873E-11 3.48598468E+04 8.51054025E+00 4 C2H4 L 1/91C 2H 4 G 200.000 3500.000 1000.000 1 2.03611116E+00 1.46454151E-02-6.71077915E-06 1.47222923E-09-1.25706061E-13 2 4.93988614E+03 1.03053693E+01 3.95920148E+00-7.57052247E-03 5.70990292E-05 3 -6.91588753E-08 2.69884373E-11 5.08977593E+03 4.09733096E+00 4 C2H5 L12/92C 2H 5 G 200.000 3500.000 1000.000 1 1.95465642E+00 1.73972722E-02-7.98206668E-06 1.75217689E-09-1.49641576E-13 2 1.28575200E+04 1.34624343E+01 4.30646568E+00-4.18658892E-03 4.97142807E-05 3 -5.99126606E-08 2.30509004E-11 1.28416265E+04 4.70720924E+00 4 C2H6 L 8/88C 2H 6 G 200.000 3500.000 1000.000 1 1.07188150E+00 2.16852677E-02-1.00256067E-05 2.21412001E-09-1.90002890E-13 2 -1.14263932E+04 1.51156107E+01 4.29142492E+00-5.50154270E-03 5.99438288E-05 3 -7.08466285E-08 2.68685771E-11-1.15222055E+04 2.66682316E+00 4 CH2CO L 5/90C 2H 2O 1 G 200.000 3500.000 1000.000 1 4.51129732E+00 9.00359745E-03-4.16939635E-06 9.23345882E-10-7.94838201E-14 2 -7.55105311E+03 6.32247205E-01 2.13583630E+00 1.81188721E-02-1.73947474E-05 3 9.34397568E-09-2.01457615E-12-7.04291804E+03 1.22156480E+01 4 HCCO SRIC91H 1C 2O 1 G 300.00 4000.00 1000.000 1 0.56282058E+01 0.40853401E-02-0.15934547E-05 0.28626052E-09-0.19407832E-13 2 0.19327215E+05-0.39302595E+01 0.22517214E+01 0.17655021E-01-0.23729101E-04 3 0.17275759E-07-0.50664811E-11 0.20059449E+05 0.12490417E+02 4 HCCOH SRI91C 2O 1H 2 G 300.000 5000.000 1000.000 1 0.59238291E+01 0.67923600E-02-0.25658564E-05 0.44987841E-09-0.29940101E-13 2 0.72646260E+04-0.76017742E+01 0.12423733E+01 0.31072201E-01-0.50866864E-04 3 0.43137131E-07-0.14014594E-10 0.80316143E+04 0.13874319E+02 4 H2CN 41687H 2C 1N 1 G 300.00 4000.000 1000.000 1 0.52097030E+01 0.29692911E-02-0.28555891E-06-0.16355500E-09 0.30432589E-13 2 0.27677109E+05-0.44444780E+01 0.28516610E+01 0.56952331E-02 0.10711400E-05 3 -0.16226120E-08-0.23511081E-12 0.28637820E+05 0.89927511E+01 4 HCN GRI/98H 1C 1N 1 G 200.000 6000.000 1000.000 1 0.38022392E+01 0.31464228E-02-0.10632185E-05 0.16619757E-09-0.97997570E-14 2 0.14407292E+05 0.15754601E+01 0.22589886E+01 0.10051170E-01-0.13351763E-04 3 0.10092349E-07-0.30089028E-11 0.14712633E+05 0.89164419E+01 4 HNO And93 H 1N 1O 1 G 200.000 6000.000 1000.000 1 0.29792509E+01 0.34944059E-02-0.78549778E-06 0.57479594E-10-0.19335916E-15 2 0.11750582E+05 0.86063728E+01 0.45334916E+01-0.56696171E-02 0.18473207E-04 3 -0.17137094E-07 0.55454573E-11 0.11548297E+05 0.17498417E+01 4 N L 6/88N 1 G 200.000 6000.000 1000.000 1 0.24159429E+01 0.17489065E-03-0.11902369E-06 0.30226245E-10-0.20360982E-14 2 0.56133773E+05 0.46496096E+01 0.25000000E+01 0.00000000E+00 0.00000000E+00 3 0.00000000E+00 0.00000000E+00 0.56104637E+05 0.41939087E+01 4 NNH T07/93N 2H 1 G 200.000 6000.000 1000.000 1 0.37667544E+01 0.28915082E-02-0.10416620E-05 0.16842594E-09-0.10091896E-13 2 0.28650697E+05 0.44705067E+01 0.43446927E+01-0.48497072E-02 0.20059459E-04 3 -0.21726464E-07 0.79469539E-11 0.28791973E+05 0.29779410E+01 4 N2O L 7/88N 2O 1 G 200.000 6000.000 1000.000 1 0.48230729E+01 0.26270251E-02-0.95850874E-06 0.16000712E-09-0.97752303E-14 2 0.80734048E+04-0.22017207E+01 0.22571502E+01 0.11304728E-01-0.13671319E-04 3 0.96819806E-08-0.29307182E-11 0.87417744E+04 0.10757992E+02 4 NH And94 N 1H 1 G 200.000 6000.000 1000.000 1 0.27836928E+01 0.13298430E-02-0.42478047E-06 0.78348501E-10-0.55044470E-14 2 0.42120848E+05 0.57407799E+01 0.34929085E+01 0.31179198E-03-0.14890484E-05 3 0.24816442E-08-0.10356967E-11 0.41880629E+05 0.18483278E+01 4 NH2 And89 N 1H 2 G 200.000 6000.000 1000.000 1 0.28347421E+01 0.32073082E-02-0.93390804E-06 0.13702953E-09-0.79206144E-14 2 0.22171957E+05 0.65204163E+01 0.42040029E+01-0.21061385E-02 0.71068348E-05 3 -0.56115197E-08 0.16440717E-11 0.21885910E+05-0.14184248E+00 4 NH3 J 6/77N 1H 3 G 200.000 6000.000 1000.000 1 0.26344521E+01 0.56662560E-02-0.17278676E-05 0.23867161E-09-0.12578786E-13 2 -0.65446958E+04 0.65662928E+01 0.42860274E+01-0.46605230E-02 0.21718513E-04 3 -0.22808887E-07 0.82638046E-11-0.67417285E+04-0.62537277E+00 4 NO RUS 78N 1O 1 G 200.000 6000.000 1000.000 1 0.32606056E+01 0.11911043E-02-0.42917048E-06 0.69457669E-10-0.40336099E-14 2 0.99209746E+04 0.63693027E+01 0.42184763E+01-0.46389760E-02 0.11041022E-04 3 -0.93361354E-08 0.28035770E-11 0.98446230E+04 0.22808464E+01 4 NO2 L 7/88N 1O 2 G 200.000 6000.000 1000.000 1 0.48847542E+01 0.21723956E-02-0.82806906E-06 0.15747510E-09-0.10510895E-13 2 0.23164983E+04-0.11741695E+00 0.39440312E+01-0.15854290E-02 0.16657812E-04 3 -0.20475426E-07 0.78350564E-11 0.28966179E+04 0.63119917E+01 4 HCNO BDEA94H 1N 1C 1O 1G 300.000 5000.000 1382.000 1 6.59860456E+00 3.02778626E-03-1.07704346E-06 1.71666528E-10-1.01439391E-14 2 1.79661339E+04-1.03306599E+01 2.64727989E+00 1.27505342E-02-1.04794236E-05 3 4.41432836E-09-7.57521466E-13 1.92990252E+04 1.07332972E+01 4 HOCN BDEA94H 1N 1C 1O 1G 300.000 5000.000 1368.000 1 5.89784885E+00 3.16789393E-03-1.11801064E-06 1.77243144E-10-1.04339177E-14 2 -3.70653331E+03-6.18167825E+00 3.78604952E+00 6.88667922E-03-3.21487864E-06 3 5.17195767E-10 1.19360788E-14-2.82698400E+03 5.63292162E+00 4 HNCO BDEA94H 1N 1C 1O 1G 300.000 5000.000 1478.000 1 6.22395134E+00 3.17864004E-03-1.09378755E-06 1.70735163E-10-9.95021955E-15 2 -1.66599344E+04-8.38224741E+00 3.63096317E+00 7.30282357E-03-2.28050003E-06 3 -6.61271298E-10 3.62235752E-13-1.55873636E+04 6.19457727E+00 4 NCO EA 93 N 1C 1O 1 G 200.000 6000.000 1000.000 1 0.51521845E+01 0.23051761E-02-0.88033153E-06 0.14789098E-09-0.90977996E-14 2 0.14004123E+05-0.25442660E+01 0.28269308E+01 0.88051688E-02-0.83866134E-05 3 0.48016964E-08-0.13313595E-11 0.14682477E+05 0.95504646E+01 4 CN HBH92 C 1N 1 G 200.000 6000.000 1000.000 1 0.37459805E+01 0.43450775E-04 0.29705984E-06-0.68651806E-10 0.44134173E-14 2 0.51536188E+05 0.27867601E+01 0.36129351E+01-0.95551327E-03 0.21442977E-05 3 -0.31516323E-09-0.46430356E-12 0.51708340E+05 0.39804995E+01 4 HCNN SRI/94C 1N 2H 1 G 300.000 5000.000 1000.000 1 0.58946362E+01 0.39895959E-02-0.15982380E-05 0.29249395E-09-0.20094686E-13 2 0.53452941E+05-0.51030502E+01 0.25243194E+01 0.15960619E-01-0.18816354E-04 3 0.12125540E-07-0.32357378E-11 0.54261984E+05 0.11675870E+02 4 N2 121286N 2 G 300.000 5000.000 1000.000 1 0.02926640E+02 0.14879768E-02-0.05684760E-05 0.10097038E-09-0.06753351E-13 2 -0.09227977E+04 0.05980528E+02 0.03298677E+02 0.14082404E-02-0.03963222E-04 3 0.05641515E-07-0.02444854E-10-0.10208999E+04 0.03950372E+02 4 AR 120186AR 1 G 300.000 5000.000 1000.000 1 0.02500000E+02 0.00000000E+00 0.00000000E+00 0.00000000E+00 0.00000000E+00 2 -0.07453750E+04 0.04366000E+02 0.02500000E+02 0.00000000E+00 0.00000000E+00 3 0.00000000E+00 0.00000000E+00-0.07453750E+04 0.04366000E+02 4 C3H8 L 4/85C 3H 8 G 300.000 5000.000 1000.000 1 0.75341368E+01 0.18872239E-01-0.62718491E-05 0.91475649E-09-0.47838069E-13 2 -0.16467516E+05-0.17892349E+02 0.93355381E+00 0.26424579E-01 0.61059727E-05 3 -0.21977499E-07 0.95149253E-11-0.13958520E+05 0.19201691E+02 4 C3H7 L 9/84C 3H 7 G 300.000 5000.000 1000.000 1 0.77026987E+01 0.16044203E-01-0.52833220E-05 0.76298590E-09-0.39392284E-13 2 0.82984336E+04-0.15480180E+02 0.10515518E+01 0.25991980E-01 0.23800540E-05 3 -0.19609569E-07 0.93732470E-11 0.10631863E+05 0.21122559E+02 4 CH3CHO L 8/88C 2H 4O 1 G 200.000 6000.000 1000.000 1 0.54041108E+01 0.11723059E-01-0.42263137E-05 0.68372451E-09-0.40984863E-13 2 -0.22593122E+05-0.34807917E+01 0.47294595E+01-0.31932858E-02 0.47534921E-04 3 -0.57458611E-07 0.21931112E-10-0.21572878E+05 0.41030159E+01 4 CH2CHO SAND86O 1H 3C 2 G 300.000 5000.000 1000.000 1 0.05975670E+02 0.08130591E-01-0.02743624E-04 0.04070304E-08-0.02176017E-12 2 0.04903218E+04-0.05045251E+02 0.03409062E+02 0.10738574E-01 0.01891492E-04 3 -0.07158583E-07 0.02867385E-10 0.15214766E+04 0.09558290E+02 4 END \\ \\ \\ This is the tran file \\ \\ AR 0 136.500 3.330 0.000 0.000 0.000 C 0 71.400 3.298 0.000 0.000 0.000 ! * C2 1 97.530 3.621 0.000 1.760 4.000 C2O 1 232.400 3.828 0.000 0.000 1.000 ! * CN2 1 232.400 3.828 0.000 0.000 1.000 ! OIS C2H 1 209.000 4.100 0.000 0.000 2.500 C2H2 1 209.000 4.100 0.000 0.000 2.500 C2H2OH 2 224.700 4.162 0.000 0.000 1.000 ! * C2H3 2 209.000 4.100 0.000 0.000 1.000 ! * C2H4 2 280.800 3.971 0.000 0.000 1.500 C2H5 2 252.300 4.302 0.000 0.000 1.500 C2H6 2 252.300 4.302 0.000 0.000 1.500 C2N 1 232.400 3.828 0.000 0.000 1.000 ! OIS C2N2 1 349.000 4.361 0.000 0.000 1.000 ! OIS C3H2 2 209.000 4.100 0.000 0.000 1.000 ! * C3H4 1 252.000 4.760 0.000 0.000 1.000 C3H6 2 266.800 4.982 0.000 0.000 1.000 C3H7 2 266.800 4.982 0.000 0.000 1.000 C4H6 2 357.000 5.180 0.000 0.000 1.000 I*C3H7 2 266.800 4.982 0.000 0.000 1.000 N*C3H7 2 266.800 4.982 0.000 0.000 1.000 C3H8 2 266.800 4.982 0.000 0.000 1.000 C4H 1 357.000 5.180 0.000 0.000 1.000 C4H2 1 357.000 5.180 0.000 0.000 1.000 C4H2OH 2 224.700 4.162 0.000 0.000 1.000 ! * C4H8 2 357.000 5.176 0.000 0.000 1.000 C4H9 2 357.000 5.176 0.000 0.000 1.000 I*C4H9 2 357.000 5.176 0.000 0.000 1.000 C5H2 1 357.000 5.180 0.000 0.000 1.000 C5H3 1 357.000 5.180 0.000 0.000 1.000 C6H2 1 357.000 5.180 0.000 0.000 1.000 C6H5 2 412.300 5.349 0.000 0.000 1.000 ! JAM C6H5O 2 450.000 5.500 0.000 0.000 1.000 ! JAM C5H5OH 2 450.000 5.500 0.000 0.000 1.000 ! JAM C6H6 2 412.300 5.349 0.000 0.000 1.000 ! SVE C6H7 2 412.300 5.349 0.000 0.000 1.000 ! JAM CH 1 80.000 2.750 0.000 0.000 0.000 CH2 1 144.000 3.800 0.000 0.000 0.000 CH2(S) 1 144.000 3.800 0.000 0.000 0.000 CH2* 1 144.000 3.800 0.000 0.000 0.000 CH2CHCCH 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH2CHCCH2 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH2CHCH2 2 260.000 4.850 0.000 0.000 1.000 ! JAM CH2CHCHCH 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH2CHCHCH2 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH2CO 2 436.000 3.970 0.000 0.000 2.000 CH2O 2 498.000 3.590 0.000 0.000 2.000 CH2OH 2 417.000 3.690 1.700 0.000 2.000 CH3 1 144.000 3.800 0.000 0.000 0.000 CH3CC 2 252.000 4.760 0.000 0.000 1.000 ! JAM CH3CCCH2 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH3CCCH3 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH3CCH2 2 260.000 4.850 0.000 0.000 1.000 ! JAM CH3CHCH 2 260.000 4.850 0.000 0.000 1.000 ! JAM CH3CH2CCH 2 357.000 5.180 0.000 0.000 1.000 ! JAM CH3CHO 2 436.000 3.970 0.000 0.000 2.000 CH2CHO 2 436.000 3.970 0.000 0.000 2.000 CH3CO 2 436.000 3.970 0.000 0.000 2.000 CH3O 2 417.000 3.690 1.700 0.000 2.000 CH3OH 2 481.800 3.626 0.000 0.000 1.000 ! SVE CH4 2 141.400 3.746 0.000 2.600 13.000 CH4O 2 417.000 3.690 1.700 0.000 2.000 CN 1 75.000 3.856 0.000 0.000 1.000 ! OIS CNC 1 232.400 3.828 0.000 0.000 1.000 ! OIS CNN 1 232.400 3.828 0.000 0.000 1.000 ! OIS CO 1 98.100 3.650 0.000 1.950 1.800 CO2 1 244.000 3.763 0.000 2.650 2.100 H 0 145.000 2.050 0.000 0.000 0.000 H2C4O 2 357.000 5.180 0.000 0.000 1.000 ! JAM H2 1 38.000 2.920 0.000 0.790 280.000 H2CCCCH 2 357.000 5.180 0.000 0.000 1.000 ! JAM H2CCCCH2 2 357.000 5.180 0.000 0.000 1.000 ! JAM H2CCCH 2 252.000 4.760 0.000 0.000 1.000 ! JAM H2CN 1 569.000 3.630 0.000 0.000 1.000 ! os/jm H2NO 2 116.700 3.492 0.000 0.000 1.000 ! JAM H2O 2 572.400 2.605 1.844 0.000 4.000 H2O2 2 107.400 3.458 0.000 0.000 3.800 HC2N2 1 349.000 4.361 0.000 0.000 1.000 ! OIS HCCHCCH 2 357.000 5.180 0.000 0.000 1.000 ! JAM HCCO 2 150.000 2.500 0.000 0.000 1.000 ! * HCNN 2 150.000 2.500 0.000 0.000 1.000 ! * HCCOH 2 436.000 3.970 0.000 0.000 2.000 HCN 1 569.000 3.630 0.000 0.000 1.000 ! OIS HCO 2 498.000 3.590 0.000 0.000 0.000 HE 0 10.200 2.576 0.000 0.000 0.000 ! * HCNO 2 232.400 3.828 0.000 0.000 1.000 ! JAM HOCN 2 232.400 3.828 0.000 0.000 1.000 ! JAM HNCO 2 232.400 3.828 0.000 0.000 1.000 ! OIS HNNO 2 232.400 3.828 0.000 0.000 1.000 ! * HNO 2 116.700 3.492 0.000 0.000 1.000 ! * HNOH 2 116.700 3.492 0.000 0.000 1.000 ! JAM HO2 2 107.400 3.458 0.000 0.000 1.000 ! * N 0 71.400 3.298 0.000 0.000 0.000 ! * N2 1 97.530 3.621 0.000 1.760 4.000 N2H2 2 71.400 3.798 0.000 0.000 1.000 ! * N2H3 2 200.000 3.900 0.000 0.000 1.000 ! * N2H4 2 205.000 4.230 0.000 4.260 1.500 N2O 1 232.400 3.828 0.000 0.000 1.000 ! * NCN 1 232.400 3.828 0.000 0.000 1.000 ! OIS NCO 1 232.400 3.828 0.000 0.000 1.000 ! OIS NH 1 80.000 2.650 0.000 0.000 4.000 NH2 2 80.000 2.650 0.000 2.260 4.000 NH3 2 481.000 2.920 1.470 0.000 10.000 NNH 2 71.400 3.798 0.000 0.000 1.000 ! * NO 1 97.530 3.621 0.000 1.760 4.000 NCNO 2 232.400 3.828 0.000 0.000 1.000 ! OIS NO2 2 200.000 3.500 0.000 0.000 1.000 ! * O 0 80.000 2.750 0.000 0.000 0.000 O2 1 107.400 3.458 0.000 1.600 3.800 OH 1 80.000 2.750 0.000 0.000 0.000 #endif
deconvolution_pack8to1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void deconvolution_pack8to1_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_packed, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; const int maxk = kernel_w * kernel_h; const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float sum = 0.f; if (bias_data_ptr) { sum = bias_data_ptr[p]; } __m256 _sum = _mm256_setzero_ps(); const float* kptr = weight_data_packed.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); for (int y = 0; y < kernel_h; y++) { int sys = (i + y * dilation_h - (kernel_extent_h - 1)); if (sys < 0 || sys % stride_h != 0) continue; int sy = sys / stride_h; if (sy >= h) continue; for (int x = 0; x < kernel_w; x++) { int sxs = (j + x * dilation_w - (kernel_extent_w - 1)); if (sxs < 0 || sxs % stride_w != 0) continue; int sx = sxs / stride_w; if (sx >= w) continue; const float* sptr = m.row(sy) + sx * 8; int k = y * kernel_w + x; __m256 _val = _mm256_load_ps(sptr); __m256 _w = _mm256_load_ps(kptr + k * 8); _sum = _mm256_comp_fmadd_ps(_val, _w, _sum); } } kptr += maxk * 8; } sum += _mm256_reduce_add_ps(_sum); sum = activation_ss(sum, activation_type, activation_params); outptr[0] = sum; outptr++; } } } }
matmul.c
//------------------------------------------------------------------------------------------------------------------------------ // Samuel Williams // SWWilliams@lbl.gov // Lawrence Berkeley National Lab //------------------------------------------------------------------------------------------------------------------------------ void matmul(level_type * level, double *C, int * id_A, int * id_B, int rows, int cols, int A_equals_B_transpose){ // *id_A = m vector_id's (conceptually pointers to the rows of a m x level->num_my_boxes*volume matrix) // *id_B = n vector_id's (conceptually pointers to the columns of a level->num_my_boxes*volume matrix x n) // *C is a mxn matrix where C[rows][cols] = dot(id_A[rows],id_B[cols]) // FIX, id_A and id_B are likely the same and thus C[][] will be symmetric (modulo missing row?) // if(A_equals_B_transpose && (cols>=rows)) then use id_B and only run for nn>=mm // common case for s-step Krylov methods // C_is_symmetric && cols< rows (use id_A) int mm,nn; uint64_t _timeStart = CycleTime(); // FIX... rather than performing an all_reduce on the essentially symmetric [G,g], do the all_reduce on the upper triangle and then duplicate (saves BW) // #pragma omp parallel for schedule(static,1) collapse(2) hclib::finish([] { hclib::loop_domain_2d loop(rows, cols); hclib::forasync(&loop, [] (int mm, int nn) { if(nn>=mm){ // upper triangular int box; double a_dot_b_level = 0.0; for(box=0;box<level->num_my_boxes;box++){ int i,j,k; const int jStride = level->my_boxes[box].jStride; const int kStride = level->my_boxes[box].kStride; const int ghosts = level->my_boxes[box].ghosts; const int dim = level->my_boxes[box].dim; double * __restrict__ grid_a = level->my_boxes[box].vectors[id_A[mm]] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point double * __restrict__ grid_b = level->my_boxes[box].vectors[id_B[nn]] + ghosts*(1+jStride+kStride); double a_dot_b_box = 0.0; for(k=0;k<dim;k++){ for(j=0;j<dim;j++){ for(i=0;i<dim;i++){ int ijk = i + j*jStride + k*kStride; a_dot_b_box += grid_a[ijk]*grid_b[ijk]; }}} a_dot_b_level+=a_dot_b_box; } C[mm*cols + nn] = a_dot_b_level; // C[mm][nn] if((mm<cols)&&(nn<rows)){C[nn*cols + mm] = a_dot_b_level;}// C[nn][mm] } }); }); level->cycles.blas3 += (uint64_t)(CycleTime()-_timeStart); #ifdef USE_MPI double *send_buffer = (double*)malloc(rows*cols*sizeof(double)); for(mm=0;mm<rows;mm++){ for(nn=0;nn<cols;nn++){ send_buffer[mm*cols + nn] = C[mm*cols + nn]; }} uint64_t _timeStartAllReduce = CycleTime(); hclib::MPI_Allreduce(send_buffer,C,rows*cols,MPI_DOUBLE,MPI_SUM,level->MPI_COMM_ALLREDUCE); uint64_t _timeEndAllReduce = CycleTime(); level->cycles.collectives += (uint64_t)(_timeEndAllReduce-_timeStartAllReduce); free(send_buffer); #endif }
GB_unop__identity_fp32_uint32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fp32_uint32) // op(A') function: GB (_unop_tran__identity_fp32_uint32) // C type: float // A type: uint32_t // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ float z = (float) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fp32_uint32) ( float *Cx, // Cx and Ax may be aliased const uint32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint32_t aij = Ax [p] ; float z = (float) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint32_t aij = Ax [p] ; float z = (float) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fp32_uint32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
FrameBuffer.h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include <mutex> #include <iostream> #include <fstream> #include <array> #include <vector> #include <memory> #include <malloc.h> #include "bb/DataType.h" #include "bb/Object.h" #include "bb/Tensor.h" namespace bb { // [FrameBuffer クラス] // ・LayerとLayerの接続に利用 // ・Layerのパラメータ構成に必要な情報を保持 // ・Tensorクラスで実体を保有 // ・Tensor内のデータの各次元の意味付けを行う(Sparseで性能の出る軸で管理) // // 外部APIとしては、Tensor が複数フレーム格納されるたような形式に見せる // 内部的には1つの Tensor に統合する。即ち内部 Tensor は次数が1多い // メモリ配置は NCHW でも NHWC でもなく、CHWN を意図しており、N = frame の意である // // また ここで node_size や node などの語を定義している。これは各フレームの // Tensor を1次元のフラットでアクセスする事を意図した用語である。 // CUDAやSIMD命令での操作を強く意図しており、これらを使ってプログラミングするときは // メモリ配置を強く意識する必要がある。 shape は上位からメモリにアクセスをする際に // 利便性を向上させる為のものである。 // 同じノードへのアクセス方法として、 // ・フレーム番号+ノード番号 // ・フレーム番号+shapeに従った多次元の添え字 // の2種類があるので注意すること // ------------------------------------- // アクセス用ポインタクラス定義 // ------------------------------------- class FrameBuffer; // const アクセス用 template <typename Tp, class FrameBufferTp, class PtrTp> class FrameBufferConstPtr_ { friend FrameBufferTp; protected: FrameBufferTp* m_buf; PtrTp m_ptr; protected: FrameBufferConstPtr_(FrameBufferTp* buf) { m_buf = buf; } public: FrameBufferConstPtr_(FrameBufferConstPtr_ const &buf) { m_buf = buf.m_buf; m_ptr = buf.m_ptr; } protected: inline void Lock(void) { m_ptr = m_buf->LockMemoryConst(); } inline void const *GetNodeBaseAddr(index_t node) const { auto addr = (std::uint8_t const *)m_ptr.GetAddr(); return addr + (m_buf->m_frame_stride * node); } inline index_t GetNodeIndex(indices_t const & indices) const { return ConvertIndicesToIndex(indices, m_buf->GetShape()); } inline index_t GetNodeIndex(index_t i0) const { return ConvertIndicesToIndex(i0, m_buf->GetShape()); } inline index_t GetNodeIndex(index_t i0, index_t i1) const { return ConvertIndicesToIndex(i0, i1, m_buf->GetShape()); } inline index_t GetNodeIndex(index_t i0, index_t i1, index_t i2) const { return ConvertIndicesToIndex(i0, i1, i2, m_buf->GetShape()); } inline Tp ReadValue(void const *base, index_t frame) const { return DataType_Read<Tp>(base, frame); } public: inline FrameBuffer const &GetFrameBuffer(void) const { return *m_buf; } inline Tp const *GetAddr(void) const { return (Tp *)m_ptr.GetAddr(); } inline Tp const *GetAddr(index_t node) const { return (Tp *)GetNodeBaseAddr(node); } inline Tp Get(index_t frame, index_t node) const { return ReadValue(GetNodeBaseAddr(node), frame); } inline Tp Get(index_t frame, indices_t indices) const { return Get(frame, GetNodeIndex(indices)); } inline Tp Get(index_t frame, index_t i0, index_t i1) const { return Get(frame, GetNodeIndex(i0, i1)); } inline Tp Get(index_t frame, index_t i0, index_t i1, index_t i2) const { return Get(frame, GetNodeIndex(i0, i1, i2)); } }; // 非const アクセス用 template <typename Tp, class FrameBufferTp, class PtrTp> class FrameBufferPtr_ : public FrameBufferConstPtr_<Tp, FrameBufferTp, PtrTp> { friend FrameBufferTp; using FrameBufferConstPtr_<Tp, FrameBufferTp, PtrTp>::m_buf; using FrameBufferConstPtr_<Tp, FrameBufferTp, PtrTp>::m_ptr; protected: FrameBufferPtr_(FrameBufferTp* buf) : FrameBufferConstPtr_<Tp, FrameBufferTp, PtrTp>(buf) { } inline void Lock(bool new_buf) { m_ptr = m_buf->LockMemory(new_buf); } protected: inline void *GetNodeBaseAddr(index_t node) { BB_DEBUG_ASSERT(node >= 0 && node < m_buf->GetNodeSize()); auto addr = (std::uint8_t *)m_ptr.GetAddr(); return addr + (m_buf->m_frame_stride * node); } inline index_t GetNodeIndex(indices_t const & indices) { return ConvertIndicesToIndex(indices, m_buf->m_node_shape); } inline index_t GetNodeIndex(index_t i0) { return ConvertIndicesToIndex(i0, m_buf->m_node_shape); } inline index_t GetNodeIndex(index_t i0, index_t i1) { return ConvertIndicesToIndex(i0, i1, m_buf->m_node_shape); } inline index_t GetNodeIndex(index_t i0, index_t i1, index_t i2) { return ConvertIndicesToIndex(i0, i1, i2, m_buf->m_node_shape); } inline void WriteValue(void *base, index_t frame, Tp value) { return DataType_Write<Tp>(base, frame, value); } inline void AddValue(void *base, index_t frame, Tp value) { return DataType_Add<Tp>(base, frame, value); } public: inline Tp *GetAddr(void) { return (Tp *)m_ptr.GetAddr(); } inline Tp *GetAddr(index_t node) { return (Tp *)GetNodeBaseAddr(node); } inline void Set(index_t frame, index_t node, Tp value) { return WriteValue(GetNodeBaseAddr(node), frame, value); } inline void Set(index_t frame, indices_t indices, Tp value) { return Set(frame, GetNodeIndex(indices), value); } inline void Set(index_t frame, index_t i0, index_t i1, Tp value) { return Set(frame, GetNodeIndex(i0, i1), value); } inline void Set(index_t frame, index_t i0, index_t i1, index_t i2, Tp value) { return Set(frame, GetNodeIndex(i0, i1, i2), value); } inline void Add(index_t frame, index_t node, Tp value) { return AddValue(GetNodeBaseAddr(node), frame, value); } inline void Add(index_t frame, indices_t indices, Tp value) { return Add(frame, GetNodeIndex(indices), value); } inline void Add(index_t frame, index_t i0, index_t i1, Tp value) { return Add(frame, GetNodeIndex(i0, i1), value); } inline void Add(index_t frame, index_t i0, index_t i1, index_t i2, Tp value) { return Add(frame, GetNodeIndex(i0, i1, i2), value); } }; // NeuralNet用のバッファ class FrameBuffer : public Object { using _super = Object; public: static inline std::string ObjectName(void){ return "FrameBuffer"; } std::string GetObjectName(void) const override { return ObjectName(); } protected: Tensor m_tensor; int m_data_type = 0; index_t m_frame_size = 0; index_t m_frame_stride = 0; index_t m_node_size = 0; indices_t m_node_shape; public: /** * @brief デフォルトコンストラクタ * @detail デフォルトコンストラクタ */ // explicit FrameBuffer(bool host_only=false) : m_tensor(host_only) {} /** * @brief コンストラクタ * @detail コンストラクタ * tensor は node_size サイズの1次元で初期化 * @param frame_size フレーム数 * @param node_size 1フレームのノード数 * @param data_type 1ノードのデータ型 */ // explicit FrameBuffer(index_t frame_size, index_t node_size, int data_type, bool host_only=false) : m_tensor(host_only) // { // Resize(frame_size, indices_t({node_size}), data_type); // } /** * @brief コンストラクタ * @detail コンストラクタ * @param frame_size フレーム数 * @param shape 1フレームのノードを構成するshape * @param data_type 1ノードのデータ型 */ explicit FrameBuffer(index_t frame_size=0, indices_t shape=indices_t(), int data_type=BB_TYPE_FP32, bool host_only=false) : m_tensor(host_only) { if ( frame_size > 0 ) { Resize(frame_size, shape, data_type); } } /** * @brief コピーコンストラクタ * @detail コピーコンストラクタ */ FrameBuffer(FrameBuffer const &buf) { *this = buf; } /** * @brief 代入演算子 * @detail 代入演算子 * 代入演算子でのコピーは、メモリは同じ箇所を指す */ FrameBuffer& operator=(FrameBuffer const &buf) { m_tensor = buf.m_tensor; m_data_type = buf.m_data_type; m_frame_size = buf.m_frame_size; m_frame_stride = buf.m_frame_stride; m_node_size = buf.m_node_size; m_node_shape = buf.m_node_shape; return *this; } #ifdef BB_PYBIND11 template<typename Tp> static FrameBuffer FromNumpy(pybind11::array_t<Tp> ndarray, int data_type, index_t frame_size, index_t frame_stride, indices_t node_shape, bool host_only=false) { FrameBuffer buf; buf.m_tensor = Tensor_<Tp>::FromNumpy(ndarray, host_only); buf.m_data_type = data_type; buf.m_frame_size = frame_size; buf.m_frame_stride = frame_stride; buf.m_node_shape = node_shape; buf.m_node_size = CalcShapeSize(node_shape); return buf; } template<typename Tp> pybind11::array_t<Tp> Numpy(void) { return m_tensor.Numpy<Tp>(); } #endif /** * @brief クローン * @detail クローン * @return メモリ内容をコピーしたクローンを返す */ FrameBuffer Clone(void) const { FrameBuffer clone_buf; clone_buf.m_tensor = m_tensor.Clone(); clone_buf.m_data_type = m_data_type; clone_buf.m_frame_size = m_frame_size; clone_buf.m_frame_stride = m_frame_stride; clone_buf.m_node_size = m_node_size; clone_buf.m_node_shape = m_node_shape; return clone_buf; } bool IsHostOnly(void) const { return m_tensor.IsHostOnly(); } bool Empty(void) const { return (m_frame_size == 0); } /** * @brief デバイスが利用可能か問い合わせる * @detail デバイスが利用可能か問い合わせる * @return デバイスが利用可能ならtrue */ bool IsDeviceAvailable(void) const { return m_tensor.IsDeviceAvailable(); } /** * @brief サイズ設定 * @detail サイズ設定 * @param frame_size フレーム数 * @param shape 1フレームのノードを構成するshape * @param data_type 1ノードのデータ型 */ static index_t CalcFrameStride(int data_type, index_t frame_size) { return ((frame_size * DataType_GetBitSize(data_type) + 255) / 256) * (256 / 8); // frame軸は256bit境界にあわせる(SIMD命令用) } /** * @brief サイズ設定 * @detail サイズ設定 * @param frame_size フレーム数 * @param shape 1フレームのノードを構成するshape * @param data_type 1ノードのデータ型 */ void Resize(index_t frame_size, indices_t shape, int data_type) { m_data_type = data_type; m_frame_size = frame_size; m_frame_stride = CalcFrameStride(data_type, frame_size); // frame軸は256bit境界にあわせる(SIMD命令用) m_node_shape = shape; // Bit型は内部 UINT8 で扱う int tensor_type = data_type; if ( data_type == BB_TYPE_BIT || data_type == BB_TYPE_BINARY ) { tensor_type = BB_TYPE_UINT8; } // サイズ計算 m_node_size = 1; std::vector<index_t> tensor_shape; for ( auto size : shape ) { tensor_shape.push_back(size); m_node_size *= size; } tensor_shape.push_back(m_frame_stride / DataType_GetByteSize(tensor_type)); // メモリ確保 m_tensor.Resize(tensor_shape, tensor_type); } /** * @brief 同じ型同じサイズにする * @detail 同じ型同じサイズにする * @param buf 型とサイズをあわせる対象 */ void ResizeLike(FrameBuffer const &buf) { Resize(buf.GetFrameSize(), buf.GetShape(), buf.GetType()); } template <typename T> void CopyTo_(FrameBuffer& dst, index_t frame_size = 0, index_t src_frame_offset = 0, index_t dst_frame_offset = 0, index_t node_size = 0, index_t src_node_offset = 0, index_t dst_node_offset = 0) const { auto dst_ptr = dst.Lock<T>(); auto src_ptr = LockConst<T>(); for ( index_t node = 0; node < node_size; ++node) { for ( index_t frame = 0; frame < frame_size; ++frame) { dst_ptr.Set(frame + dst_frame_offset, node + dst_node_offset, src_ptr.Get(frame + src_frame_offset, node + src_node_offset)); } } } /** * @brief コピー * @detail コピーを行う */ void CopyTo(FrameBuffer& dst, index_t frame_size = 0, index_t src_frame_offset=0, index_t dst_frame_offset=0, index_t node_size = 0,index_t src_node_offset=0, index_t dst_node_offset=0) const { BB_ASSERT(dst.GetType() == GetType()); if ( node_size <= 0) { node_size = std::min(dst.GetNodeSize() - dst_node_offset, GetFrameSize() - src_node_offset); } if ( frame_size <= 0) { frame_size = std::min(dst.GetFrameSize() - dst_frame_offset, GetFrameSize() - dst_frame_offset); } BB_ASSERT(frame_size + src_frame_offset <= GetFrameSize()); BB_ASSERT(frame_size + dst_frame_offset <= dst.GetFrameSize()); BB_ASSERT(node_size + src_node_offset <= GetNodeSize()); BB_ASSERT(node_size + dst_node_offset <= dst.GetNodeSize()); #ifdef BB_WITH_CUDA if (dst.IsDeviceAvailable() && IsDeviceAvailable()) { if ( DataType_GetBitSize(GetType()) == 32 ) { auto dst_ptr = dst.LockDeviceMemory(); auto src_ptr = LockDeviceMemoryConst(); bbcu_int32_FrameBufferCopy ( (int *)dst_ptr.GetAddr(), (int const *)src_ptr.GetAddr(), (int )node_size, (int )dst_node_offset, (int )src_node_offset, (int )frame_size, (int )dst_frame_offset, (int )src_frame_offset, (int )(dst.GetFrameStride() / 4), (int )(GetFrameStride() / 4) ); return; } if ( DataType_GetBitSize(GetType()) == 1 ) { BB_ASSERT(dst_frame_offset % 32 == 0); BB_ASSERT(src_frame_offset % 32 == 0); BB_ASSERT(frame_size % 32 == 0); auto dst_ptr = dst.LockDeviceMemory(); auto src_ptr = LockDeviceMemoryConst(); bbcu_int32_FrameBufferCopy ( (int *)dst_ptr.GetAddr(), (int const *)src_ptr.GetAddr(), (int )node_size, (int )dst_node_offset, (int )src_node_offset, (int )(frame_size / 32), (int )(dst_frame_offset / 32), (int )(src_frame_offset / 32), (int )(dst.GetFrameStride() / 4), (int )(GetFrameStride() / 4) ); return; } } #endif switch ( GetType() ) { case BB_TYPE_BIT: CopyTo_<Bit >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_FP32: CopyTo_<float >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_FP64: CopyTo_<double >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_INT8: CopyTo_<int8_t >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_INT16: CopyTo_<int16_t >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_INT32: CopyTo_<int32_t >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_INT64: CopyTo_<int64_t >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_UINT8: CopyTo_<uint8_t >(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_UINT16: CopyTo_<uint16_t>(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_UINT32: CopyTo_<uint32_t>(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; case BB_TYPE_UINT64: CopyTo_<uint64_t>(dst, frame_size, src_frame_offset, dst_frame_offset, node_size, src_node_offset, dst_node_offset); return; } // 他は必要なときに足す BB_ASSERT(0); } // ------------------------------------- // シリアライズ // ------------------------------------- protected: void DumpObjectData(std::ostream &os) const override { // バージョン std::int64_t ver = 1; bb::SaveValue(os, ver); // 親クラス _super::DumpObjectData(os); // メンバ bb::SaveValue(os, m_data_type); bb::SaveValue(os, m_frame_size); bb::SaveValue(os, m_frame_stride); bb::SaveValue(os, m_node_shape); m_tensor.DumpObject(os); } void LoadObjectData(std::istream &is) override { // バージョン std::int64_t ver; bb::LoadValue(is, ver); BB_ASSERT(ver == 1); // 親クラス _super::LoadObjectData(is); // メンバ bb::LoadValue(is, m_data_type); bb::LoadValue(is, m_frame_size); bb::LoadValue(is, m_frame_stride); bb::LoadValue(is, m_node_shape); m_tensor.LoadObject(is); // 再構築 m_node_size = CalcShapeSize(m_node_shape); } // ------------------------------------- // Serialize(旧) // ------------------------------------- public: void Save(std::ostream &os) const { os.write((char const *)&m_data_type, sizeof(m_data_type)); SaveIndex(os, m_frame_size); SaveIndex(os, m_frame_stride); SaveIndex(os, m_node_size); SaveIndices(os, m_node_shape); m_tensor.Save(os); } void Load(std::istream &is) { is.read((char *)&m_data_type, sizeof(m_data_type)); m_frame_size = LoadIndex(is); m_frame_stride = LoadIndex(is); m_node_size = LoadIndex(is); m_node_shape = LoadIndices(is); m_tensor.Load(is); } void Save(std::string filename) const { std::ofstream ofs(filename, std::ios::binary); Save(ofs); } void Load(std::string filename) { std::ifstream ifs(filename, std::ios::binary); Load(ifs); } #ifdef BB_WITH_CEREAL template <class Archive> void serialize(Archive& archive, std::uint32_t const version) { archive(cereal::make_nvp("data_type", m_data_type)); archive(cereal::make_nvp("frame_size", m_frame_size)); archive(cereal::make_nvp("frame_stride", m_frame_stride)); archive(cereal::make_nvp("node_size", m_node_size)); archive(cereal::make_nvp("node_shape", m_node_shape)); archive(cereal::make_nvp("tensor", m_tensor)); } #endif // ------------------------------------- // Resize // ------------------------------------- /* void Resize(index_t frame_size, index_t i0, int type) { Resize(frame_size, indices_t({i0}), type); } void Resize(index_t frame_size, index_t i0, index_t i1, int type) { Resize(frame_size, indices_t({i0, i1}), type); } void Resize(index_t frame_size, index_t i0, index_t i1, index_t i2, int type) { Resize(frame_size, indices_t({i0, i1, i2}), type); } void Resize(index_t frame_size, index_t i0, index_t i1, index_t i2, index_t i3, int type) { Resize(frame_size, indices_t({i0, i1, i2, i3}), type); } */ void Reshape(std::vector<index_t> shape) { index_t auto_index = -1; index_t total = 1; for (std::intptr_t i = (std::intptr_t)shape.size()-1; i >= 0;--i) { if (shape[i] < 0) { auto_index = i; } else { total *= shape[i]; } } if (auto_index >= 0) { shape[(std::size_t)auto_index] = m_node_size / total; } // 再計算 total = 1; for (auto size : shape) { total *= size; } BB_ASSERT(total == m_node_size); m_node_shape = shape; std::vector<index_t> tensor_shape; for ( auto size : shape ) { tensor_shape.push_back(size); } tensor_shape.push_back(-1); m_tensor.Reshape(tensor_shape); } std::vector<index_t> GetShape(void) const { return m_node_shape; } /** * @brief 内容のゼロ埋め * @detail 内容のゼロ埋め */ void FillZero(void) { m_tensor.FillZero(); } void Fill(double value) { m_tensor = value; } int GetType(void) const { return m_data_type; } index_t GetFrameSize(void) const { return m_frame_size; } index_t GetNodeSize(void) const { return m_node_size; } // debug inline bool IsValidValue(void) const { return m_tensor.IsValidValue(); } // debug template <typename Tp> inline bool IsZero(void) const { for (index_t frame = 0; frame < GetFrameSize(); ++frame ) { for (index_t node = 0; node < GetNodeSize(); ++node ) { if ( GetValue<Tp>(frame, node) != 0 ) { return false; } } } return true; } // --------------------------------- // ダイレクトアクセス用 // --------------------------------- index_t GetFrameStride(void) const { return m_frame_stride; } Memory::Ptr LockMemory(bool new_buf=false) const { return m_tensor.LockMemory(new_buf); } Memory::ConstPtr LockMemoryConst(void) const { return m_tensor.LockMemoryConst(); } Memory::DevPtr LockDeviceMemory(bool new_buf=false) const { return m_tensor.LockDeviceMemory(new_buf); } Memory::DevConstPtr LockDeviceMemoryConst(void) const { return m_tensor.LockDeviceMemoryConst(); } // 型指定アクセス template <typename MemTp, typename ValueTp> inline ValueTp Get(void const *addr, index_t frame, index_t node) const { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemoryConst(); return static_cast<ValueTp>(DataType_Read<MemTp>(GetNodeBaseAddr(addr, node), frame)); } template <typename MemTp, typename ValueTp> inline ValueTp Get(void const *addr, index_t frame, std::vector<index_t> const & indices) { return Get<MemTp, ValueTp>(addr, frame, GetNodeIndex(indices)); } template <typename MemTp, typename ValueTp> inline void Set(void *addr, index_t frame, index_t node, ValueTp value) { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemory(); DataType_Write<MemTp>(GetNodeBaseAddr(addr, node), frame, static_cast<MemTp>(value)); } template <typename MemTp, typename ValueTp> inline void Set(void *addr, index_t frame, std::vector<index_t> const & indices, ValueTp value) { Set<MemTp, ValueTp>(addr, frame, GetNodeIndex(indices), value); } template <typename MemTp, typename ValueTp> inline void Add(void *addr, index_t frame, index_t node, ValueTp value) { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemory(); DataType_Add<MemTp>(GetNodeBaseAddr(addr, node), frame, static_cast<MemTp>(value)); } template <typename MemTp, typename ValueTp> inline void Add(void *addr, index_t frame, std::vector<index_t> const & indices, ValueTp value) { Add<MemTp, ValueTp>(addr, frame, GetNodeIndex(indices), value); } // 汎用アクセス template <typename Tp> inline Tp GetValue(void const *addr, index_t frame, index_t node) { return ReadValue<Tp>(GetNodeBaseAddr(addr, node), frame); } template <typename Tp> inline Tp GetValue(void const *addr, index_t frame, std::vector<index_t> const & indices) { return GetValue<Tp>(addr, frame, GetNodeIndex(indices)); } template <typename Tp> inline void SetValue(void *addr, index_t frame, index_t node, Tp value) { WriteValue<Tp>(GetNodeBaseAddr(addr, node), frame, value); } template <typename Tp> inline void SetValue(void *addr, index_t frame, std::vector<index_t> const & indices, Tp value) { SetValue<Tp>(addr, frame, GetNodeIndex(indices), value); } template <typename Tp> inline void AddValue(void *addr, index_t frame, index_t node, Tp value) { AddValue<Tp>(GetNodeBaseAddr(addr, node), frame, value); } template <typename Tp> inline void AddValue(void *addr, index_t frame, std::vector<index_t> const & indices, Tp value) { AddValue<Tp>(addr, frame, GetNodeIndex(indices), value); } protected: template <typename DT, typename ST> FrameBuffer ConvertTo__(void) { BB_ASSERT(GetType() == DataType<ST>::type); FrameBuffer dst_buf(GetFrameSize(), GetShape(), DataType<DT>::type); #ifdef BB_WITH_CUDA if ( DataType<ST>::type == BB_TYPE_BIT && DataType<DT>::type == BB_TYPE_FP32 && this->IsDeviceAvailable() && dst_buf.IsDeviceAvailable() ) { auto src_ptr = this->LockDeviceMemoryConst(); auto dst_ptr = dst_buf.LockDeviceMemory(true); bbcu_ConvBitToReal<float>( (int const *)src_ptr.GetAddr(), (float *)dst_ptr.GetAddr(), -1.0f, +1.0f, (int)this->GetNodeSize(), (int)this->GetFrameSize(), (int)(this->GetFrameStride() / sizeof(int)), (int)(dst_buf.GetFrameStride() / sizeof(float)) ); return dst_buf; } #endif auto src_ptr = this->LockConst<ST>(); auto dst_ptr = dst_buf.Lock<DT>(); #pragma omp parallel for for (index_t node = 0; node < m_node_size; ++node) { for (index_t frame = 0; frame < m_frame_size; ++frame) { dst_ptr.Set(frame, node, (DT)src_ptr.Get(frame, node)); } } return dst_buf; } template <typename ST> FrameBuffer ConvertTo_(int type) { switch (type) { case BB_TYPE_BIT: return ConvertTo__<Bit, ST>(); case BB_TYPE_FP32: return ConvertTo__<float, ST>(); case BB_TYPE_FP64: return ConvertTo__<double, ST>(); case BB_TYPE_INT8: return ConvertTo__<std::int8_t, ST>(); case BB_TYPE_INT16: return ConvertTo__<std::int16_t, ST>(); case BB_TYPE_INT32: return ConvertTo__<std::int32_t, ST>(); case BB_TYPE_INT64: return ConvertTo__<std::int64_t, ST>(); case BB_TYPE_UINT8: return ConvertTo__<std::int8_t, ST>(); case BB_TYPE_UINT16: return ConvertTo__<std::int16_t, ST>(); case BB_TYPE_UINT32: return ConvertTo__<std::int32_t, ST>(); case BB_TYPE_UINT64: return ConvertTo__<std::int64_t, ST>(); default: BB_ASSERT(0); } return FrameBuffer(); } public: FrameBuffer ConvertTo(int type) { switch (m_data_type) { case BB_TYPE_BIT: return ConvertTo_<Bit>(type); case BB_TYPE_FP32: return ConvertTo_<float>(type); case BB_TYPE_FP64: return ConvertTo_<double>(type); case BB_TYPE_INT8: return ConvertTo_<std::int8_t >(type); case BB_TYPE_INT16: return ConvertTo_<std::int16_t>(type); case BB_TYPE_INT32: return ConvertTo_<std::int32_t>(type); case BB_TYPE_INT64: return ConvertTo_<std::int64_t>(type); case BB_TYPE_UINT8: return ConvertTo_<std::int8_t>(type); case BB_TYPE_UINT16: return ConvertTo_<std::int16_t>(type); case BB_TYPE_UINT32: return ConvertTo_<std::int32_t>(type); case BB_TYPE_UINT64: return ConvertTo_<std::int64_t>(type); default: BB_ASSERT(0); } return FrameBuffer(); } protected: // --------------------------------- // アクセス用 // --------------------------------- void *GetNodeBaseAddr(void* base_addr, index_t node) const { BB_DEBUG_ASSERT(node < m_node_size); auto addr = (std::uint8_t*)base_addr; return addr + (m_frame_stride * node); } void const *GetNodeBaseAddr(const void* base_addr, index_t node) const { BB_DEBUG_ASSERT(node < m_node_size); auto addr = (std::uint8_t const *)base_addr; return addr + (m_frame_stride * node); } inline index_t GetNodeIndex(std::vector<index_t> const & indices) const { BB_DEBUG_ASSERT(indices.size() == m_node_shape.size()); index_t stride = 1; index_t index = 0; for ( std::intptr_t i = (std::intptr_t)m_node_shape.size()-1; i>= 0; --i ) { BB_DEBUG_ASSERT(indices[i] >= 0 && indices[i] < m_node_shape[i]); index += stride * indices[i]; stride *= m_node_shape[i]; } return index; } template<typename Tp> Tp ReadValue(void *base, index_t frame) const { switch (m_data_type) { case BB_TYPE_BIT: return static_cast<Tp>(DataType_Read<Bit> (base, frame)); break; case BB_TYPE_FP32: return static_cast<Tp>(DataType_Read<float> (base, frame)); break; case BB_TYPE_FP64: return static_cast<Tp>(DataType_Read<double> (base, frame)); break; case BB_TYPE_INT8: return static_cast<Tp>(DataType_Read<std::int8_t> (base, frame)); break; case BB_TYPE_INT16: return static_cast<Tp>(DataType_Read<std::int16_t>(base, frame)); break; case BB_TYPE_INT32: return static_cast<Tp>(DataType_Read<std::int32_t>(base, frame)); break; case BB_TYPE_INT64: return static_cast<Tp>(DataType_Read<std::int64_t>(base, frame)); break; case BB_TYPE_UINT8: return static_cast<Tp>(DataType_Read<std::int8_t> (base, frame)); break; case BB_TYPE_UINT16: return static_cast<Tp>(DataType_Read<std::int16_t>(base, frame)); break; case BB_TYPE_UINT32: return static_cast<Tp>(DataType_Read<std::int32_t>(base, frame)); break; case BB_TYPE_UINT64: return static_cast<Tp>(DataType_Read<std::int64_t>(base, frame)); break; default: BB_ASSERT(0); } return 0; } template<typename Tp> void WriteValue(void *base, index_t frame, Tp value) const { switch (m_data_type) { case BB_TYPE_BIT: DataType_Write<Bit> (base, frame, static_cast<Bit> (value)); break; case BB_TYPE_FP32: DataType_Write<float> (base, frame, static_cast<float> (value)); break; case BB_TYPE_FP64: DataType_Write<double> (base, frame, static_cast<double> (value)); break; case BB_TYPE_INT8: DataType_Write<std::int8_t> (base, frame, static_cast<int8_t> (value)); break; case BB_TYPE_INT16: DataType_Write<std::int16_t>(base, frame, static_cast<int16_t> (value)); break; case BB_TYPE_INT32: DataType_Write<std::int32_t>(base, frame, static_cast<int32_t> (value)); break; case BB_TYPE_INT64: DataType_Write<std::int64_t>(base, frame, static_cast<int64_t> (value)); break; case BB_TYPE_UINT8: DataType_Write<std::int8_t> (base, frame, static_cast<uint8_t> (value)); break; case BB_TYPE_UINT16: DataType_Write<std::int16_t>(base, frame, static_cast<uint16_t>(value)); break; case BB_TYPE_UINT32: DataType_Write<std::int32_t>(base, frame, static_cast<uint32_t>(value)); break; case BB_TYPE_UINT64: DataType_Write<std::int64_t>(base, frame, static_cast<uint64_t>(value)); break; default: BB_ASSERT(0); } } template<typename Tp> void AddValue(void *base, index_t frame, Tp value) const { switch (m_data_type) { case BB_TYPE_BIT: DataType_Add<Bit> (base, frame, static_cast<Bit> (value)); break; case BB_TYPE_FP32: DataType_Add<float> (base, frame, static_cast<float> (value)); break; case BB_TYPE_FP64: DataType_Add<double> (base, frame, static_cast<double> (value)); break; case BB_TYPE_INT8: DataType_Add<std::int8_t> (base, frame, static_cast<int8_t> (value)); break; case BB_TYPE_INT16: DataType_Add<std::int16_t>(base, frame, static_cast<int16_t> (value)); break; case BB_TYPE_INT32: DataType_Add<std::int32_t>(base, frame, static_cast<int32_t> (value)); break; case BB_TYPE_INT64: DataType_Add<std::int64_t>(base, frame, static_cast<int64_t> (value)); break; case BB_TYPE_UINT8: DataType_Add<std::int8_t> (base, frame, static_cast<uint8_t> (value)); break; case BB_TYPE_UINT16: DataType_Add<std::int16_t>(base, frame, static_cast<uint16_t>(value)); break; case BB_TYPE_UINT32: DataType_Add<std::int32_t>(base, frame, static_cast<uint32_t>(value)); break; case BB_TYPE_UINT64: DataType_Add<std::int64_t>(base, frame, static_cast<uint64_t>(value)); break; default: BB_ASSERT(0); } } public: friend FrameBufferConstPtr_<Bit const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<float const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<double const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<int8_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<int16_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<int32_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<int64_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<uint8_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<uint16_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<uint32_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<uint64_t const, FrameBuffer const, Memory::ConstPtr>; friend FrameBufferConstPtr_<Bit , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<float , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<double , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<int8_t , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<int16_t , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<int32_t , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<int64_t , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<uint8_t , FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<uint16_t, FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<uint32_t, FrameBuffer, Memory::Ptr>; friend FrameBufferConstPtr_<uint64_t, FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<Bit , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<float , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<double , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<int8_t , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<int16_t , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<int32_t , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<int64_t , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<uint8_t , FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<uint16_t, FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<uint32_t, FrameBuffer, Memory::Ptr>; friend FrameBufferPtr_<uint64_t, FrameBuffer, Memory::Ptr>; template <typename Tp> auto LockConst(void) const { FrameBufferConstPtr_<Tp const, FrameBuffer const, Memory::ConstPtr> ptr(this); ptr.Lock(); return ptr; } template <typename Tp> auto Lock(bool new_buf=false) { FrameBufferPtr_<Tp, FrameBuffer, Memory::Ptr> ptr(this); ptr.Lock(new_buf); return ptr; } public: // 型指定アクセス template <typename MemTp, typename ValueTp> inline ValueTp Get(index_t frame, index_t node) const { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemoryConst(); return static_cast<ValueTp>(DataType_Read<MemTp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame)); } template <typename MemTp, typename ValueTp> inline ValueTp Get(index_t frame, std::vector<index_t> const & indices) { return Get<MemTp, ValueTp>(frame, GetNodeIndex(indices)); } template <typename MemTp, typename ValueTp> inline void Set(index_t frame, index_t node, ValueTp value) { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemory(); DataType_Write<MemTp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame, static_cast<MemTp>(value)); } template <typename MemTp, typename ValueTp> inline void Set(index_t frame, std::vector<index_t> const & indices, ValueTp value) { Set<MemTp, ValueTp>(frame, GetNodeIndex(indices), value); } template <typename MemTp, typename ValueTp> inline void Add(index_t frame, index_t node, ValueTp value) { BB_DEBUG_ASSERT(m_data_type == DataType<MemTp>::type); auto ptr = LockMemory(); DataType_Add<MemTp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame, static_cast<MemTp>(value)); } template <typename MemTp, typename ValueTp> inline void Add(index_t frame, std::vector<index_t> const & indices, ValueTp value) { Add<MemTp, ValueTp>(frame, GetNodeIndex(indices), value); } // 汎用アクセス template <typename Tp> inline Tp GetValue(index_t frame, index_t node) const { auto ptr = LockMemory(); return ReadValue<Tp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame); } template <typename Tp> inline Tp GetValue(index_t frame, std::vector<index_t> const & indices) const { return GetValue<Tp>(frame, GetNodeIndex(indices)); } template <typename Tp> inline void SetValue(index_t frame, index_t node, Tp value) { auto ptr = LockMemory(); WriteValue<Tp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame, value); } template <typename Tp> inline void SetValue(index_t frame, std::vector<index_t> const & indices, Tp value) { SetValue<Tp>(frame, GetNodeIndex(indices), value); } template <typename Tp> inline void AddValue(index_t frame, index_t node, Tp value) { auto ptr = LockMemory(); AddValue<Tp>(GetNodeBaseAddr(ptr.GetAddr(), node), frame, value); } template <typename Tp> inline void AddValue(index_t frame, std::vector<index_t> const & indices, Tp value) { AddValue<Tp>(frame, GetNodeIndex(indices), value); } inline void SetBit (index_t frame, index_t node, Bit value) { SetValue<Bit >(frame, node, value); } inline void SetFP32 (index_t frame, index_t node, float value) { SetValue<float >(frame, node, value); } inline void SetFP64 (index_t frame, index_t node, double value) { SetValue<double >(frame, node, value); } inline void SetINT8 (index_t frame, index_t node, std::int8_t value) { SetValue<std::int8_t >(frame, node, value); } inline void SetINT16 (index_t frame, index_t node, std::int16_t value) { SetValue<std::int16_t >(frame, node, value); } inline void SetINT32 (index_t frame, index_t node, std::int32_t value) { SetValue<std::int32_t >(frame, node, value); } inline void SetINT64 (index_t frame, index_t node, std::int64_t value) { SetValue<std::int64_t >(frame, node, value); } inline void SetUINT8 (index_t frame, index_t node, std::uint8_t value) { SetValue<std::uint8_t >(frame, node, value); } inline void SetUINT16(index_t frame, index_t node, std::uint16_t value) { SetValue<std::uint16_t>(frame, node, value); } inline void SetUINT32(index_t frame, index_t node, std::uint32_t value) { SetValue<std::uint32_t>(frame, node, value); } inline void SetUINT64(index_t frame, index_t node, std::uint64_t value) { SetValue<std::uint64_t>(frame, node, value); } inline void SetBit (index_t frame, std::vector<index_t> const & indices, Bit value) { SetValue<Bit >(frame, indices, value); } inline void SetFP32 (index_t frame, std::vector<index_t> const & indices, float value) { SetValue<float >(frame, indices, value); } inline void SetFP64 (index_t frame, std::vector<index_t> const & indices, double value) { SetValue<double >(frame, indices, value); } inline void SetINT8 (index_t frame, std::vector<index_t> const & indices, std::int8_t value) { SetValue<std::int8_t >(frame, indices, value); } inline void SetINT16 (index_t frame, std::vector<index_t> const & indices, std::int16_t value) { SetValue<std::int16_t >(frame, indices, value); } inline void SetINT32 (index_t frame, std::vector<index_t> const & indices, std::int32_t value) { SetValue<std::int32_t >(frame, indices, value); } inline void SetINT64 (index_t frame, std::vector<index_t> const & indices, std::int64_t value) { SetValue<std::int64_t >(frame, indices, value); } inline void SetUINT8 (index_t frame, std::vector<index_t> const & indices, std::uint8_t value) { SetValue<std::uint8_t >(frame, indices, value); } inline void SetUINT16(index_t frame, std::vector<index_t> const & indices, std::uint16_t value) { SetValue<std::uint16_t>(frame, indices, value); } inline void SetUINT32(index_t frame, std::vector<index_t> const & indices, std::uint32_t value) { SetValue<std::uint32_t>(frame, indices, value); } inline void SetUINT64(index_t frame, std::vector<index_t> const & indices, std::uint64_t value) { SetValue<std::uint64_t>(frame, indices, value); } inline Bit GetBit (index_t frame, index_t node) const { return GetValue<Bit >(frame, node); } inline float GetFP32 (index_t frame, index_t node) const { return GetValue<float >(frame, node); } inline double GetFP64 (index_t frame, index_t node) const { return GetValue<double >(frame, node); } inline std::int8_t GetINT8 (index_t frame, index_t node) const { return GetValue<std::int8_t >(frame, node); } inline std::int16_t GetINT16 (index_t frame, index_t node) const { return GetValue<std::int16_t >(frame, node); } inline std::int32_t GetINT32 (index_t frame, index_t node) const { return GetValue<std::int32_t >(frame, node); } inline std::int64_t GetINT64 (index_t frame, index_t node) const { return GetValue<std::int64_t >(frame, node); } inline std::uint8_t GetUINT8 (index_t frame, index_t node) const { return GetValue<std::uint8_t >(frame, node); } inline std::uint16_t GetUINT16(index_t frame, index_t node) const { return GetValue<std::uint16_t>(frame, node); } inline std::uint32_t GetUINT32(index_t frame, index_t node) const { return GetValue<std::uint32_t>(frame, node); } inline std::uint64_t GetUINT64(index_t frame, index_t node) const { return GetValue<std::uint64_t>(frame, node); } inline Bit GetBit (index_t frame, std::vector<index_t> const & indices) { return GetValue<Bit >(frame, indices); } inline float GetFP32 (index_t frame, std::vector<index_t> const & indices) { return GetValue<float >(frame, indices); } inline double GetFP64 (index_t frame, std::vector<index_t> const & indices) { return GetValue<double >(frame, indices); } inline std::int8_t GetINT8 (index_t frame, std::vector<index_t> const & indices) { return GetValue<std::int8_t >(frame, indices); } inline std::int16_t GetINT16 (index_t frame, std::vector<index_t> const & indices) { return GetValue<std::int16_t >(frame, indices); } inline std::int32_t GetINT32 (index_t frame, std::vector<index_t> const & indices) { return GetValue<std::int32_t >(frame, indices); } inline std::int64_t GetINT64 (index_t frame, std::vector<index_t> const & indices) { return GetValue<std::int64_t >(frame, indices); } inline std::uint8_t GetUINT8 (index_t frame, std::vector<index_t> const & indices) { return GetValue<std::uint8_t >(frame, indices); } inline std::uint16_t GetUINT16(index_t frame, std::vector<index_t> const & indices) { return GetValue<std::uint16_t>(frame, indices); } inline std::uint32_t GetUINT32(index_t frame, std::vector<index_t> const & indices) { return GetValue<std::uint32_t>(frame, indices); } inline std::uint64_t GetUINT64(index_t frame, std::vector<index_t> const & indices) { return GetValue<std::uint64_t>(frame, indices); } template<typename Tp> void SetVector(index_t frame, std::vector<Tp> const &data) { BB_ASSERT(data.size() == (size_t)m_node_size); BB_ASSERT(frame >= 0 && frame < m_frame_size); for (index_t node = 0; node < m_node_size; ++node) { SetValue<Tp>(frame, node, data[node]); } } template<typename Tp> void SetVector(std::vector< std::vector<Tp> > const &data) { BB_ASSERT(data.size() == (size_t)m_frame_size); for (index_t frame = 0; frame < m_frame_size; ++frame) { BB_ASSERT(data[frame].size() == (size_t)m_node_size); for (index_t node = 0; node < m_node_size; ++node) { SetValue<Tp>(frame, node, data[frame][node]); } } } template<typename Tp> void SetVector(std::vector< std::vector<Tp> > const &data, index_t offset) { BB_ASSERT(GetType() == DataType<Tp>::type); BB_ASSERT(offset + m_frame_size <= (index_t)data.size() ); auto ptr = Lock<Tp>(); for (index_t frame = 0; frame < m_frame_size; ++frame) { BB_ASSERT(data[(size_t)frame].size() == (size_t)m_node_size); for (index_t node = 0; node < m_node_size; ++node) { ptr.Set(frame, node, data[(size_t)(frame + offset)][(size_t)node]); } } } template<typename Tp> std::vector<Tp> GetVector(index_t frame) const { BB_ASSERT(frame >= 0 && frame < m_frame_size); std::vector<Tp> data(m_node_size); for (index_t node = 0; node < m_node_size; ++node) { data[node] = GetValue<Tp>(frame, node); } return data; } template<typename BufType, typename VecType=float> void SetData_(std::vector< std::vector<VecType> > const &data, index_t offset=0) { BB_ASSERT(GetType() == DataType<BufType>::type); BB_ASSERT(offset + (index_t)data.size() <= m_frame_size); index_t size = (index_t)data.size(); if ( size + offset > m_frame_size ) { size = m_frame_size - offset; } auto ptr = Lock<BufType>(); for (index_t i = 0; i < size; ++i) { index_t frame = i + offset; BB_ASSERT(data[i].size() == (size_t)m_node_size); for (index_t node = 0; node < m_node_size; ++node) { ptr.Set(frame, node, (BufType)data[i][node]); } } } template<typename BufType, typename VecType=float> std::vector< std::vector<VecType> > GetData_(index_t size=0, index_t offset=0) { if ( size <= 0 ) { size = m_frame_size - offset; } BB_ASSERT(GetType() == DataType<BufType>::type); BB_ASSERT(offset + size <= m_frame_size); std::vector< std::vector<VecType> > data(size); auto ptr = LockConst<BufType>(); for (index_t i = 0; i < size; ++i) { data[i].resize(m_node_size); index_t frame = i + offset; for (index_t node = 0; node < m_node_size; ++node) { data[i][node] = (VecType)ptr.Get(frame, node); } } return data; } template<typename VecType=float> void SetData(std::vector< std::vector<VecType> > const &data, index_t offset=0) { switch (GetType()) { case BB_TYPE_BIT: SetData_<bb::Bit, VecType>(data, offset); break; case BB_TYPE_FP32: SetData_<float, VecType>(data, offset); break; case BB_TYPE_FP64: SetData_<double, VecType>(data, offset); break; case BB_TYPE_INT8: SetData_<std::int8_t, VecType>(data, offset); break; case BB_TYPE_INT16: SetData_<std::int16_t, VecType>(data, offset); break; case BB_TYPE_INT32: SetData_<std::int32_t, VecType>(data, offset); break; case BB_TYPE_INT64: SetData_<std::int64_t, VecType>(data, offset); break; case BB_TYPE_UINT8: SetData_<std::uint8_t, VecType>(data, offset); break; case BB_TYPE_UINT16: SetData_<std::uint16_t, VecType>(data, offset); break; case BB_TYPE_UINT32: SetData_<std::uint32_t, VecType>(data, offset); break; case BB_TYPE_UINT64: SetData_<std::uint64_t, VecType>(data, offset); break; default: BB_ASSERT(0); } } template<typename VecType=float> std::vector< std::vector<VecType> > GetData(index_t size=0, index_t offset=0) { switch (GetType()) { case BB_TYPE_BIT: return GetData_<bb::Bit, VecType>(size, offset); case BB_TYPE_FP32: return GetData_<float, VecType>(size, offset); case BB_TYPE_FP64: return GetData_<double, VecType>(size, offset); case BB_TYPE_INT8: return GetData_<std::int8_t, VecType>(size, offset); case BB_TYPE_INT16: return GetData_<std::int16_t, VecType>(size, offset); case BB_TYPE_INT32: return GetData_<std::int32_t, VecType>(size, offset); case BB_TYPE_INT64: return GetData_<std::int64_t, VecType>(size, offset); case BB_TYPE_UINT8: return GetData_<std::uint8_t, VecType>(size, offset); case BB_TYPE_UINT16: return GetData_<std::uint16_t, VecType>(size, offset); case BB_TYPE_UINT32: return GetData_<std::uint32_t, VecType>(size, offset); case BB_TYPE_UINT64: return GetData_<std::uint64_t, VecType>(size, offset); default: BB_ASSERT(0); } return std::vector< std::vector<VecType> >(); } // テンソルの設定 public: /* template<typename Tp> void SetTensor(index_t frame, Tensor const &tensor) { BB_ASSERT(m_data_type == DataType<Tp>::type); BB_ASSERT(tensor.GetType() == DataType<Tp>::type); BB_ASSERT(tensor.GetShape() == m_tensor.GetShape()); int dim = tensor.GetDim(); indices_t indices(tensor.GetDim(), 0); for ( ; ; ) { // m_tensor.template At<Tp>(indices) = tensor.template At<Tp>(indices); int i = 0; for ( ; ; ) { indices[i]++; if ( indices[i] < m_node_shape[i] ) { break; } indices[i] = 0; i++; if (i >= dim) { return; } } } } */ // フレームの部分切り出し FrameBuffer FrameRange(index_t size, index_t offset=0) { BB_ASSERT(offset >= 0 && offset < m_frame_size); BB_ASSERT(size >= 0 && size < m_frame_size - offset); FrameBuffer buf(size, m_node_shape, m_data_type); auto src_ptr = m_tensor.LockMemoryConst(); auto dst_ptr = buf.m_tensor.LockMemory(true); auto src_addr = (std::int8_t const *)src_ptr.GetAddr(); auto dst_addr = (std::int8_t *)dst_ptr.GetAddr(); if (m_data_type == BB_TYPE_BIT && (offset % 8) != 0 ) { #pragma omp parallel for for (index_t node = 0; node < m_node_size; ++node) { for (index_t frame = 0; frame < size; ++frame) { auto val = DataType_Read<Bit>(src_addr + m_frame_stride * node, frame + offset); DataType_Write<Bit>(dst_addr + m_frame_stride * node, frame, val); } } } else { int unit = DataType_GetBitSize(m_data_type); index_t byte_offset = (offset * unit + 7) / 8; index_t byte_size = (size * unit + 7) / 8; #pragma omp parallel for for (index_t node = 0; node < m_node_size; ++node) { memcpy(dst_addr + buf.m_frame_stride * node, src_addr + m_frame_stride * node + byte_offset, (std::size_t)byte_size); } } return buf; } FrameBuffer Range(index_t size, index_t offset=0) { BB_ASSERT(offset >= 0 && offset < m_node_size); BB_ASSERT(size >= 0 && size < m_node_size - offset); FrameBuffer buf(m_frame_size, {size}, m_data_type); auto src_ptr = m_tensor.LockMemoryConst(); auto dst_ptr = buf.m_tensor.LockMemory(true); auto src_addr = (std::int8_t const *)src_ptr.GetAddr(); auto dst_addr = (std::int8_t *)dst_ptr.GetAddr(); index_t stride_size = GetFrameStride(); memcpy(dst_addr, src_addr + (m_frame_stride * offset), (std::size_t)(stride_size * size)); return buf; } FrameBuffer Concatenate(FrameBuffer const& buf) { BB_ASSERT(buf.GetType() == GetType()); BB_ASSERT(buf.m_frame_size == m_frame_size); BB_ASSERT(buf.m_frame_stride == m_frame_stride); FrameBuffer dst_buf(m_frame_size, {m_node_size + buf.m_node_size}, m_data_type); auto dst_ptr = dst_buf.m_tensor.LockMemory(true); auto dst_addr = (std::int8_t *)dst_ptr.GetAddr(); { auto src0_ptr = m_tensor.LockMemoryConst(); auto src0_addr = (std::int8_t const *)src0_ptr.GetAddr(); memcpy(dst_addr, src0_addr, (std::size_t)(m_frame_stride * m_node_size)); dst_addr += m_frame_stride * m_node_size; } { auto src1_ptr = buf.m_tensor.LockMemoryConst(); auto src1_addr = (std::int8_t const *)src1_ptr.GetAddr(); memcpy(dst_addr, src1_addr, (std::size_t)(buf.m_frame_stride * buf.m_node_size)); } return dst_buf; } // ------------------------------------- // 演算 // ------------------------------------- protected: template<typename T> bool _IsNan(void) { #ifdef BB_WITH_CUDA if ( this->IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { Tensor_<int> result(1); { auto ptr_buf = this->LockDeviceMemoryConst(); auto ptr_result = result.LockDeviceMemory(true); bbcu_FrameBuf_IsnNan ( (int *)ptr_result.GetAddr(), (T const *)ptr_buf.GetAddr(), (int )this->GetNodeSize(), (int )this->GetFrameSize(), (int )(this->GetFrameStride() / sizeof(T)) ); } { auto dst_ptr = result.LockConst(); return dst_ptr(0) != 0; } } #endif auto ptr = LockConst<T>(); for ( index_t node = 0; node < GetNodeSize(); ++node ) { for ( index_t frame = 0; frame < GetFrameSize(); ++frame ) { if ( std::isnan(ptr.Get(frame, node)) ) { return true; } } } return false; } template<typename T> double _Min(void) { T value = std::numeric_limits<T>::max(); auto ptr = LockConst<T>(); for ( index_t node = 0; node < GetNodeSize(); ++node ) { for ( index_t frame = 0; frame < GetFrameSize(); ++frame ) { value = std::min(value, ptr.Get(frame, node)); } } return (double)value; } template<typename T> double _MinFp(void) { #ifdef BB_WITH_CUDA if ( this->IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { Tensor_<T> result(1); { auto ptr_buf = this->LockDeviceMemoryConst(); auto ptr_result = result.LockDeviceMemory(true); bbcu_FrameBuf_Min<T> ( (T *)ptr_result.GetAddr(), (T const *)ptr_buf.GetAddr(), (int )this->GetNodeSize(), (int )this->GetFrameSize(), (int )(this->GetFrameStride() / sizeof(T)) ); } { auto dst_ptr = result.LockConst(); return (double)dst_ptr(0); } } #endif return _Min<T>(); } template<typename T> double _Max(void) { T value = std::numeric_limits<T>::lowest(); auto ptr = LockConst<T>(); for ( index_t node = 0; node < GetNodeSize(); ++node ) { for ( index_t frame = 0; frame < GetFrameSize(); ++frame ) { value = std::max(value, ptr.Get(frame, node)); } } return (double)value; } template<typename T> double _MaxFp(void) { #ifdef BB_WITH_CUDA if ( this->IsDeviceAvailable() && Manager::IsDeviceAvailable() ) { Tensor_<T> result(1); { auto ptr_buf = this->LockDeviceMemoryConst(); auto ptr_result = result.LockDeviceMemory(true); bbcu_FrameBuf_Max<T> ( (T *)ptr_result.GetAddr(), (T const *)ptr_buf.GetAddr(), (int )this->GetNodeSize(), (int )this->GetFrameSize(), (int )(this->GetFrameStride() / sizeof(T)) ); } { auto dst_ptr = result.LockConst(); return (double)dst_ptr(0); } } #endif return _Max<T>(); } public: inline FrameBuffer& operator=(double src) { m_tensor = src; return *this; } inline FrameBuffer& operator+=(FrameBuffer src) { m_tensor += src.m_tensor; return *this; } inline FrameBuffer& operator+=(double src) { m_tensor += src; return *this; } inline FrameBuffer& operator-=(FrameBuffer src) { m_tensor -= src.m_tensor; return *this; } inline FrameBuffer& operator-=(double src) { m_tensor -= src; return *this; } inline FrameBuffer& operator*=(FrameBuffer src) { m_tensor *= src.m_tensor; return *this; } inline FrameBuffer& operator*=(double src) { m_tensor *= src; return *this; } inline FrameBuffer& operator/=(FrameBuffer src) { m_tensor /= src.m_tensor; return *this; } inline FrameBuffer& operator/=(double src) { m_tensor /= src; return *this; } bool IsNan(void) { switch ( GetType() ) { case BB_TYPE_FP32: return _IsNan<float>(); case BB_TYPE_FP64: return _IsNan<double>(); } return false; } double Min(void) { switch ( GetType() ) { case BB_TYPE_FP32: return _MinFp<float >(); case BB_TYPE_FP64: return _MinFp<double>(); case BB_TYPE_BIT: return _Min<Bit >(); case BB_TYPE_INT8: return _Min<int8_t >(); case BB_TYPE_INT16: return _Min<int16_t >(); case BB_TYPE_INT32: return _Min<int32_t >(); case BB_TYPE_INT64: return _Min<int64_t >(); case BB_TYPE_UINT8: return _Min<uint8_t >(); case BB_TYPE_UINT16: return _Min<uint16_t>(); case BB_TYPE_UINT32: return _Min<uint32_t>(); case BB_TYPE_UINT64: return _Min<uint64_t>(); default: BB_ASSERT(0); } return 0; } double Max(void) { switch ( GetType() ) { case BB_TYPE_FP32: return _MaxFp<float >(); case BB_TYPE_FP64: return _MaxFp<double>(); case BB_TYPE_BIT: return _Max<Bit >(); case BB_TYPE_INT8: return _Max<int8_t >(); case BB_TYPE_INT16: return _Max<int16_t >(); case BB_TYPE_INT32: return _Max<int32_t >(); case BB_TYPE_INT64: return _Max<int64_t >(); case BB_TYPE_UINT8: return _Max<uint8_t >(); case BB_TYPE_UINT16: return _Max<uint16_t>(); case BB_TYPE_UINT32: return _Max<uint32_t>(); case BB_TYPE_UINT64: return _Max<uint64_t>(); default: BB_ASSERT(0); } return 0; } FrameBuffer Sqrt(void) { FrameBuffer dst(GetFrameSize(), GetShape(), GetType(), IsHostOnly()); dst.m_tensor = m_tensor.Sqrt(); return dst; } FrameBuffer Exp(void) { FrameBuffer dst(GetFrameSize(), GetShape(), GetType(), IsHostOnly()); dst.m_tensor = m_tensor.Exp(); return dst; } double Sum(void) { return m_tensor.Sum(); } double Norm(void) { return std::sqrt((*this * *this).Sum()); } friend FrameBuffer operator+(FrameBuffer const &src0, FrameBuffer const &src1); friend FrameBuffer operator+(FrameBuffer const &src0, double src1); friend FrameBuffer operator+(double src0, FrameBuffer const &src1); friend FrameBuffer operator-(FrameBuffer const &src0, FrameBuffer const &src1); friend FrameBuffer operator-(FrameBuffer const &src0, double src1); friend FrameBuffer operator-(double src0, FrameBuffer const &src1); friend FrameBuffer operator*(FrameBuffer const &src0, FrameBuffer const &src1); friend FrameBuffer operator*(FrameBuffer const &src0, double src1); friend FrameBuffer operator*(double src0, FrameBuffer const &src1); friend FrameBuffer operator/(FrameBuffer const &src0, FrameBuffer const &src1); friend FrameBuffer operator/(FrameBuffer const &src0, double src1); friend FrameBuffer operator/(double src0, FrameBuffer const &src1); friend FrameBuffer Sqrt(FrameBuffer const &src); friend FrameBuffer Exp(FrameBuffer const &src); }; inline FrameBuffer operator+(FrameBuffer const &src0, FrameBuffer const &src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor + src1.m_tensor; return dst; } inline FrameBuffer operator+(FrameBuffer const &src0, double src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor + src1; return dst; } inline FrameBuffer operator+(double src0, FrameBuffer const &src1) { FrameBuffer dst(src1.GetFrameSize(), src1.GetShape(), src1.GetType(), src1.IsHostOnly()); dst.m_tensor = src0 + src1.m_tensor; return dst; } inline FrameBuffer operator-(FrameBuffer const &src0, FrameBuffer const &src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor - src1.m_tensor; return dst; } inline FrameBuffer operator-(FrameBuffer const &src0, double src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor - src1; return dst; } inline FrameBuffer operator-(double src0, FrameBuffer const &src1) { FrameBuffer dst(src1.GetFrameSize(), src1.GetShape(), src1.GetType(), src1.IsHostOnly()); dst.m_tensor = src0 - src1.m_tensor; return dst; } inline FrameBuffer operator*(FrameBuffer const &src0, FrameBuffer const &src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor * src1.m_tensor; return dst; } inline FrameBuffer operator*(FrameBuffer const &src0, double src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor * src1; return dst; } inline FrameBuffer operator*(double src0, FrameBuffer const &src1) { FrameBuffer dst(src1.GetFrameSize(), src1.GetShape(), src1.GetType(), src1.IsHostOnly()); dst.m_tensor = src0 * src1.m_tensor; return dst; } inline FrameBuffer operator/(FrameBuffer const &src0, FrameBuffer const &src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor / src1.m_tensor; return dst; } inline FrameBuffer operator/(FrameBuffer const &src0, double src1) { FrameBuffer dst(src0.GetFrameSize(), src0.GetShape(), src0.GetType(), src0.IsHostOnly()); dst.m_tensor = src0.m_tensor / src1; return dst; } inline FrameBuffer operator/(double src0, FrameBuffer const &src1) { FrameBuffer dst(src1.GetFrameSize(), src1.GetShape(), src1.GetType(), src1.IsHostOnly()); dst.m_tensor = src0 / src1.m_tensor; return dst; } inline FrameBuffer Sqrt(FrameBuffer const &src) { FrameBuffer dst(src.GetFrameSize(), src.GetShape(), src.GetType(), src.IsHostOnly()); dst.m_tensor = Sqrt(src.m_tensor); return dst; } inline FrameBuffer Exp(FrameBuffer const &src) { FrameBuffer dst(src.GetFrameSize(), src.GetShape(), src.GetType(), src.IsHostOnly()); dst.m_tensor = Exp(src.m_tensor); return dst; } template<typename T> std::ostream &operator<<(std::ostream& os, FrameBufferConstPtr_<T const, FrameBuffer const, Memory::ConstPtr> ptr) { os << "[\n"; for ( index_t frame = 0; frame < ptr.GetFrameBuffer().GetFrameSize(); ++frame ) { os << " ["; for ( index_t node = 0; node < ptr.GetFrameBuffer().GetNodeSize(); ++node ) { os << ptr.Get(frame, node) << ", "; if ( node % 16 == 15 ) { os << "\n"; } } os << "]\n"; } os << "]\n"; return os; } inline std::ostream& operator<<(std::ostream& os, FrameBuffer const &buf) { switch (buf.GetType()) { case BB_TYPE_BIT: return os << buf.LockConst<Bit >(); case BB_TYPE_FP32: return os << buf.LockConst<float >(); case BB_TYPE_FP64: return os << buf.LockConst<double >(); case BB_TYPE_INT8: return os << buf.LockConst<int8_t >(); case BB_TYPE_INT16: return os << buf.LockConst<int16_t >(); case BB_TYPE_INT32: return os << buf.LockConst<int32_t >(); case BB_TYPE_INT64: return os << buf.LockConst<int64_t >(); case BB_TYPE_UINT8: return os << buf.LockConst<uint8_t >(); case BB_TYPE_UINT16: return os << buf.LockConst<uint16_t>(); case BB_TYPE_UINT32: return os << buf.LockConst<uint32_t>(); case BB_TYPE_UINT64: return os << buf.LockConst<uint64_t>(); default: BB_ASSERT(0); } return os; } }
contact_utilities.h
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // #if !defined(KRATOS_CONTACT_UTILITIES) #define KRATOS_CONTACT_UTILITIES // System includes // External includes // Project includes #include "utilities/openmp_utils.h" #include "utilities/math_utils.h" #include "contact_structural_mechanics_application_variables.h" #include "includes/model_part.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ /** * @class ContactUtilities * @ingroup ContactStructuralMechanicsApplication * @brief This class includes some utilities used for contact computations * @author Vicente Mataix Ferrandiz */ class ContactUtilities { public: ///@name Type Definitions ///@{ /// Pointer definition of MortarUtilities KRATOS_CLASS_POINTER_DEFINITION( ContactUtilities ); // Some geometrical definitions typedef Node<3> NodeType; typedef Point::CoordinatesArrayType CoordinatesArrayType; /// Definition of geometries typedef Geometry<NodeType> GeometryType; /// The containers of the components of the model parts typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ConditionsContainerType ConditionsArrayType; /// Index type definition typedef std::size_t IndexType; /// Size type definition typedef std::size_t SizeType; ///@} ///@name Life Cycle ///@{ ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ ///@} ///@name Operations ///@{ /** * @brief This function computes the relative size of the mesh * @param rModelPart The modelpart to compute */ static inline double CalculateRelativeSizeMesh(ModelPart& rModelPart) { return CalculateMaxNodalH(rModelPart)/CalculateMinimalNodalH(rModelPart); } /** * @brief This method computes the maximal nodal H * @param rModelPart The modelpart to compute */ static inline double CalculateMaxNodalH(ModelPart& rModelPart) { // We iterate over the nodes NodesArrayType& r_nodes_array = rModelPart.Nodes(); const auto it_node_begin = r_nodes_array.begin(); // // Creating the max auxiliar value // double max_value = 0.0; // // #pragma omp parallel for reduction(max:max_value) // for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { // auto it_node = it_node_begin + i; // KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(NODAL_H)) << "ERROR:: NODAL_H not added" << std::endl; // max_value = std::max(max_value, it_node->FastGetSolutionStepValue(NODAL_H)); // } // // return max_value; // Creating a buffer for parallel vector fill const int num_threads = OpenMPUtils::GetNumThreads(); std::vector<double> max_vector(num_threads, 0.0); double nodal_h; #pragma omp parallel for private(nodal_h) for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(NODAL_H)) << "ERROR:: NODAL_H not added" << std::endl; nodal_h = it_node->FastGetSolutionStepValue(NODAL_H); const int id = OpenMPUtils::ThisThread(); if (nodal_h > max_vector[id]) max_vector[id] = nodal_h; } return *std::max_element(max_vector.begin(), max_vector.end()); } /** * @brief This method computes the mean nodal H * @param rModelPart The modelpart to compute */ static inline double CalculateMeanNodalH(ModelPart& rModelPart) { // We iterate over the nodes NodesArrayType& r_nodes_array = rModelPart.Nodes(); const auto it_node_begin = r_nodes_array.begin(); // Creating the sum auxiliar value double sum_nodal_h = 0.0; #pragma omp parallel for reduction(+:sum_nodal_h) for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(NODAL_H)) << "ERROR:: NODAL_H not added" << std::endl; sum_nodal_h += it_node->FastGetSolutionStepValue(NODAL_H);; } return sum_nodal_h/static_cast<double>(r_nodes_array.size()); } /** * @brief This method computes the minimal nodal H * @param rModelPart The modelpart to compute */ static inline double CalculateMinimalNodalH(ModelPart& rModelPart) { // We iterate over the nodes NodesArrayType& r_nodes_array = rModelPart.Nodes(); const auto it_node_begin = r_nodes_array.begin(); // // Creating the min auxiliar value // double min_value = 0.0; // // #pragma omp parallel for reduction(min:min_value) // for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { // auto it_node = it_node_begin + i; // KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(NODAL_H)) << "ERROR:: NODAL_H not added" << std::endl; // min_value = std::min(min_value, it_node->FastGetSolutionStepValue(NODAL_H)); // } // // return min_value; // Creating a buffer for parallel vector fill const int num_threads = OpenMPUtils::GetNumThreads(); std::vector<double> min_vector(num_threads, 0.0); double nodal_h; #pragma omp parallel for private(nodal_h) for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; KRATOS_DEBUG_ERROR_IF_NOT(it_node->SolutionStepsDataHas(NODAL_H)) << "ERROR:: NODAL_H not added" << std::endl; nodal_h = it_node->FastGetSolutionStepValue(NODAL_H); const int id = OpenMPUtils::ThisThread(); if (nodal_h > min_vector[id]) min_vector[id] = nodal_h; } return *std::min_element(min_vector.begin(), min_vector.end()); } /** * @brief This function scales the points according to a factor (to increase the bounding box) * @param rPointToScale The point to scale * @param rNormal The normal of the point * @param LengthSearch The factor considered to "grow" the node */ template<class TPointType> static inline void ScaleNode( TPointType& rPointToScale, const array_1d<double, 3>& rNormal, const double LengthSearch ) { noalias(rPointToScale.Coordinates()) = rPointToScale.Coordinates() + rNormal * LengthSearch; } /** * @brief Calculates the distance between nodes * @param rPointOrigin The first node * @param rPointDestiny The second node */ static inline double DistancePoints( const GeometryType::CoordinatesArrayType& rPointOrigin, const GeometryType::CoordinatesArrayType& rPointDestiny ) { return std::sqrt((rPointOrigin[0] - rPointDestiny[0]) * (rPointOrigin[0] - rPointDestiny[0]) + (rPointOrigin[1] - rPointDestiny[1]) * (rPointOrigin[1] - rPointDestiny[1]) + (rPointOrigin[2] - rPointDestiny[2]) * (rPointOrigin[2] - rPointDestiny[2])); } /** * @brief It calculates the center updated in u_n+1 or u_n+1/2 * @param rModelPart The modelpart to update * @param DeltaTime The increment of time considered * @param HalfJump If the jumpt is just half dt */ static inline void ComputeStepJump( ModelPart& rModelPart, const double DeltaTime, const bool HalfJump = true ) { // Time constants const double velocity_constant = HalfJump ? 0.25 : 0.5; const double acceleration_constant = HalfJump ? 0.125 : 0.5; // Iterate over the nodes NodesArrayType& r_nodes_array = rModelPart.Nodes(); // Node iterator const auto it_node_begin = r_nodes_array.begin(); // We compute the half jump array_1d<double, 3> new_delta_disp; #pragma omp parallel for firstprivate(new_delta_disp) for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; const array_1d<double, 3>& r_current_velocity = it_node->FastGetSolutionStepValue(VELOCITY); const array_1d<double, 3>& r_previous_velocity = it_node->FastGetSolutionStepValue(VELOCITY, 1); const array_1d<double, 3>& r_previous_acceleration = it_node->FastGetSolutionStepValue(ACCELERATION, 1); noalias(new_delta_disp) = velocity_constant * DeltaTime * (r_current_velocity + r_previous_velocity) + acceleration_constant * std::pow(DeltaTime, 2) * r_previous_acceleration; if (it_node->IsFixed(DISPLACEMENT_X)) new_delta_disp[0] = 0.0; if (it_node->IsFixed(DISPLACEMENT_Y)) new_delta_disp[1] = 0.0; if (it_node->IsFixed(DISPLACEMENT_Z)) new_delta_disp[2] = 0.0; it_node->SetValue(DELTA_COORDINATES, new_delta_disp); } } /** * @brief It checks the activity of the current contact simulation * @param rModelPart The modelpart to check the activity * @param ThrowError If an error is thrown */ static inline bool CheckActivity( ModelPart& rModelPart, const bool ThrowError = true ) { // Iterate over the nodes NodesArrayType& r_nodes_array = rModelPart.Nodes(); // Node iterator const auto it_node_begin = r_nodes_array.begin(); // We compute the half jump IndexType aux_check = 0; #pragma omp parallel for reduction(+:aux_check) for(int i = 0; i < static_cast<int>(r_nodes_array.size()); ++i) { auto it_node = it_node_begin + i; if (it_node->Is(SLAVE)) { if (it_node->Is(ACTIVE)) { aux_check += 1; } } } const bool is_active = aux_check == 0 ? false : true; KRATOS_ERROR_IF(ThrowError && !is_active) << "CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl; return is_active; } /** * @brief It computes the explicit contributions of the conditions * @param rModelPart The modelpart to update */ static inline void ComputeExplicitContributionConditions(ModelPart& rModelPart) { ConditionsArrayType& r_conditions_array = rModelPart.Conditions(); KRATOS_TRACE_IF("Empty model part", r_conditions_array.size() == 0) << "YOUR COMPUTING CONTACT MODEL PART IS EMPTY" << std::endl; const auto it_cond_begin = r_conditions_array.begin(); ProcessInfo& r_process_info = rModelPart.GetProcessInfo(); #pragma omp parallel for for(int i = 0; i < static_cast<int>(r_conditions_array.size()); ++i) { auto it_cond = it_cond_begin + i; it_cond->AddExplicitContribution(r_process_info); } } /** * @brief It activates the conditions with active nodes * @param rModelPart The modelpart to check */ static inline void ActivateConditionWithActiveNodes(ModelPart& rModelPart) { ConditionsArrayType& r_conditions_array = rModelPart.Conditions(); KRATOS_TRACE_IF("Empty model part", r_conditions_array.size() == 0) << "YOUR COMPUTING CONTACT MODEL PART IS EMPTY" << std::endl; const auto it_cond_begin = r_conditions_array.begin(); bool is_active = false; #pragma omp parallel for firstprivate(is_active) for(int i = 0; i < static_cast<int>(r_conditions_array.size()); ++i) { auto it_cond = it_cond_begin + i; GeometryType& r_geometry = it_cond->GetGeometry(); if (r_geometry.NumberOfGeometryParts() > 0) { GeometryType& r_parent_geometry = r_geometry.GetGeometryPart(0); is_active = false; for ( IndexType i_node = 0; i_node < r_parent_geometry.size(); ++i_node ) { if (r_parent_geometry[i_node].Is(ACTIVE)) { is_active = true; break; } } it_cond->Set(ACTIVE, is_active); } } } /** * @brief It calculates the center updated in u_n+1/2 * @param rThisGeometry The geometry to calculate * @return point: The center in u_n+1/2 (Newmark) */ static inline array_1d<double, 3> GetHalfJumpCenter(GeometryType& rThisGeometry) { array_1d<double, 3> center = (rThisGeometry.Center()).Coordinates(); // Initialize variables Vector N; GeometryType::CoordinatesArrayType local_point; // Get shape functions rThisGeometry.PointLocalCoordinates( local_point, center ); rThisGeometry.ShapeFunctionsValues( N, local_point ); KRATOS_DEBUG_ERROR_IF_NOT(rThisGeometry[0].Has(DELTA_COORDINATES)) << "Please call ComputeStepJump() first" << std::endl; const Vector new_delta_disp_center = prod(trans(GetVariableMatrix(rThisGeometry, DELTA_COORDINATES)), N); for (IndexType i = 0; i < new_delta_disp_center.size(); ++i) center[i] += new_delta_disp_center[i]; return center; } /** * @brief It calculates the matrix containing the tangent vector of the r_gt (for frictional contact) * @param rGeometry The geometry to calculate * @param StepSlip The considered step slip * @return tangent_matrix The matrix containing the tangent vectors of the r_gt */ template< std::size_t TDim, std::size_t TNumNodes> static inline BoundedMatrix<double, TNumNodes, TDim> ComputeTangentMatrixSlip( const GeometryType& rGeometry, const std::size_t StepSlip = 1 ) { /* DEFINITIONS */ // Zero tolerance const double zero_tolerance = std::numeric_limits<double>::epsilon(); // Tangent matrix BoundedMatrix<double, TNumNodes, TDim> tangent_matrix; for (IndexType i_node = 0; i_node < TNumNodes; ++i_node) { const array_1d<double, 3>& r_gt = rGeometry[i_node].FastGetSolutionStepValue(WEIGHTED_SLIP, StepSlip); const double norm_slip = norm_2(r_gt); if (norm_slip > zero_tolerance) { // Non zero r_gt const array_1d<double, 3> tangent_slip = r_gt/norm_slip; for (std::size_t i_dof = 0; i_dof < TDim; ++i_dof) tangent_matrix(i_node, i_dof) = tangent_slip[i_dof]; } else { // We consider the tangent direction as auxiliar const array_1d<double, 3>& r_normal = rGeometry[i_node].FastGetSolutionStepValue(NORMAL); array_1d<double, 3> tangent_xi, tangent_eta; MathUtils<double>::OrthonormalBasis(r_normal, tangent_xi, tangent_eta); if (TDim == 3) { for (std::size_t i_dof = 0; i_dof < 3; ++i_dof) tangent_matrix(i_node, i_dof) = tangent_xi[i_dof]; } else { if (std::abs(tangent_xi[2]) > std::numeric_limits<double>::epsilon()) { for (std::size_t i_dof = 0; i_dof < 2; ++i_dof) tangent_matrix(i_node, i_dof) = tangent_eta[i_dof]; } else { for (std::size_t i_dof = 0; i_dof < 2; ++i_dof) tangent_matrix(i_node, i_dof) = tangent_xi[i_dof]; } } } } return tangent_matrix; } private: /** * @brief It calculates the matrix of a variable of a geometry * @param rNodes The geometry to calculate * @param rVarName The name of the variable to calculate * @return var_matrix: The matrix containing the variables of the geometry */ static inline Matrix GetVariableMatrix( const GeometryType& rNodes, const Variable<array_1d<double,3> >& rVarName ) { /* DEFINITIONS */ const SizeType num_nodes = rNodes.size(); const SizeType dim = rNodes.WorkingSpaceDimension(); Matrix var_matrix(num_nodes, dim); for (IndexType i_node = 0; i_node < num_nodes; i_node++) { const array_1d<double, 3> value = rNodes[i_node].GetValue(rVarName); for (IndexType i_dof = 0; i_dof < dim; i_dof++) var_matrix(i_node, i_dof) = value[i_dof]; } return var_matrix; } };// class ContactUtilities } #endif /* KRATOS_CONTACT_UTILITIES defined */
omp_parallel_for_firstprivate.c
<ompts:test> <ompts:testdescription>Test which checks the omp parallel for firstprivate directive.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp parallel for firstprivate</ompts:directive> <ompts:dependences>omp parallel for reduction,omp parallel for private</ompts:dependences> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_parallel_for_firstprivate</ompts:testcode:functionname>(FILE * logFile) { <ompts:orphan:vars> int sum ; int i2; int i; </ompts:orphan:vars> sum=0; i2=3; int known_sum; #pragma omp parallel for reduction(+:sum) private(i) <ompts:check>firstprivate(i2)</ompts:check><ompts:crosscheck>private(i2)</ompts:crosscheck> <ompts:orphan> for (i = 1; i <= LOOPCOUNT; i++) { sum = sum + (i + i2); } /*end of for*/ </ompts:orphan> known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2 + i2 * LOOPCOUNT; return (known_sum == sum); } /* end of check_parallel_for_fistprivate */ </ompts:testcode> </ompts:test>
declare_simd_aarch64_complex.c
// REQUIRES: aarch64-registered-target // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +neon -fopenmp -x c -std=c11 -emit-llvm %s -o - -femit-all-decls | FileCheck %s // RUN: %clang_cc1 -triple aarch64-linux-gnu -target-feature +sve -fopenmp -x c -std=c11 -emit-llvm %s -o - -femit-all-decls | FileCheck %s --check-prefix=SVE #pragma omp declare simd #pragma omp declare simd simdlen(4) notinbranch double _Complex double_complex(double _Complex); // CHECK: "_ZGVnM2v_double_complex" "_ZGVnN2v_double_complex" "_ZGVnN4v_double_complex" // CHECK-NOT: double_complex // SVE: "_ZGVsM4v_double_complex" "_ZGVsMxv_double_complex" // SVE-NOT: double_complex #pragma omp declare simd #pragma omp declare simd simdlen(8) notinbranch float _Complex float_complex(float _Complex); // CHECK: "_ZGVnM2v_float_complex" "_ZGVnN2v_float_complex" "_ZGVnN8v_float_complex" // CHECK-NOT: float_complex // SVE: "_ZGVsM8v_float_complex" "_ZGVsMxv_float_complex" // SVE-NOT: float_complex static double _Complex *DC; static float _Complex *DF; void call_the_complex_functions() { double_complex(*DC); float_complex(*DF); }
wgs64.c
#include <stdio.h> #include <omp.h> int n =64; int main(void) { int fail = 0; int a = -1; // #if 1 #pragma omp target { //nothing } #endif #pragma omp target teams distribute thread_limit(64) for (int k =0; k < n; k++) { // nothing } #pragma omp target teams distribute parallel for thread_limit(64) for (int k =0; k < n; k++) { // nothing } printf("Succeeded\n"); return fail; }
26_omp_heap.c
// clang-format off // RUN: %run %s --omp 2>&1 | %filecheck %s --check-prefix=CHECK-TSAN // RUN: %run %s --omp 2>&1 | %filecheck %s // REQUIRES: openmp && softcounter // clang-format on #include <stdlib.h> void repeat_alloc_free(unsigned n) { for (int i = 0; i < n; i++) { double* d = (double*)malloc(sizeof(double) * n); free(d); } } int main(int argc, char** argv) { const int n = 1000; // CHECK: [Trace] TypeART Runtime Trace #pragma omp parallel sections { #pragma omp section repeat_alloc_free(n); #pragma omp section repeat_alloc_free(n); #pragma omp section repeat_alloc_free(n); } // CHECK-TSAN-NOT: ThreadSanitizer // CHECK-NOT: Error // CHECK: Allocation type detail (heap, stack, global) // CHECK: 6 : 3000 , 0 , 0 , double // CHECK: Free allocation type detail (heap, stack) // CHECK: 6 : 3000 , 0 , double return 0; }