source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
truecrypt_fmt_plug.c | /* TrueCrypt volume support to John The Ripper
*
* Written by Alain Espinosa <alainesp at gmail.com> in 2012. 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) 2012 Alain Espinosa and it is hereby released to the
* general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*
* (This is a heavily cut-down "BSD license".)
*
* Updated in Dec, 2014 by JimF. This is a ugly format, and was converted
* into a more standard (using crypt_all) format. The PKCS5_PBKDF2_HMAC can
* be replaced with faster pbkdf2_xxxx functions (possibly with SIMD usage).
* this has been done for sha512. ripemd160 and Whirlpool pbkdf2 header
* files have been created. Also, proper decrypt is now done, (in cmp_exact)
* and we test against the 'TRUE' signature, and against 2 crc32's which
* are computed over the 448 bytes of decrypted data. So we now have a
* full 96 bits of hash. There will be no way we get false positives from
* this slow format. EVP_AES_XTS removed. Also, we now only pbkdf2 over
* 64 bytes of data (all that is needed for the 2 AES keys), and that sped
* up the crypts A LOT (~3x faster)
*
*/
#include "arch.h"
#if FMT_EXTERNS_H
extern struct fmt_main fmt_truecrypt;
extern struct fmt_main fmt_truecrypt_ripemd160;
extern struct fmt_main fmt_truecrypt_sha512;
extern struct fmt_main fmt_truecrypt_whirlpool;
#elif FMT_REGISTERS_H
john_register_one(&fmt_truecrypt);
john_register_one(&fmt_truecrypt_ripemd160);
john_register_one(&fmt_truecrypt_sha512);
john_register_one(&fmt_truecrypt_whirlpool);
#else
#include "aes_xts.h"
#include <string.h>
#include "misc.h"
#include "memory.h"
#include "common.h"
#include "formats.h"
#include "crc32.h"
#include "johnswap.h"
#define PBKDF2_HMAC_SHA512_ALSO_INCLUDE_CTX
#include "pbkdf2_hmac_sha512.h"
#include "pbkdf2_hmac_ripemd160.h"
#include "pbkdf2_hmac_whirlpool.h"
#ifdef _OPENMP
#include <omp.h>
#ifndef OMP_SCALE
#ifdef __MIC__
#define OMP_SCALE 4
#else
#define OMP_SCALE 1
#endif // __MIC__
#endif // OMP_SCALE
#endif // _OPENMP
#include "memdbg.h"
/* 64 is the actual maximum used by Truecrypt software as of version 7.1a */
#define PLAINTEXT_LENGTH 64
#define MAX_CIPHERTEXT_LENGTH (512*2+32)
#define SALT_SIZE sizeof(struct cust_salt)
#define SALT_ALIGN 4
#define BINARY_SIZE 0
#define BINARY_ALIGN 1
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
static unsigned char (*key_buffer)[PLAINTEXT_LENGTH + 1];
static unsigned char (*first_block_dec)[16];
#define TAG_WHIRLPOOL "truecrypt_WHIRLPOOL$"
#define TAG_SHA512 "truecrypt_SHA_512$"
#define TAG_RIPEMD160 "truecrypt_RIPEMD_160$"
#define TAG_WHIRLPOOL_LEN (sizeof(TAG_WHIRLPOOL)-1)
#define TAG_SHA512_LEN (sizeof(TAG_SHA512)-1)
#define TAG_RIPEMD160_LEN (sizeof(TAG_RIPEMD160)-1)
#define IS_SHA512 1
#define IS_RIPEMD160 2
#define IS_WHIRLPOOL 3
// borrowed from https://github.com/bwalex/tc-play
#define MAX_PASSSZ 64
#define PASS_BUFSZ 256
#define KPOOL_SZ 64
#define MAX_KFILE_SZ 1048576 /* 1 MB */
#define MAX_KEYFILES 256
// keyfile(s) data
unsigned char (*keyfiles_data)[MAX_KFILE_SZ];
int (*keyfiles_length);
struct cust_salt {
unsigned char salt[64];
// I 'thought' that bin[] could be removed, so that only salt[] was used
// for salt dupe-removal. That was wrong, bin[] must also be part of the
// salt dupe logic, or we will get wrong passwords found, if there is
// hashes with the same salts. bin[] array really is part of the salt
// since we decrypt it, to do the final check. So there is no real way
// to have any duplicate salts. in essense, we have a 'fixed' binary
// and the salt is the entire input hash. The fixed binary can be
// thought of as 'TRUE' (but it is more than this). It is simply we
// do not know the real binary until after we correctly decrypt.
// Initially I moved bin[] and ported to dyna_salt. All hashes in a
// test suite cracked, BUT the same password was used for all of them,
// the first password in the file. Not what we wanted.
unsigned char bin[512-64];
int loop_inc;
int num_iterations;
int hash_type;
int nkeyfiles;
} *psalt;
static struct fmt_tests tests_ripemd160[] = {
{"truecrypt_RIPEMD_160$b9f118f89d2699cbe42cad7bc2c61b0822b3d6e57e8d43e79f55666aa30572676c3aced5f0900af223e9fcdf43ac39637640977f546eb714475f8e2dbf5368bfb80a671d7796d4a88c36594acd07081b7ef0fbead3d3a0ff2b295e9488a5a2747ed97905436c28c636f408b36b0898aad3c4e9566182bd55f80e97a55ad9cf20899599fb775f314067c9f7e6153b9544bfbcffb53eef5a34b515e38f186a2ddcc7cd3aed635a1fb4aab98b82d57341ec6ae52ad72e43f41aa251717082d0858bf2ccc69a7ca00daceb5b325841d70bb2216e1f0d4dc936b9f50ebf92dbe2abec9bc3babea7a4357fa74a7b2bcce542044552bbc0135ae35568526e9bd2afde0fa4969d6dc680cf96f7d82ec0a75b6170c94e3f2b6fd98f2e6f01db08ce63f1b6bcf5ea380ed6f927a5a8ced7995d83ea8e9c49238e8523d63d6b669ae0d165b94f1e19b49922b4748798129eed9aa2dae0d2798adabf35dc4cc30b25851a3469a9ee0877775abca26374a4176f8d237f8191fcc870f413ffdbfa73ee22790a548025c4fcafd40f631508f1f6c8d4c847e409c839d21ff146f469feff87198bc184db4b5c5a77f3402f491538503f68e0116dac76344b762627ad678de76cb768779f8f1c35338dd9f72dcc1ac337319b0e21551b9feb85f8cac67a2f35f305a39037bf96cd61869bf1761abcce644598dad254990d17f0faa4965926acb75abf", "password" },
{"truecrypt_RIPEMD_160$6ab053e5ebee8c56bce5705fb1e03bf8cf99e2930232e525befe1e45063aa2e30981585020a967a1c45520543847cdb281557e16c81cea9d329b666e232eeb008dbe3e1f1a181f69f073f0f314bc17e255d42aaa1dbab92231a4fb62d100f6930bae4ccf6726680554dea3e2419fb67230c186f6af2c8b4525eb8ebb73d957b01b8a124b736e45f94160266bcfaeda16b351ec750d980250ebb76672578e9e3a104dde89611bce6ee32179f35073be9f1dee8da002559c6fab292ff3af657cf5a0d864a7844235aeac441afe55f69e51c7a7c06f7330a1c8babae2e6476e3a1d6fb3d4eb63694218e53e0483659aad21f20a70817b86ce56c2b27bae3017727ff26866a00e75f37e6c8091a28582bd202f30a5790f5a90792de010aebc0ed81e9743d00518419f32ce73a8d3f07e55830845fe21c64a8a748cbdca0c3bf512a4938e68a311004538619b65873880f13b2a9486f1292d5c77116509a64eb0a1bba7307f97d42e7cfa36d2b58b71393e04e7e3e328a7728197b8bcdef14cf3f7708cd233c58031c695da5f6b671cc5066323cc86bb3c6311535ad223a44abd4eec9077d70ab0f257de5706a3ff5c15e3bc2bde6496a8414bc6a5ed84fe9462b65efa866312e0699e47338e879ae512a66f3f36fc086d2595bbcff2e744dd1ec283ba8e91299e62e4b2392608dd950ede0c1f3d5b317b2870ead59efe096c054ea1", "123" },
{NULL}
};
static struct fmt_tests tests_sha512[] = {
{"truecrypt_SHA_512$aa582afe64197a3cfd4faf7697673e5e14414369da3f716400414f63f75447da7d3abdc65a25ea511b1772d67370d6c349d8000de66d65861403093fecfb85719e1d46158d24324e5a2c0ee598214b1b2e7eac761dbde8cb85bcb33f293df7f30c9e44a3fa97bf1c70e9986677855873fa2435d9154ccaed8f28d68f16b10adcce7032d7c1742d322739d02c05457859abdaa176faa95c674d2a1092c30832dd2afd9a319599b4d1db92ffe6e48b3b29e566d5c51af091839699f5ad1715730fef24e94e39a6f40770b8320e30bf972d810b588af88ce3450337adbec0a10255b20230bcfca93aa5a0a6592cd6038312181c0792c59ec9e5d95a6216497d39ae28131869b89368e82371718970bf9750a7114c83d87b1b0cd16b6e8d41c4925d15ec26107e92847ec1bb73363ca10f3ad62afa8b0f95ff13cdbe217a1e8a74508ef439ed2140b26d5538b8d011a0d1e469f2a6962e56964adc75b90d9c6a16e88ad0adb59a337f8abb3f9d76f7f9acad22853e9dbbce13a4f686c6a802243b0901972af3c6928511609ac7b957b352452c4347acd563a72faa86a46522942fdc57f32d48c5148a2bb0bc2c3dbc9851385f816f2ece958957082c0a8fe69f647be675d87fcb8244912abc277a3242ee17e1d522f85598417559cb3a9f60b755e5b613069cb54c05a4c5d2fbd3ca6ba793320aeb0e109f8b21852daf2d9ed74dd9", "password"},
{"truecrypt_SHA_512$73f6b08614dc4ffbd77d27a0815b0700d6b612f573ccd6c8937e8d154321e3c1c1c67dd348d4d3bc8304e94a3a6ec0c672de8396a9a6b26b12393195b7daa4225a9d3a134229be011f8179791bb00c31b5c132c8dbad5a6f8738487477c409b3c32d90b07be8d7a3a9faa95d37ab6faccc459d47f029e25adcea48cee83eaa35b7acc3f849717000421d92ac46e6f16ec3dccacd3ffae76a48280977d2a6727027d9d6ff9c4c98405359ee382f6dd1eca0d7007cbe804b81485c1085e74b58d3eb1e3c7ebdc1e1ab1384e4440ab6ca7beed7e0ef7d1e0da5ffc3cd89f7b6ac8a9257ee369d397ac1e112f75382ddbe6f7317ec20c46cb7b2111d0d91570e90b4c01a0b8205fcdf4d0cadcf4a067b8f285a541f1d649894fb3ade29a2ee0575524455d489c299dde215bea3254f7d43aa4e4011a39bdb6e7473bc29f588e659fdbf065cc4a336ba42f2b6c07479cf3e544978150fb013da7db22afcb4f8384e39e2edfa30a4cbe5e84a07c54ba66663bb9284836cc5a8ba7489d3f7f92aec6d9f4e264c90c2af6181082bd273197bc42c325cb1de31006dd55425e3f210d2ddd7973978eec865d3226bb1e30a9897146d90d79a73070e87f0182981ea85f15f948ae1958af7704fabecd6f07e20be70be9f9c38a5c5e5c8b17be648f011b2c40f62d6ac51de932add5bdb47bb428fd510b004a7aa79321b03ed7aa202be439fbf", "password" },
{"truecrypt_SHA_512$cfd9e5757da139b32d117cd60f86f649400615dc218981106dfadd44598599a7ec0ace42de61506fe8d81b5c885861cdb26e0c38cb9adfcff27ba88872220ccd0914d4fa44bab5a708fe6864e0f665ac71d87e7e97b3724d610cf1f6ec09fa99da40126f63868654fed3381eaa8176f689e8e292c3cb68e43601d5804bc2e19d86722c21d42204e158b26b720e7b8f7580edce15469195dd7ed711b0fcb6c8abc253d0fd93cc784d5279de527fbdcfb357780635a5c363b773b55957d7efb472f6e6012489a9f0d225573446e5251cfb277a1365eed787e0da52f02d835667d74cc41fa4002cc35ad1ce276fbf9d73d6553ac0f8ab6961901d292a66df814a2cbda1b41f29aeec88ed15e7d37fe84ac5306b5a1b8d2e1f2c132e5c7d40ca7bb76d4ff87980ca4d75eaac5066b3ed50b53259554b9f922f7cee8e91847359d06e448da02cbeeecc78ca9bee2899a33dfa04a478ca131d33c64d6de5f81b219f11bed6ff3c0d56f26b3a27c79e7c55b6f76567a612166ce71028e3d3ae7e5abd25faec5e2e9dc30719baa2c138e26d6f8e3799a72b5e7b1c2a07c12cea452073b72f6e429bb17dd23fe3934c9e406bb4060083f92aa100c2e82ca40664f65c02cbc800c5696659f8df84db17edb92de5d4f1ca9e5fe71844e1e8c4f8b19ce7362fb3ca5467bf65122067c53f011648a6663894b315e6c5c635bec5bd39da028041", "123" },
/* test vector with single keyfile, with data "1234567" */
{NULL}
};
static struct fmt_tests tests_whirlpool[] = {
{"truecrypt_WHIRLPOOL$5724ba89229d705010ec56af416b16155682a0cab9cf48ac5a5fdd2086c9a251ae4bbea6cfb8464321a789852f7812095b0e0c4c4f9c6d14ba7beedaf3484b375ac7bc97b43c3e74bf1a0c259b7ac8725d990d2ff31935ca3443f2ce8df59de86515da3e0f53f728882b71c5cc704df0c87c282a7413db446e9a2e516a144311dd25092eb0a2c5df0240d899708289fc7141abd8538fa5791d9f96c39129cce9fe8a6e58e84364e2f4acc32274147431cb2d2480b1b54bffee485acee0925852b8a6ee71d275f028b92e540be595448e5f1d78560a3b8ad209962dd5981d7ca98db9a678a588a9296157d44502cd78f9e32f022dddc9bc8111b5704ee39a9b56d30b89898ae340e90f2e6c73be6ac64de97e32fc2eed0b66dcd5c1553eeab3950cf851624a5a4439435a6fd5717fda6d5f939f4a902321341964c16bda8975752ba150fb9d858d8eaff2a2086cb50d30abff741ee20223b4223b1783f0ed537a609a081afed952395ef0b5de6883db66cbb5a8bac70f2f757c7b6e6bb5d863672820f0d3d61b262b2b6c2ca0dc8e7137851aa450da1c1d915e005bff0e849a89bf67693ef97f5c17bf8d07a18c562dc783274f9ec580f9519a6dd1429b66160ddb04549506ad616dd0695da144fa2ad270eac7163983e9036f1bde3c7634b8a246b8dcd518ce3e12b881c838fbce59a0cfdffa3b21447e3f28124f63549c3962", "password" },
{"truecrypt_WHIRLPOOL$0650595770851981d70b088ff6ef4bf90573e08d03c8cac8b2dfded22e1653f5c45103758c68be344fdccae42b4683087da083a3841b92fb79856798eaee793c04cd95ae556d9616684da17e47bd2f775d8128f94b80b781e4cab4921b12c620721cf719ca72d3997cea829fd29b429282b597d5719c13423cdf7bd717fa12a56b8eddcf7b1ad2796c4ad078ab3a9bd944a694aa4b0078ed160440dd3db13dd1d04a7aaaa4dc016a95bd1cfafcd833ae933c627bf5512ae55c76069af7190823dba0133d6fe02e4421d3684ff2a2493da990a3cc5eed40a9e8c48c7a89a2f47030d45c324a3d78b941e772e24b285af6739ae1f5953ff838edaa69e79939f55d0fe00cd0e3a20a46db3a232009eabc800711342f7e580ba909f16c2039d4900fd4025845a385641a6037ceb6420fe7d37868e8c06e6146eddec9e6cb97e71048da5fa5898dac08152516ea1c6729e85d31596cd226aa218ce693989efb9fa8b05404bcc2debbc75c429a03fe31bfc49f10d595b898436ff6b02fc01d745b91280f26ae94a4969ce7f86c12e6b562c7b5377e3fb3247a8cda11a930c2a9e80f24966925de01afad5987ebee9c3de1d41667c6dc35cebbbc963f263c700d06a647ab7020385e3a7e30406f3e7a9b3142d39e0439c98948134d11166b621dfd3ea9d3a84d985b2aa7732b7ad9beba44334dd86292b0c94befb2cb8aa72a823129cb", "123" },
{NULL}
};
static struct fmt_tests tests_all[] = {
{"truecrypt_SHA_512$aa582afe64197a3cfd4faf7697673e5e14414369da3f716400414f63f75447da7d3abdc65a25ea511b1772d67370d6c349d8000de66d65861403093fecfb85719e1d46158d24324e5a2c0ee598214b1b2e7eac761dbde8cb85bcb33f293df7f30c9e44a3fa97bf1c70e9986677855873fa2435d9154ccaed8f28d68f16b10adcce7032d7c1742d322739d02c05457859abdaa176faa95c674d2a1092c30832dd2afd9a319599b4d1db92ffe6e48b3b29e566d5c51af091839699f5ad1715730fef24e94e39a6f40770b8320e30bf972d810b588af88ce3450337adbec0a10255b20230bcfca93aa5a0a6592cd6038312181c0792c59ec9e5d95a6216497d39ae28131869b89368e82371718970bf9750a7114c83d87b1b0cd16b6e8d41c4925d15ec26107e92847ec1bb73363ca10f3ad62afa8b0f95ff13cdbe217a1e8a74508ef439ed2140b26d5538b8d011a0d1e469f2a6962e56964adc75b90d9c6a16e88ad0adb59a337f8abb3f9d76f7f9acad22853e9dbbce13a4f686c6a802243b0901972af3c6928511609ac7b957b352452c4347acd563a72faa86a46522942fdc57f32d48c5148a2bb0bc2c3dbc9851385f816f2ece958957082c0a8fe69f647be675d87fcb8244912abc277a3242ee17e1d522f85598417559cb3a9f60b755e5b613069cb54c05a4c5d2fbd3ca6ba793320aeb0e109f8b21852daf2d9ed74dd9", "password"},
{"truecrypt_SHA_512$73f6b08614dc4ffbd77d27a0815b0700d6b612f573ccd6c8937e8d154321e3c1c1c67dd348d4d3bc8304e94a3a6ec0c672de8396a9a6b26b12393195b7daa4225a9d3a134229be011f8179791bb00c31b5c132c8dbad5a6f8738487477c409b3c32d90b07be8d7a3a9faa95d37ab6faccc459d47f029e25adcea48cee83eaa35b7acc3f849717000421d92ac46e6f16ec3dccacd3ffae76a48280977d2a6727027d9d6ff9c4c98405359ee382f6dd1eca0d7007cbe804b81485c1085e74b58d3eb1e3c7ebdc1e1ab1384e4440ab6ca7beed7e0ef7d1e0da5ffc3cd89f7b6ac8a9257ee369d397ac1e112f75382ddbe6f7317ec20c46cb7b2111d0d91570e90b4c01a0b8205fcdf4d0cadcf4a067b8f285a541f1d649894fb3ade29a2ee0575524455d489c299dde215bea3254f7d43aa4e4011a39bdb6e7473bc29f588e659fdbf065cc4a336ba42f2b6c07479cf3e544978150fb013da7db22afcb4f8384e39e2edfa30a4cbe5e84a07c54ba66663bb9284836cc5a8ba7489d3f7f92aec6d9f4e264c90c2af6181082bd273197bc42c325cb1de31006dd55425e3f210d2ddd7973978eec865d3226bb1e30a9897146d90d79a73070e87f0182981ea85f15f948ae1958af7704fabecd6f07e20be70be9f9c38a5c5e5c8b17be648f011b2c40f62d6ac51de932add5bdb47bb428fd510b004a7aa79321b03ed7aa202be439fbf", "password" },
{TAG_SHA512"cfd9e5757da139b32d117cd60f86f649400615dc218981106dfadd44598599a7ec0ace42de61506fe8d81b5c885861cdb26e0c38cb9adfcff27ba88872220ccd0914d4fa44bab5a708fe6864e0f665ac71d87e7e97b3724d610cf1f6ec09fa99da40126f63868654fed3381eaa8176f689e8e292c3cb68e43601d5804bc2e19d86722c21d42204e158b26b720e7b8f7580edce15469195dd7ed711b0fcb6c8abc253d0fd93cc784d5279de527fbdcfb357780635a5c363b773b55957d7efb472f6e6012489a9f0d225573446e5251cfb277a1365eed787e0da52f02d835667d74cc41fa4002cc35ad1ce276fbf9d73d6553ac0f8ab6961901d292a66df814a2cbda1b41f29aeec88ed15e7d37fe84ac5306b5a1b8d2e1f2c132e5c7d40ca7bb76d4ff87980ca4d75eaac5066b3ed50b53259554b9f922f7cee8e91847359d06e448da02cbeeecc78ca9bee2899a33dfa04a478ca131d33c64d6de5f81b219f11bed6ff3c0d56f26b3a27c79e7c55b6f76567a612166ce71028e3d3ae7e5abd25faec5e2e9dc30719baa2c138e26d6f8e3799a72b5e7b1c2a07c12cea452073b72f6e429bb17dd23fe3934c9e406bb4060083f92aa100c2e82ca40664f65c02cbc800c5696659f8df84db17edb92de5d4f1ca9e5fe71844e1e8c4f8b19ce7362fb3ca5467bf65122067c53f011648a6663894b315e6c5c635bec5bd39da028041", "123" },
{"truecrypt_RIPEMD_160$b9f118f89d2699cbe42cad7bc2c61b0822b3d6e57e8d43e79f55666aa30572676c3aced5f0900af223e9fcdf43ac39637640977f546eb714475f8e2dbf5368bfb80a671d7796d4a88c36594acd07081b7ef0fbead3d3a0ff2b295e9488a5a2747ed97905436c28c636f408b36b0898aad3c4e9566182bd55f80e97a55ad9cf20899599fb775f314067c9f7e6153b9544bfbcffb53eef5a34b515e38f186a2ddcc7cd3aed635a1fb4aab98b82d57341ec6ae52ad72e43f41aa251717082d0858bf2ccc69a7ca00daceb5b325841d70bb2216e1f0d4dc936b9f50ebf92dbe2abec9bc3babea7a4357fa74a7b2bcce542044552bbc0135ae35568526e9bd2afde0fa4969d6dc680cf96f7d82ec0a75b6170c94e3f2b6fd98f2e6f01db08ce63f1b6bcf5ea380ed6f927a5a8ced7995d83ea8e9c49238e8523d63d6b669ae0d165b94f1e19b49922b4748798129eed9aa2dae0d2798adabf35dc4cc30b25851a3469a9ee0877775abca26374a4176f8d237f8191fcc870f413ffdbfa73ee22790a548025c4fcafd40f631508f1f6c8d4c847e409c839d21ff146f469feff87198bc184db4b5c5a77f3402f491538503f68e0116dac76344b762627ad678de76cb768779f8f1c35338dd9f72dcc1ac337319b0e21551b9feb85f8cac67a2f35f305a39037bf96cd61869bf1761abcce644598dad254990d17f0faa4965926acb75abf", "password" },
{TAG_RIPEMD160"6ab053e5ebee8c56bce5705fb1e03bf8cf99e2930232e525befe1e45063aa2e30981585020a967a1c45520543847cdb281557e16c81cea9d329b666e232eeb008dbe3e1f1a181f69f073f0f314bc17e255d42aaa1dbab92231a4fb62d100f6930bae4ccf6726680554dea3e2419fb67230c186f6af2c8b4525eb8ebb73d957b01b8a124b736e45f94160266bcfaeda16b351ec750d980250ebb76672578e9e3a104dde89611bce6ee32179f35073be9f1dee8da002559c6fab292ff3af657cf5a0d864a7844235aeac441afe55f69e51c7a7c06f7330a1c8babae2e6476e3a1d6fb3d4eb63694218e53e0483659aad21f20a70817b86ce56c2b27bae3017727ff26866a00e75f37e6c8091a28582bd202f30a5790f5a90792de010aebc0ed81e9743d00518419f32ce73a8d3f07e55830845fe21c64a8a748cbdca0c3bf512a4938e68a311004538619b65873880f13b2a9486f1292d5c77116509a64eb0a1bba7307f97d42e7cfa36d2b58b71393e04e7e3e328a7728197b8bcdef14cf3f7708cd233c58031c695da5f6b671cc5066323cc86bb3c6311535ad223a44abd4eec9077d70ab0f257de5706a3ff5c15e3bc2bde6496a8414bc6a5ed84fe9462b65efa866312e0699e47338e879ae512a66f3f36fc086d2595bbcff2e744dd1ec283ba8e91299e62e4b2392608dd950ede0c1f3d5b317b2870ead59efe096c054ea1", "123" },
{"truecrypt_WHIRLPOOL$5724ba89229d705010ec56af416b16155682a0cab9cf48ac5a5fdd2086c9a251ae4bbea6cfb8464321a789852f7812095b0e0c4c4f9c6d14ba7beedaf3484b375ac7bc97b43c3e74bf1a0c259b7ac8725d990d2ff31935ca3443f2ce8df59de86515da3e0f53f728882b71c5cc704df0c87c282a7413db446e9a2e516a144311dd25092eb0a2c5df0240d899708289fc7141abd8538fa5791d9f96c39129cce9fe8a6e58e84364e2f4acc32274147431cb2d2480b1b54bffee485acee0925852b8a6ee71d275f028b92e540be595448e5f1d78560a3b8ad209962dd5981d7ca98db9a678a588a9296157d44502cd78f9e32f022dddc9bc8111b5704ee39a9b56d30b89898ae340e90f2e6c73be6ac64de97e32fc2eed0b66dcd5c1553eeab3950cf851624a5a4439435a6fd5717fda6d5f939f4a902321341964c16bda8975752ba150fb9d858d8eaff2a2086cb50d30abff741ee20223b4223b1783f0ed537a609a081afed952395ef0b5de6883db66cbb5a8bac70f2f757c7b6e6bb5d863672820f0d3d61b262b2b6c2ca0dc8e7137851aa450da1c1d915e005bff0e849a89bf67693ef97f5c17bf8d07a18c562dc783274f9ec580f9519a6dd1429b66160ddb04549506ad616dd0695da144fa2ad270eac7163983e9036f1bde3c7634b8a246b8dcd518ce3e12b881c838fbce59a0cfdffa3b21447e3f28124f63549c3962", "password" },
{TAG_WHIRLPOOL"0650595770851981d70b088ff6ef4bf90573e08d03c8cac8b2dfded22e1653f5c45103758c68be344fdccae42b4683087da083a3841b92fb79856798eaee793c04cd95ae556d9616684da17e47bd2f775d8128f94b80b781e4cab4921b12c620721cf719ca72d3997cea829fd29b429282b597d5719c13423cdf7bd717fa12a56b8eddcf7b1ad2796c4ad078ab3a9bd944a694aa4b0078ed160440dd3db13dd1d04a7aaaa4dc016a95bd1cfafcd833ae933c627bf5512ae55c76069af7190823dba0133d6fe02e4421d3684ff2a2493da990a3cc5eed40a9e8c48c7a89a2f47030d45c324a3d78b941e772e24b285af6739ae1f5953ff838edaa69e79939f55d0fe00cd0e3a20a46db3a232009eabc800711342f7e580ba909f16c2039d4900fd4025845a385641a6037ceb6420fe7d37868e8c06e6146eddec9e6cb97e71048da5fa5898dac08152516ea1c6729e85d31596cd226aa218ce693989efb9fa8b05404bcc2debbc75c429a03fe31bfc49f10d595b898436ff6b02fc01d745b91280f26ae94a4969ce7f86c12e6b562c7b5377e3fb3247a8cda11a930c2a9e80f24966925de01afad5987ebee9c3de1d41667c6dc35cebbbc963f263c700d06a647ab7020385e3a7e30406f3e7a9b3142d39e0439c98948134d11166b621dfd3ea9d3a84d985b2aa7732b7ad9beba44334dd86292b0c94befb2cb8aa72a823129cb", "123" },
{NULL}
};
static void init(struct fmt_main *self)
{
#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
key_buffer = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*key_buffer));
first_block_dec = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*first_block_dec));
keyfiles_data = mem_calloc(MAX_KEYFILES,
sizeof(*keyfiles_data));
keyfiles_length = mem_calloc(MAX_KEYFILES,
sizeof(int));
}
static void done(void)
{
MEM_FREE(first_block_dec);
MEM_FREE(key_buffer);
MEM_FREE(keyfiles_data);
MEM_FREE(keyfiles_length);
}
static int valid(char* ciphertext, int pos)
{
unsigned int i;
char *p, *q;
int nkeyfiles = -1;
p = ciphertext + pos;
q = strchr(p, '$');
if (!q) { /* no keyfiles */
if(pos + 512*2 != strlen(ciphertext))
return 0;
} else {
if (q - p != 512 * 2)
return 0;
/* check keyfile(s) */
p = q + 1;
nkeyfiles = atoi(p);
if (nkeyfiles > MAX_KEYFILES || nkeyfiles < 1)
return 0;
}
// Not hexadecimal characters
for (i = 0; i < 512*2; i++) {
if (atoi16l[ARCH_INDEX((ciphertext+pos)[i])] == 0x7F)
return 0;
}
return 1;
}
static int valid_ripemd160(char* ciphertext, struct fmt_main *self)
{
// Not a supported hashing
if (strncmp(ciphertext, TAG_RIPEMD160, TAG_RIPEMD160_LEN))
return 0;
return valid(ciphertext, TAG_RIPEMD160_LEN);
}
static int valid_sha512(char* ciphertext, struct fmt_main *self)
{
// Not a supported hashing
if (strncmp(ciphertext, TAG_SHA512, TAG_SHA512_LEN))
return 0;
return valid(ciphertext, TAG_SHA512_LEN);
}
static int valid_whirlpool(char* ciphertext, struct fmt_main *self)
{
// Not a supported hashing
if (strncmp(ciphertext, TAG_WHIRLPOOL, TAG_WHIRLPOOL_LEN))
return 0;
return valid(ciphertext, TAG_WHIRLPOOL_LEN);
}
static int valid_truecrypt(char *ciphertext, struct fmt_main *self) {
if (valid_sha512(ciphertext, self) ||
valid_ripemd160(ciphertext, self) ||
valid_whirlpool(ciphertext, self))
return 1;
return 0;
}
static void set_salt(void *salt)
{
psalt = salt;
}
static void* get_salt(char *ciphertext)
{
static char buf[sizeof(struct cust_salt)+4];
struct cust_salt *s = (struct cust_salt *)mem_align(buf, 4);
unsigned int i;
char tpath[PATH_BUFFER_SIZE] = {0};
char *p, *q;
int idx;
FILE *fp;
size_t sz;
memset(s, 0, sizeof(struct cust_salt));
s->num_iterations = 1000;
s->loop_inc = 1;
if (!strncmp(ciphertext, TAG_WHIRLPOOL, TAG_WHIRLPOOL_LEN)) {
ciphertext += TAG_WHIRLPOOL_LEN;
s->hash_type = IS_WHIRLPOOL;
} else if (!strncmp(ciphertext, TAG_SHA512, TAG_SHA512_LEN)) {
ciphertext += TAG_SHA512_LEN;
s->hash_type = IS_SHA512;
#if SSE_GROUP_SZ_SHA512
s->loop_inc = SSE_GROUP_SZ_SHA512;
#endif
} else if (!strncmp(ciphertext, TAG_RIPEMD160, TAG_RIPEMD160_LEN)) {
ciphertext += TAG_RIPEMD160_LEN;
s->hash_type = IS_RIPEMD160;
s->num_iterations = 2000;
} else {
// should never get here! valid() should catch all lines that do not have the tags.
fprintf(stderr, "Error, unknown type in truecrypt::get_salt(), [%s]\n", ciphertext);
error();
}
// Convert the hexadecimal salt in binary
for(i = 0; i < 64; i++)
s->salt[i] = (atoi16[ARCH_INDEX(ciphertext[2*i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2*i+1])];
for(; i < 512; i++)
s->bin[i-64] = (atoi16[ARCH_INDEX(ciphertext[2*i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2*i+1])];
p = ciphertext;
q = strchr(p, '$');
if (!q) /* no keyfiles */
return s;
// process keyfile(s)
p = q + 1;
s->nkeyfiles = atoi(p);
for (idx = 0; idx < s->nkeyfiles; idx++) {
p = strchr(p, '$') + 1; // at first filename
q = strchr(p, '$');
if (!q) { // last file
memset(tpath, 0, sizeof(tpath) - 1);
strncpy(tpath, p, sizeof(tpath));
} else {
memset(tpath, 0, sizeof(tpath) - 1);
strncpy(tpath, p, q-p);
}
/* read this into keyfiles_data[idx] */
fp = fopen(tpath, "rb");
if (!fp)
pexit("fopen %s", p);
if (fseek(fp, 0L, SEEK_END) == -1)
pexit("fseek");
sz = ftell(fp);
if (fseek(fp, 0L, SEEK_SET) == -1)
pexit("fseek");
if (fread(keyfiles_data[idx], 1, sz, fp) != sz)
pexit("fread");
keyfiles_length[idx] = sz;
fclose(fp);
}
return s;
}
static int apply_keyfiles(unsigned char *pass, size_t pass_memsz, int nkeyfiles)
{
int pl, k;
unsigned char *kpool;
unsigned char *kdata;
int kpool_idx;
size_t i, kdata_sz;
uint32_t crc;
if (pass_memsz < MAX_PASSSZ) {
error();
}
pl = strlen((char *)pass);
memset(pass+pl, 0, MAX_PASSSZ-pl);
if ((kpool = mem_calloc(1, KPOOL_SZ)) == NULL) {
error();
}
for (k = 0; k < nkeyfiles; k++) {
kpool_idx = 0;
kdata_sz = keyfiles_length[k];
kdata = keyfiles_data[k];
crc = ~0U;
for (i = 0; i < kdata_sz; i++) {
crc = jtr_crc32(crc, kdata[i]);
kpool[kpool_idx++] += (unsigned char)(crc >> 24);
kpool[kpool_idx++] += (unsigned char)(crc >> 16);
kpool[kpool_idx++] += (unsigned char)(crc >> 8);
kpool[kpool_idx++] += (unsigned char)(crc);
/* Wrap around */
if (kpool_idx == KPOOL_SZ)
kpool_idx = 0;
}
}
/* Apply keyfile pool to passphrase */
for (i = 0; i < KPOOL_SZ; i++)
pass[i] += kpool[i];
MEM_FREE(kpool);
return 0;
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
int i;
const int count = *pcount;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i = 0; i < count; i+=psalt->loop_inc)
{
unsigned char key[64];
#if SSE_GROUP_SZ_SHA512
unsigned char Keys[SSE_GROUP_SZ_SHA512][64];
#endif
int j;
int ksz = strlen((char *)key_buffer[i]);
#if SSE_GROUP_SZ_SHA512
if (psalt->hash_type != IS_SHA512)
#endif
{
strncpy((char*)key, (char*)key_buffer[i], 64);
/* process keyfile(s) */
if (psalt->nkeyfiles) {
apply_keyfiles(key, 64, psalt->nkeyfiles);
ksz = 64;
}
}
#if SSE_GROUP_SZ_SHA512
if (psalt->hash_type == IS_SHA512) {
int lens[SSE_GROUP_SZ_SHA512];
unsigned char *pin[SSE_GROUP_SZ_SHA512];
union {
unsigned char *pout[SSE_GROUP_SZ_SHA512];
unsigned char *poutc;
} x;
for (j = 0; j < SSE_GROUP_SZ_SHA512; ++j) {
lens[j] = strlen((char*)(key_buffer[i+j]));
strncpy((char*)Keys[j], (char*)key_buffer[i+j], 64);
/* process keyfile(s) */
if (psalt->nkeyfiles) {
apply_keyfiles(Keys[j], 64, psalt->nkeyfiles);
lens[j] = 64;
}
pin[j] = key_buffer[i+j];
x.pout[j] = Keys[j];
}
pbkdf2_sha512_sse((const unsigned char **)pin, lens, psalt->salt, 64, psalt->num_iterations, &(x.poutc), sizeof(key), 0);
}
#else
if (psalt->hash_type == IS_SHA512) {
pbkdf2_sha512((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
}
#endif
else if (psalt->hash_type == IS_RIPEMD160)
pbkdf2_ripemd160((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
else
pbkdf2_whirlpool((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
for (j = 0; j < psalt->loop_inc; ++j) {
#if SSE_GROUP_SZ_SHA512
if (psalt->hash_type == IS_SHA512)
memcpy(key, Keys[j], sizeof(key));
#endif
// Try to decrypt using AES
AES_XTS_decrypt(key, first_block_dec[i+j], psalt->bin, 16, 256);
}
}
return count;
}
static int cmp_all(void* binary, int count)
{
int i;
for (i = 0; i < count; ++i) {
if (!memcmp(first_block_dec[i], "TRUE", 4))
return 1;
}
return 0;
}
static int cmp_one(void* binary, int index)
{
if (!memcmp(first_block_dec[index], "TRUE", 4))
return 1;
return 0;
}
// compare a BE string crc32, against crc32, and do it in a safe for non-aligned CPU way.
// this function is not really speed critical.
static int cmp_crc32s(unsigned char *given_crc32, CRC32_t comp_crc32) {
return given_crc32[0] == ((comp_crc32>>24)&0xFF) &&
given_crc32[1] == ((comp_crc32>>16)&0xFF) &&
given_crc32[2] == ((comp_crc32>> 8)&0xFF) &&
given_crc32[3] == ((comp_crc32>> 0)&0xFF);
}
static int cmp_exact(char *source, int idx)
{
#if 0
if (!memcmp(first_block_dec[idx], "TRUE", 4) && !memcmp(&first_block_dec[idx][12], "\0\0\0\0", 4))
return 1;
#else
unsigned char key[64];
unsigned char decr_header[512-64];
CRC32_t check_sum;
#if DEBUG
static int cnt;
char fname[64];
FILE *fp;
#endif
int ksz = strlen((char *)key_buffer[idx]);
strncpy((char*)key, (char*)key_buffer[idx], 64);
/* process keyfile(s) */
if (psalt->nkeyfiles) {
apply_keyfiles(key, 64, psalt->nkeyfiles);
ksz = 64;
}
if (psalt->hash_type == IS_SHA512)
pbkdf2_sha512(key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
else if (psalt->hash_type == IS_RIPEMD160)
pbkdf2_ripemd160(key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
else
pbkdf2_whirlpool(key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0);
// we have 448 bytes of header (64 bytes unencrypted salt were the first 64 bytes).
// decrypt it and look for 3 items.
AES_XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256);
// first item we look for is a contstant string 'TRUE' in the first 4 bytes
if (memcmp(decr_header, "TRUE", 4))
return 0;
// now we look for 2 crc values. At offset 8 is the first. This provided
// CRC should be the crc32 of the last 256 bytes of the buffer.
CRC32_Init(&check_sum);
CRC32_Update(&check_sum, &decr_header[256-64], 256);
if (!cmp_crc32s(&decr_header[8], ~check_sum))
return 0;
// now we compute crc of the first part of the buffer, up to 4 bytes less than
// the start of that last 256 bytes (i.e. 188 bytes in total). Following this
// buffer we compute crc32 over, should be a 4 byte block that is what we are
// given as a match for this crc32 (of course, those 4 bytes are not part of
// the crc32. The 4 bytes of provided crc32 is the only 4 bytes of the header
// which are not placed into 'some' CRC32 computation.
CRC32_Init(&check_sum);
CRC32_Update(&check_sum, decr_header, 256-64-4);
if (!cmp_crc32s(&decr_header[256-64-4], ~check_sum))
return 0;
#if DEBUG
snprintf(fname, sizeof(fname), "tc_decr_header-%04d.dat", cnt++);
fp = fopen(fname, "wb");
fwrite(decr_header, 1, 512-64, fp);
fclose(fp);
#endif
// Passed 96 bits of tests. This is the right password!
return 1;
#endif
return 0;
}
static void set_key(char* key, int index)
{
strcpy((char*)(key_buffer[index]), key);
}
static char *get_key(int index)
{
return (char*)(key_buffer[index]);
}
static int salt_hash(void *salt)
{
unsigned v=0, i;
struct cust_salt *psalt = (struct cust_salt *)salt;
for (i = 0; i < 64; ++i) {
v *= 11;
v += psalt->salt[i];
}
return v & (SALT_HASH_SIZE - 1);
}
static unsigned int tc_hash_algorithm(void *salt)
{
return (unsigned int)((struct cust_salt*)salt)->hash_type;
}
struct fmt_main fmt_truecrypt = {
{
"tc_aes_xts", // FORMAT_LABEL
"TrueCrypt AES256_XTS", // FORMAT_NAME
#if SSE_GROUP_SZ_SHA512
"SHA512 " SHA512_ALGORITHM_NAME " /RIPEMD160/WHIRLPOOL",
#else
#if ARCH_BITS >= 64
"SHA512 64/" ARCH_BITS_STR " /RIPEMD160/WHIRLPOOL",
#else
"SHA512 32/" ARCH_BITS_STR " /RIPEMD160/WHIRLPOOL",
#endif
#endif
"", // BENCHMARK_COMMENT
-1, // BENCHMARK_LENGTH
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
#if SSE_GROUP_SZ_SHA512
SSE_GROUP_SZ_SHA512,
SSE_GROUP_SZ_SHA512,
#else
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#endif
FMT_CASE | FMT_8_BIT | FMT_OMP,
{
"hash algorithm [1:SHA512 2:RIPEMD160 3:Whirlpool]",
},
tests_all
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid_truecrypt,
fmt_default_split,
fmt_default_binary,
get_salt,
{
tc_hash_algorithm,
},
fmt_default_source,
{
fmt_default_binary_hash
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_truecrypt_ripemd160 = {
{
"tc_ripemd160", // FORMAT_LABEL
"TrueCrypt AES256_XTS", // FORMAT_NAME
"RIPEMD160 32/" ARCH_BITS_STR, // ALGORITHM_NAME,
"", // BENCHMARK_COMMENT
-1, // 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,
{ NULL },
tests_ripemd160
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid_ripemd160,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_truecrypt_sha512 = {
{
"tc_sha512", // FORMAT_LABEL
"TrueCrypt AES256_XTS", // FORMAT_NAME
#if SSE_GROUP_SZ_SHA512
"SHA512 " SHA512_ALGORITHM_NAME, // ALGORITHM_NAME,
#else
#if ARCH_BITS >= 64
"SHA512 64/" ARCH_BITS_STR,
#else
"SHA512 32/" ARCH_BITS_STR,
#endif
#endif
"", // BENCHMARK_COMMENT
-1, // BENCHMARK_LENGTH
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
#if SSE_GROUP_SZ_SHA512
SSE_GROUP_SZ_SHA512,
SSE_GROUP_SZ_SHA512,
#else
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
#endif
FMT_CASE | FMT_8_BIT | FMT_OMP,
{ NULL },
tests_sha512
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid_sha512,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
struct fmt_main fmt_truecrypt_whirlpool = {
{
"tc_whirlpool", // FORMAT_LABEL
"TrueCrypt AES256_XTS", // FORMAT_NAME
#if ARCH_BITS >= 64
"WHIRLPOOL 64/" ARCH_BITS_STR, // ALGORITHM_NAME,
#else
"WHIRLPOOL 32/" ARCH_BITS_STR, // ALGORITHM_NAME,
#endif
"", // BENCHMARK_COMMENT
-1, // 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,
{ NULL },
tests_whirlpool
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid_whirlpool,
fmt_default_split,
fmt_default_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash
},
salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
openmp.c | #include <stdio.h>
#include <omp.h>
// COMPILE WIH -fopenmp flag
int main() {
int tid;
int gid = 1;
#pragma omp parallel private(tid) shared(gid)
{
tid = omp_get_thread_num();
gid = tid;
printf("Hello World %d %d\n", tid, gid);
}
} |
GB_binop__iseq_int32.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__iseq_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__iseq_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__iseq_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__iseq_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_int32)
// A*D function (colscale): GB (_AxD__iseq_int32)
// D*A function (rowscale): GB (_DxB__iseq_int32)
// C+=B function (dense accum): GB (_Cdense_accumB__iseq_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__iseq_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_int32)
// C=scalar+B GB (_bind1st__iseq_int32)
// C=scalar+B' GB (_bind1st_tran__iseq_int32)
// C=A+scalar GB (_bind2nd__iseq_int32)
// C=A'+scalar GB (_bind2nd_tran__iseq_int32)
// C type: int32_t
// A type: int32_t
// A pattern? 0
// B type: int32_t
// B pattern? 0
// BinaryOp: cij = (aij == bij)
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_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) \
int32_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) \
int32_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) \
int32_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_ISEQ || GxB_NO_INT32 || GxB_NO_ISEQ_INT32)
//------------------------------------------------------------------------------
// 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__iseq_int32)
(
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__iseq_int32)
(
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__iseq_int32)
(
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 int32_t
int32_t bwork = (*((int32_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__iseq_int32)
(
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
int32_t *restrict Cx = (int32_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__iseq_int32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_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__iseq_int32)
(
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) ;
int32_t alpha_scalar ;
int32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_t *) alpha_scalar_in)) ;
beta_scalar = (*((int32_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__iseq_int32)
(
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__iseq_int32)
(
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__iseq_int32)
(
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__iseq_int32)
(
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__iseq_int32)
(
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
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_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 ;
int32_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__iseq_int32)
(
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 ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int32_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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x == aij) ; \
}
GrB_Info GB (_bind1st_tran__iseq_int32)
(
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 \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij == y) ; \
}
GrB_Info GB (_bind2nd_tran__iseq_int32)
(
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
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
sp_single.c | /*--------------------------------------------------------------------
NAS Parallel Benchmarks 2.3 OpenMP C versions - SP
This benchmark is an OpenMP C version of the NPB SP code.
The OpenMP C versions are developed by RWCP and derived from the serial
Fortran versions in "NPB 2.3-serial" developed by NAS.
Permission to use, copy, distribute and modify this software for any
purpose with or without fee is hereby granted.
This software is provided "as is" without express or implied warranty.
Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp
Information on OpenMP activities at RWCP is available at:
http://pdplab.trc.rwcp.or.jp/pdperf/Omni/
Information on NAS Parallel Benchmarks 2.3 is available at:
http://www.nas.nasa.gov/NAS/NPB/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
Author: R. Van der Wijngaart
W. Saphir
OpenMP C version: S. Satoh
--------------------------------------------------------------------*/
//#include "npb-C.h"
/*
NAS Parallel Benchmarks 2.3 OpenMP C Versions
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if defined(_OPENMP)
#include <omp.h>
#endif /* _OPENMP */
typedef int boolean;
typedef struct { double real; double imag; } dcomplex;
#define TRUE 1
#define FALSE 0
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define pow2(a) ((a)*(a))
#define get_real(c) c.real
#define get_imag(c) c.imag
#define cadd(c,a,b) (c.real = a.real + b.real, c.imag = a.imag + b.imag)
#define csub(c,a,b) (c.real = a.real - b.real, c.imag = a.imag - b.imag)
#define cmul(c,a,b) (c.real = a.real * b.real - a.imag * b.imag, \
c.imag = a.real * b.imag + a.imag * b.real)
#define crmul(c,a,b) (c.real = a.real * b, c.imag = a.imag * b)
extern double randlc(double *, double);
extern void vranlc(int, double *, double, double *);
extern void timer_clear(int);
extern void timer_start(int);
extern void timer_stop(int);
extern double timer_read(int);
extern void c_print_results(char *name, char cclass, int n1, int n2,
int n3, int niter, int nthreads, double t,
double mops, char *optype, int passed_verification,
char *npbversion, char *compiletime, char *cc,
char *clink, char *c_lib, char *c_inc,
char *cflags, char *clinkflags, char *rand);
/* global variables */
//#include "header.h"
/******************/
/* default values */
/******************/
#ifndef CLASS
#define CLASS 'S'
#endif
#if CLASS == 'S'
/* CLASS = S */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define PROBLEM_SIZE 12
#define NITER_DEFAULT 100
#define DT_DEFAULT 0.015
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'W'
/* CLASS = W */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define PROBLEM_SIZE 36
#define NITER_DEFAULT 400
#define DT_DEFAULT 0.0015
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'A'
/* CLASS = A */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define PROBLEM_SIZE 64
#define NITER_DEFAULT 400
#define DT_DEFAULT 0.0015
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'B'
/* CLASS = B */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define PROBLEM_SIZE 102
#define NITER_DEFAULT 400
#define DT_DEFAULT 0.001
#define CONVERTDOUBLE FALSE
#endif
#if CLASS == 'C'
/* CLASS = C */
/*
c This file is generated automatically by the setparams utility.
c It sets the number of processors and the classc of the NPB
c in this directory. Do not modify it by hand.
*/
#define PROBLEM_SIZE 162
#define NITER_DEFAULT 400
#define DT_DEFAULT 0.00067
#define CONVERTDOUBLE FALSE
#endif
#define COMPILETIME "28 Oct 2014"
#define NPBVERSION "2.3"
#define CS1 "gcc"
#define CS2 "$(CC)"
#define CS3 "(none)"
#define CS4 "-I../common"
#define CS5 "-fopenmp -O2"
#define CS6 "-lm -fopenmp"
#define CS7 "randdp"
/* common /global */
static int grid_points[3];
/* common /constants/ */
static double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3,
dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4,
dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt,
ce[13][5], dxmax, dymax, dzmax, xxcon1, xxcon2,
xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1,
dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4,
yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1,
zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1,
dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1,
dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2,
c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt,
dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1,
c2dtty1, c2dttz1, comz1, comz4, comz5, comz6,
c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16;
#define IMAX PROBLEM_SIZE
#define JMAX PROBLEM_SIZE
#define KMAX PROBLEM_SIZE
/*--------------------------------------------------------------------
c To improve cache performance, first two dimensions padded by 1
c for even number sizes only
c-------------------------------------------------------------------*/
/* common /fields/ */
static double u [5][IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
us [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
vs [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
ws [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
qs [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
ainv [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
rho_i [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
speed [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
square [IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
rhs [5][IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
forcing [5][IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1],
lhs [15][IMAX/2*2+1][JMAX/2*2+1][KMAX/2*2+1];
/* common /work_1d/ */
static double cv[PROBLEM_SIZE], rhon[PROBLEM_SIZE],
rhos[PROBLEM_SIZE], rhoq[PROBLEM_SIZE],
cuf[PROBLEM_SIZE], q[PROBLEM_SIZE],
ue[5][PROBLEM_SIZE], buf[5][PROBLEM_SIZE];
/* function declarations */
static void add(void);
static void adi(void);
static void error_norm(double rms[5]);
static void rhs_norm(double rms[5]);
static void exact_rhs(void);
static void exact_solution(double xi, double eta, double zeta,
double dtemp[5]);
static void initialize(void);
static void lhsinit(void);
static void lhsx(void);
static void lhsy(void);
static void lhsz(void);
static void ninvr(void);
static void pinvr(void);
static void compute_rhs(void);
static void set_constants(void);
static void txinvr(void);
static void tzetar(void);
static void verify(int no_time_steps, char *cclass, boolean *verified);
static void x_solve(void);
static void y_solve(void);
static void z_solve(void);
/*--------------------------------------------------------------------
program SP
c-------------------------------------------------------------------*/
int main(int argc, char **argv) {
int niter, step;
double mflops, tmax;
int nthreads = 1;
boolean verified;
char cclass;
FILE *fp;
/*--------------------------------------------------------------------
c Read input file (if it exists), else take
c defaults from parameters
c-------------------------------------------------------------------*/
printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version"
" - SP Benchmark\n\n");
fp = fopen("inputsp.data", "r");
if (fp != NULL) {
printf(" Reading from input file inputsp.data\n");
fscanf(fp, "%d", &niter);
while (fgetc(fp) != '\n');
fscanf(fp, "%lf", &dt);
while (fgetc(fp) != '\n');
fscanf(fp, "%d%d%d",
&grid_points[0], &grid_points[1], &grid_points[2]);
fclose(fp);
} else {
printf(" No input file inputsp.data. Using compiled defaults");
niter = NITER_DEFAULT;
dt = DT_DEFAULT;
grid_points[0] = PROBLEM_SIZE;
grid_points[1] = PROBLEM_SIZE;
grid_points[2] = PROBLEM_SIZE;
}
printf(" Size: %3dx%3dx%3d\n",
grid_points[0], grid_points[1], grid_points[2]);
printf(" Iterations: %3d dt: %10.6f\n", niter, dt);
if ( (grid_points[0] > IMAX) ||
(grid_points[1] > JMAX) ||
(grid_points[2] > KMAX) ) {
printf("%d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]);
printf(" Problem size too big for compiled array sizes\n");
exit(1);
}
set_constants();
initialize();
lhsinit();
exact_rhs();
/*--------------------------------------------------------------------
c do one time step to touch all code, and reinitialize
c-------------------------------------------------------------------*/
#pragma omp parallel
{
adi();
}
initialize();
timer_clear(1);
timer_start(1);
#pragma omp parallel private(step)
{
for (step = 1; step <= niter; step++) {
if (step % 20 == 0 || step == 1) {
#pragma omp master
printf(" Time step %4d\n", step);
}
adi();
}
#if defined(_OPENMP)
#pragma omp master
nthreads = omp_get_num_threads();
#endif /* _OPENMP */
} /* end parallel */
timer_stop(1);
tmax = timer_read(1);
verify(niter, &cclass, &verified);
if (tmax != 0) {
mflops = ( 881.174 * pow((double)PROBLEM_SIZE, 3.0)
- 4683.91 * pow2((double)PROBLEM_SIZE)
+ 11484.5 * (double)PROBLEM_SIZE
- 19272.4) * (double)niter / (tmax*1000000.0);
} else {
mflops = 0.0;
}
c_print_results("SP", cclass, grid_points[0],
grid_points[1], grid_points[2], niter, nthreads,
tmax, mflops, " floating point",
verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5,
CS6, "(none)");
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void add(void) {
int i, j, k, m;
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c addition of update to the vector u
c-------------------------------------------------------------------*/
#pragma omp for
for (m = 0; m < 5; m++) {
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
u[m][i][j][k] = u[m][i][j][k] + rhs[m][i][j][k];
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void adi(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
compute_rhs();
txinvr();
x_solve();
y_solve();
z_solve();
add();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void error_norm(double rms[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function computes the norm of the difference between the
c computed solution and the exact solution
c-------------------------------------------------------------------*/
int i, j, k, m, d;
double xi, eta, zeta, u_exact[5], add;
for (m = 0; m < 5; m++) {
rms[m] = 0.0;
}
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)j * dnym1;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, u_exact);
for (m = 0; m < 5; m++) {
add = u[m][i][j][k] - u_exact[m];
rms[m] = rms[m] + add*add;
}
}
}
}
for (m = 0; m < 5; m++) {
for (d = 0; d < 3; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void rhs_norm(double rms[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
int i, j, k, d, m;
double add;
for (m = 0; m < 5; m++) {
rms[m] = 0.0;
}
for (i = 0; i <= grid_points[0]-2; i++) {
for (j = 0; j <= grid_points[1]-2; j++) {
for (k = 0; k <= grid_points[2]-2; k++) {
for (m = 0; m < 5; m++) {
add = rhs[m][i][j][k];
rms[m] = rms[m] + add*add;
}
}
}
}
for (m = 0; m < 5; m++) {
for (d = 0; d < 3; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void exact_rhs(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c compute the right hand side based on exact solution
c-------------------------------------------------------------------*/
double dtemp[5], xi, eta, zeta, dtpp;
int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1;
/*--------------------------------------------------------------------
c initialize
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
for (i = 0; i <= grid_points[0]-1; i++) {
for (j = 0; j <= grid_points[1]-1; j++) {
for (k= 0; k <= grid_points[2]-1; k++) {
forcing[m][i][j][k] = 0.0;
}
}
}
}
/*--------------------------------------------------------------------
c xi-direction flux differences
c-------------------------------------------------------------------*/
for (k = 1; k <= grid_points[2]-2; k++) {
zeta = (double)k * dnzm1;
for (j = 1; j <= grid_points[1]-2; j++) {
eta = (double)j * dnym1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[m][i] = dtemp[m];
}
dtpp = 1.0 / dtemp[0];
for (m = 1; m < 5; m++) {
buf[m][i] = dtpp * dtemp[m];
}
cuf[i] = buf[1][i] * buf[1][i];
buf[0][i] = cuf[i] + buf[2][i] * buf[2][i] + buf[3][i] * buf[3][i];
q[i] = 0.5 * (buf[1][i]*ue[1][i] + buf[2][i]*ue[2][i]
+ buf[3][i]*ue[3][i]);
}
for (i = 1; i <= grid_points[0]-2; i++) {
im1 = i-1;
ip1 = i+1;
forcing[0][i][j][k] = forcing[0][i][j][k] -
tx2*( ue[1][ip1]-ue[1][im1] )+
dx1tx1*(ue[0][ip1]-2.0*ue[0][i]+ue[0][im1]);
forcing[1][i][j][k] = forcing[1][i][j][k]
- tx2 * ((ue[1][ip1]*buf[1][ip1]+c2*(ue[4][ip1]-q[ip1]))-
(ue[1][im1]*buf[1][im1]+c2*(ue[4][im1]-q[im1])))+
xxcon1*(buf[1][ip1]-2.0*buf[1][i]+buf[1][im1])+
dx2tx1*( ue[1][ip1]-2.0* ue[1][i]+ue[1][im1]);
forcing[2][i][j][k] = forcing[2][i][j][k]
- tx2 * (ue[2][ip1]*buf[1][ip1]-ue[2][im1]*buf[1][im1])+
xxcon2*(buf[2][ip1]-2.0*buf[2][i]+buf[2][im1])+
dx3tx1*( ue[2][ip1]-2.0*ue[2][i] +ue[2][im1]);
forcing[3][i][j][k] = forcing[3][i][j][k]
- tx2*(ue[3][ip1]*buf[1][ip1]-ue[3][im1]*buf[1][im1])+
xxcon2*(buf[3][ip1]-2.0*buf[3][i]+buf[3][im1])+
dx4tx1*( ue[3][ip1]-2.0* ue[3][i]+ ue[3][im1]);
forcing[4][i][j][k] = forcing[4][i][j][k]
- tx2*(buf[1][ip1]*(c1*ue[4][ip1]-c2*q[ip1])-
buf[1][im1]*(c1*ue[4][im1]-c2*q[im1]))+
0.5*xxcon3*(buf[0][ip1]-2.0*buf[0][i]+
buf[0][im1])+
xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+
xxcon5*(buf[4][ip1]-2.0*buf[4][i]+buf[4][im1])+
dx5tx1*( ue[4][ip1]-2.0* ue[4][i]+ ue[4][im1]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
i = 1;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(5.0*ue[m][i] - 4.0*ue[m][i+1] +ue[m][i+2]);
i = 2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(-4.0*ue[m][i-1] + 6.0*ue[m][i] -
4.0*ue[m][i+1] + ue[m][i+2]);
}
for (m = 0; m < 5; m++) {
for (i = 3; i <= grid_points[0]-4; i++) {
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp*
(ue[m][i-2] - 4.0*ue[m][i-1] +
6.0*ue[m][i] - 4.0*ue[m][i+1] + ue[m][i+2]);
}
}
for (m = 0; m < 5; m++) {
i = grid_points[0]-3;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][i-2] - 4.0*ue[m][i-1] +
6.0*ue[m][i] - 4.0*ue[m][i+1]);
i = grid_points[0]-2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][i-2] - 4.0*ue[m][i-1] + 5.0*ue[m][i]);
}
}
}
/*--------------------------------------------------------------------
c eta-direction flux differences
c-------------------------------------------------------------------*/
for (k = 1; k <= grid_points[2]-2; k++) {
zeta = (double)k * dnzm1;
for (i = 1; i <= grid_points[0]-2; i++) {
xi = (double)i * dnxm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[m][j] = dtemp[m];
}
dtpp = 1.0/dtemp[0];
for (m = 1; m < 5; m++) {
buf[m][j] = dtpp * dtemp[m];
}
cuf[j] = buf[2][j] * buf[2][j];
buf[0][j] = cuf[j] + buf[1][j] * buf[1][j] +
buf[3][j] * buf[3][j];
q[j] = 0.5*(buf[1][j]*ue[1][j] + buf[2][j]*ue[2][j] +
buf[3][j]*ue[3][j]);
}
for (j = 1; j <= grid_points[1]-2; j++) {
jm1 = j-1;
jp1 = j+1;
forcing[0][i][j][k] = forcing[0][i][j][k] -
ty2*( ue[2][jp1]-ue[2][jm1] )+
dy1ty1*(ue[0][jp1]-2.0*ue[0][j]+ue[0][jm1]);
forcing[1][i][j][k] = forcing[1][i][j][k]
- ty2*(ue[1][jp1]*buf[2][jp1]-ue[1][jm1]*buf[2][jm1])+
yycon2*(buf[1][jp1]-2.0*buf[1][j]+buf[1][jm1])+
dy2ty1*( ue[1][jp1]-2.0* ue[1][j]+ ue[1][jm1]);
forcing[2][i][j][k] = forcing[2][i][j][k]
- ty2*((ue[2][jp1]*buf[2][jp1]+c2*(ue[4][jp1]-q[jp1]))-
(ue[2][jm1]*buf[2][jm1]+c2*(ue[4][jm1]-q[jm1])))+
yycon1*(buf[2][jp1]-2.0*buf[2][j]+buf[2][jm1])+
dy3ty1*( ue[2][jp1]-2.0*ue[2][j] +ue[2][jm1]);
forcing[3][i][j][k] = forcing[3][i][j][k]
- ty2*(ue[3][jp1]*buf[2][jp1]-ue[3][jm1]*buf[2][jm1])+
yycon2*(buf[3][jp1]-2.0*buf[3][j]+buf[3][jm1])+
dy4ty1*( ue[3][jp1]-2.0*ue[3][j]+ ue[3][jm1]);
forcing[4][i][j][k] = forcing[4][i][j][k]
- ty2*(buf[2][jp1]*(c1*ue[4][jp1]-c2*q[jp1])-
buf[2][jm1]*(c1*ue[4][jm1]-c2*q[jm1]))+
0.5*yycon3*(buf[0][jp1]-2.0*buf[0][j]+
buf[0][jm1])+
yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+
yycon5*(buf[4][jp1]-2.0*buf[4][j]+buf[4][jm1])+
dy5ty1*(ue[4][jp1]-2.0*ue[4][j]+ue[4][jm1]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
j = 1;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(5.0*ue[m][j] - 4.0*ue[m][j+1] +ue[m][j+2]);
j = 2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(-4.0*ue[m][j-1] + 6.0*ue[m][j] -
4.0*ue[m][j+1] + ue[m][j+2]);
}
for (m = 0; m < 5; m++) {
for (j = 3; j <= grid_points[1]-4; j++) {
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp*
(ue[m][j-2] - 4.0*ue[m][j-1] +
6.0*ue[m][j] - 4.0*ue[m][j+1] + ue[m][j+2]);
}
}
for (m = 0; m < 5; m++) {
j = grid_points[1]-3;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][j-2] - 4.0*ue[m][j-1] +
6.0*ue[m][j] - 4.0*ue[m][j+1]);
j = grid_points[1]-2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][j-2] - 4.0*ue[m][j-1] + 5.0*ue[m][j]);
}
}
}
/*--------------------------------------------------------------------
c zeta-direction flux differences
c-------------------------------------------------------------------*/
for (j = 1; j <= grid_points[1]-2; j++) {
eta = (double)j * dnym1;
for (i = 1; i <= grid_points[0]-2; i++) {
xi = (double)i * dnxm1;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, dtemp);
for (m = 0; m < 5; m++) {
ue[m][k] = dtemp[m];
}
dtpp = 1.0/dtemp[0];
for (m = 1; m < 5; m++) {
buf[m][k] = dtpp * dtemp[m];
}
cuf[k] = buf[3][k] * buf[3][k];
buf[0][k] = cuf[k] + buf[1][k] * buf[1][k] +
buf[2][k] * buf[2][k];
q[k] = 0.5*(buf[1][k]*ue[1][k] + buf[2][k]*ue[2][k] +
buf[3][k]*ue[3][k]);
}
for (k = 1; k <= grid_points[2]-2; k++) {
km1 = k-1;
kp1 = k+1;
forcing[0][i][j][k] = forcing[0][i][j][k] -
tz2*( ue[3][kp1]-ue[3][km1] )+
dz1tz1*(ue[0][kp1]-2.0*ue[0][k]+ue[0][km1]);
forcing[1][i][j][k] = forcing[1][i][j][k]
- tz2 * (ue[1][kp1]*buf[3][kp1]-ue[1][km1]*buf[3][km1])+
zzcon2*(buf[1][kp1]-2.0*buf[1][k]+buf[1][km1])+
dz2tz1*( ue[1][kp1]-2.0* ue[1][k]+ ue[1][km1]);
forcing[2][i][j][k] = forcing[2][i][j][k]
- tz2 * (ue[2][kp1]*buf[3][kp1]-ue[2][km1]*buf[3][km1])+
zzcon2*(buf[2][kp1]-2.0*buf[2][k]+buf[2][km1])+
dz3tz1*(ue[2][kp1]-2.0*ue[2][k]+ue[2][km1]);
forcing[3][i][j][k] = forcing[3][i][j][k]
- tz2 * ((ue[3][kp1]*buf[3][kp1]+c2*(ue[4][kp1]-q[kp1]))-
(ue[3][km1]*buf[3][km1]+c2*(ue[4][km1]-q[km1])))+
zzcon1*(buf[3][kp1]-2.0*buf[3][k]+buf[3][km1])+
dz4tz1*( ue[3][kp1]-2.0*ue[3][k] +ue[3][km1]);
forcing[4][i][j][k] = forcing[4][i][j][k]
- tz2 * (buf[3][kp1]*(c1*ue[4][kp1]-c2*q[kp1])-
buf[3][km1]*(c1*ue[4][km1]-c2*q[km1]))+
0.5*zzcon3*(buf[0][kp1]-2.0*buf[0][k]
+buf[0][km1])+
zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+
zzcon5*(buf[4][kp1]-2.0*buf[4][k]+buf[4][km1])+
dz5tz1*( ue[4][kp1]-2.0*ue[4][k]+ ue[4][km1]);
}
/*--------------------------------------------------------------------
c Fourth-order dissipation
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
k = 1;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(5.0*ue[m][k] - 4.0*ue[m][k+1] +ue[m][k+2]);
k = 2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(-4.0*ue[m][k-1] + 6.0*ue[m][k] -
4.0*ue[m][k+1] + ue[m][k+2]);
}
for (m = 0; m < 5; m++) {
for (k = 3; k <= grid_points[2]-4; k++) {
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp*
(ue[m][k-2] - 4.0*ue[m][k-1] +
6.0*ue[m][k] - 4.0*ue[m][k+1] + ue[m][k+2]);
}
}
for (m = 0; m < 5; m++) {
k = grid_points[2]-3;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][k-2] - 4.0*ue[m][k-1] +
6.0*ue[m][k] - 4.0*ue[m][k+1]);
k = grid_points[2]-2;
forcing[m][i][j][k] = forcing[m][i][j][k] - dssp *
(ue[m][k-2] - 4.0*ue[m][k-1] + 5.0*ue[m][k]);
}
}
}
/*--------------------------------------------------------------------
c now change the sign of the forcing function,
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
forcing[m][i][j][k] = -1.0 * forcing[m][i][j][k];
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void exact_solution(double xi, double eta, double zeta,
double dtemp[5]) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function returns the exact solution at point xi, eta, zeta
c-------------------------------------------------------------------*/
int m;
for (m = 0; m < 5; m++) {
dtemp[m] = ce[0][m] +
xi*(ce[1][m] + xi*(ce[4][m] +
xi*(ce[7][m] + xi*ce[10][m]))) +
eta*(ce[2][m] + eta*(ce[5][m] +
eta*(ce[8][m] + eta*ce[11][m])))+
zeta*(ce[3][m] + zeta*(ce[6][m] +
zeta*(ce[9][m] +
zeta*ce[12][m])));
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void initialize(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This subroutine initializes the field variable u using
c tri-linear transfinite interpolation of the boundary values
c-------------------------------------------------------------------*/
int i, j, k, m, ix, iy, iz;
double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5];
/*--------------------------------------------------------------------
c Later (in compute_rhs) we compute 1/u for every element. A few of
c the corner elements are not used, but it convenient (and faster)
c to compute the whole thing with a simple loop. Make sure those
c values are nonzero by initializing the whole thing here.
c-------------------------------------------------------------------*/
for (i = 0; i <= IMAX-1; i++) {
for (j = 0; j <= IMAX-1; j++) {
for (k = 0; k <= IMAX-1; k++) {
u[0][i][j][k] = 1.0;
u[1][i][j][k] = 0.0;
u[2][i][j][k] = 0.0;
u[3][i][j][k] = 0.0;
u[4][i][j][k] = 1.0;
}
}
}
/*--------------------------------------------------------------------
c first store the "interpolated" values everywhere on the grid
c-------------------------------------------------------------------*/
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)j * dnym1;
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
for (ix = 0; ix < 2; ix++) {
exact_solution((double)ix, eta, zeta,
&Pface[ix][0][0]);
}
for (iy = 0; iy < 2; iy++) {
exact_solution(xi, (double)iy , zeta,
&Pface[iy][1][0]);
}
for (iz = 0; iz < 2; iz++) {
exact_solution(xi, eta, (double)iz,
&Pface[iz][2][0]);
}
for (m = 0; m < 5; m++) {
Pxi = xi * Pface[1][0][m] +
(1.0-xi) * Pface[0][0][m];
Peta = eta * Pface[1][1][m] +
(1.0-eta) * Pface[0][1][m];
Pzeta = zeta * Pface[1][2][m] +
(1.0-zeta) * Pface[0][2][m];
u[m][i][j][k] = Pxi + Peta + Pzeta -
Pxi*Peta - Pxi*Pzeta - Peta*Pzeta +
Pxi*Peta*Pzeta;
}
}
}
}
/*--------------------------------------------------------------------
c now store the exact values on the boundaries
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c west face
c-------------------------------------------------------------------*/
xi = 0.0;
i = 0;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c east face
c-------------------------------------------------------------------*/
xi = 1.0;
i = grid_points[0]-1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c south face
c-------------------------------------------------------------------*/
eta = 0.0;
j = 0;
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c north face
c-------------------------------------------------------------------*/
eta = 1.0;
j = grid_points[1]-1;
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (k = 0; k < grid_points[2]; k++) {
zeta = (double)k * dnzm1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c bottom face
c-------------------------------------------------------------------*/
zeta = 0.0;
k = 0;
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i *dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
/*--------------------------------------------------------------------
c top face
c-------------------------------------------------------------------*/
zeta = 1.0;
k = grid_points[2]-1;
for (i = 0; i < grid_points[0]; i++) {
xi = (double)i * dnxm1;
for (j = 0; j < grid_points[1]; j++) {
eta = (double)j * dnym1;
exact_solution(xi, eta, zeta, temp);
for (m = 0; m < 5; m++) {
u[m][i][j][k] = temp[m];
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsinit(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
int i, j, k, n;
/*--------------------------------------------------------------------
c zap the whole left hand side for starters
c-------------------------------------------------------------------*/
for (n = 0; n < 15; n++) {
#pragma omp for nowait
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
lhs[n][i][j][k] = 0.0;
}
}
}
}
#pragma omp barrier
/*--------------------------------------------------------------------
c next, set all diagonal values to 1. This is overkill, but
c convenient
c-------------------------------------------------------------------*/
for (n = 0; n < 3; n++) {
#pragma omp for
for (i = 0; i < grid_points[0]; i++) {
for (j = 0; j < grid_points[1]; j++) {
for (k = 0; k < grid_points[2]; k++) {
lhs[5*n+2][i][j][k] = 1.0;
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsx(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side for the three x-factors
c-------------------------------------------------------------------*/
double ru1;
int i, j, k;
/*--------------------------------------------------------------------
c first fill the lhs for the u-eigenvalue
c-------------------------------------------------------------------*/
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
#pragma omp for
for (i = 0; i <= grid_points[0]-1; i++) {
ru1 = c3c4*rho_i[i][j][k];
cv[i] = us[i][j][k];
rhon[i] = max(dx2+con43*ru1,
max(dx5+c1c5*ru1,
max(dxmax+ru1,
dx1)));
}
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
lhs[0][i][j][k] = 0.0;
lhs[1][i][j][k] = - dttx2 * cv[i-1] - dttx1 * rhon[i-1];
lhs[2][i][j][k] = 1.0 + c2dttx1 * rhon[i];
lhs[3][i][j][k] = dttx2 * cv[i+1] - dttx1 * rhon[i+1];
lhs[4][i][j][k] = 0.0;
}
}
}
/*--------------------------------------------------------------------
c add fourth order dissipation
c-------------------------------------------------------------------*/
i = 1;
#pragma omp for nowait
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[2][i][j][k] = lhs[2][i][j][k] + comz5;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4;
lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz6;
lhs[3][i+1][j][k] = lhs[3][i+1][j][k] - comz4;
lhs[4][i+1][j][k] = lhs[4][i+1][j][k] + comz1;
}
}
#pragma omp for nowait
for (i = 3; i <= grid_points[0]-4; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
}
}
}
i = grid_points[0]-3;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[0][i+1][j][k] = lhs[0][i+1][j][k] + comz1;
lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4;
lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz5;
}
}
/*--------------------------------------------------------------------
c subsequently, fill the other factors (u+c), (u-c) by adding to
c the first
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0+5][i][j][k] = lhs[0][i][j][k];
lhs[1+5][i][j][k] = lhs[1][i][j][k] -
dttx2 * speed[i-1][j][k];
lhs[2+5][i][j][k] = lhs[2][i][j][k];
lhs[3+5][i][j][k] = lhs[3][i][j][k] +
dttx2 * speed[i+1][j][k];
lhs[4+5][i][j][k] = lhs[4][i][j][k];
lhs[0+10][i][j][k] = lhs[0][i][j][k];
lhs[1+10][i][j][k] = lhs[1][i][j][k] +
dttx2 * speed[i-1][j][k];
lhs[2+10][i][j][k] = lhs[2][i][j][k];
lhs[3+10][i][j][k] = lhs[3][i][j][k] -
dttx2 * speed[i+1][j][k];
lhs[4+10][i][j][k] = lhs[4][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsy(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side for the three y-factors
c-------------------------------------------------------------------*/
double ru1;
int i, j, k;
/*--------------------------------------------------------------------
c first fill the lhs for the u-eigenvalue
c-------------------------------------------------------------------*/
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
#pragma omp for
for (j = 0; j <= grid_points[1]-1; j++) {
ru1 = c3c4*rho_i[i][j][k];
cv[j] = vs[i][j][k];
rhoq[j] = max(dy3 + con43 * ru1,
max(dy5 + c1c5*ru1,
max(dymax + ru1,
dy1)));
}
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
lhs[0][i][j][k] = 0.0;
lhs[1][i][j][k] = -dtty2 * cv[j-1] - dtty1 * rhoq[j-1];
lhs[2][i][j][k] = 1.0 + c2dtty1 * rhoq[j];
lhs[3][i][j][k] = dtty2 * cv[j+1] - dtty1 * rhoq[j+1];
lhs[4][i][j][k] = 0.0;
}
}
}
/*--------------------------------------------------------------------
c add fourth order dissipation
c-------------------------------------------------------------------*/
j = 1;
#pragma omp for nowait
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[2][i][j][k] = lhs[2][i][j][k] + comz5;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4;
lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz6;
lhs[3][i][j+1][k] = lhs[3][i][j+1][k] - comz4;
lhs[4][i][j+1][k] = lhs[4][i][j+1][k] + comz1;
}
}
#pragma omp for nowait
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 3; j <= grid_points[1]-4; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
}
}
}
j = grid_points[1]-3;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[0][i][j+1][k] = lhs[0][i][j+1][k] + comz1;
lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4;
lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz5;
}
}
/*--------------------------------------------------------------------
c subsequently, do the other two factors
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0+5][i][j][k] = lhs[0][i][j][k];
lhs[1+5][i][j][k] = lhs[1][i][j][k] -
dtty2 * speed[i][j-1][k];
lhs[2+5][i][j][k] = lhs[2][i][j][k];
lhs[3+5][i][j][k] = lhs[3][i][j][k] +
dtty2 * speed[i][j+1][k];
lhs[4+5][i][j][k] = lhs[4][i][j][k];
lhs[0+10][i][j][k] = lhs[0][i][j][k];
lhs[1+10][i][j][k] = lhs[1][i][j][k] +
dtty2 * speed[i][j-1][k];
lhs[2+10][i][j][k] = lhs[2][i][j][k];
lhs[3+10][i][j][k] = lhs[3][i][j][k] -
dtty2 * speed[i][j+1][k];
lhs[4+10][i][j][k] = lhs[4][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void lhsz(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c This function computes the left hand side for the three z-factors
c-------------------------------------------------------------------*/
double ru1;
int i, j, k;
/*--------------------------------------------------------------------
c first fill the lhs for the u-eigenvalue
c-------------------------------------------------------------------*/
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
#pragma omp for
for (k = 0; k <= grid_points[2]-1; k++) {
ru1 = c3c4*rho_i[i][j][k];
cv[k] = ws[i][j][k];
rhos[k] = max(dz4 + con43 * ru1,
max(dz5 + c1c5 * ru1,
max(dzmax + ru1,
dz1)));
}
#pragma omp for
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0][i][j][k] = 0.0;
lhs[1][i][j][k] = -dttz2 * cv[k-1] - dttz1 * rhos[k-1];
lhs[2][i][j][k] = 1.0 + c2dttz1 * rhos[k];
lhs[3][i][j][k] = dttz2 * cv[k+1] - dttz1 * rhos[k+1];
lhs[4][i][j][k] = 0.0;
}
}
}
/*--------------------------------------------------------------------
c add fourth order dissipation
c-------------------------------------------------------------------*/
k = 1;
#pragma omp for nowait
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
lhs[2][i][j][k] = lhs[2][i][j][k] + comz5;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4;
lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz6;
lhs[3][i][j][k+1] = lhs[3][i][j][k+1] - comz4;
lhs[4][i][j][k+1] = lhs[4][i][j][k+1] + comz1;
}
}
#pragma omp for nowait
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 3; k <= grid_points[2]-4; k++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[4][i][j][k] = lhs[4][i][j][k] + comz1;
}
}
}
k = grid_points[2]-3;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
lhs[0][i][j][k] = lhs[0][i][j][k] + comz1;
lhs[1][i][j][k] = lhs[1][i][j][k] - comz4;
lhs[2][i][j][k] = lhs[2][i][j][k] + comz6;
lhs[3][i][j][k] = lhs[3][i][j][k] - comz4;
lhs[0][i][j][k+1] = lhs[0][i][j][k+1] + comz1;
lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4;
lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz5;
}
}
/*--------------------------------------------------------------------
c subsequently, fill the other factors (u+c), (u-c)
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
lhs[0+5][i][j][k] = lhs[0][i][j][k];
lhs[1+5][i][j][k] = lhs[1][i][j][k] -
dttz2 * speed[i][j][k-1];
lhs[2+5][i][j][k] = lhs[2][i][j][k];
lhs[3+5][i][j][k] = lhs[3][i][j][k] +
dttz2 * speed[i][j][k+1];
lhs[4+5][i][j][k] = lhs[4][i][j][k];
lhs[0+10][i][j][k] = lhs[0][i][j][k];
lhs[1+10][i][j][k] = lhs[1][i][j][k] +
dttz2 * speed[i][j][k-1];
lhs[2+10][i][j][k] = lhs[2][i][j][k];
lhs[3+10][i][j][k] = lhs[3][i][j][k] -
dttz2 * speed[i][j][k+1];
lhs[4+10][i][j][k] = lhs[4][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void ninvr(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c block-diagonal matrix-vector multiplication
c-------------------------------------------------------------------*/
int i, j, k;
double r1, r2, r3, r4, r5, t1, t2;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
r1 = rhs[0][i][j][k];
r2 = rhs[1][i][j][k];
r3 = rhs[2][i][j][k];
r4 = rhs[3][i][j][k];
r5 = rhs[4][i][j][k];
t1 = bt * r3;
t2 = 0.5 * ( r4 + r5 );
rhs[0][i][j][k] = -r2;
rhs[1][i][j][k] = r1;
rhs[2][i][j][k] = bt * ( r4 - r5 );
rhs[3][i][j][k] = -t1 + t2;
rhs[4][i][j][k] = t1 + t2;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void pinvr(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c block-diagonal matrix-vector multiplication
c-------------------------------------------------------------------*/
int i, j, k;
double r1, r2, r3, r4, r5, t1, t2;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
r1 = rhs[0][i][j][k];
r2 = rhs[1][i][j][k];
r3 = rhs[2][i][j][k];
r4 = rhs[3][i][j][k];
r5 = rhs[4][i][j][k];
t1 = bt * r1;
t2 = 0.5 * ( r4 + r5 );
rhs[0][i][j][k] = bt * ( r4 - r5 );
rhs[1][i][j][k] = -r3;
rhs[2][i][j][k] = r2;
rhs[3][i][j][k] = -t1 + t2;
rhs[4][i][j][k] = t1 + t2;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void compute_rhs(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
int i, j, k, m;
double aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1,
wijk, wp1, wm1;
/*--------------------------------------------------------------------
c compute the reciprocal of density, and the kinetic energy,
c and the speed of sound.
c-------------------------------------------------------------------*/
#pragma omp for nowait
for (i = 0; i <= grid_points[0]-1; i++) {
for (j = 0; j <= grid_points[1]-1; j++) {
for (k = 0; k <= grid_points[2]-1; k++) {
rho_inv = 1.0/u[0][i][j][k];
rho_i[i][j][k] = rho_inv;
us[i][j][k] = u[1][i][j][k] * rho_inv;
vs[i][j][k] = u[2][i][j][k] * rho_inv;
ws[i][j][k] = u[3][i][j][k] * rho_inv;
square[i][j][k] = 0.5* (u[1][i][j][k]*u[1][i][j][k] +
u[2][i][j][k]*u[2][i][j][k] +
u[3][i][j][k]*u[3][i][j][k] ) * rho_inv;
qs[i][j][k] = square[i][j][k] * rho_inv;
/*--------------------------------------------------------------------
c (do not need speed and ainx until the lhs computation)
c-------------------------------------------------------------------*/
aux = c1c2*rho_inv* (u[4][i][j][k] - square[i][j][k]);
aux = sqrt(aux);
speed[i][j][k] = aux;
ainv[i][j][k] = 1.0/aux;
}
}
}
/*--------------------------------------------------------------------
c copy the exact forcing term to the right hand side; because
c this forcing term is known, we can store it on the whole grid
c including the boundary
c-------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 0; i <= grid_points[0]-1; i++) {
for (j = 0; j <= grid_points[1]-1; j++) {
for (k = 0; k <= grid_points[2]-1; k++) {
rhs[m][i][j][k] = forcing[m][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c compute xi-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
uijk = us[i][j][k];
up1 = us[i+1][j][k];
um1 = us[i-1][j][k];
rhs[0][i][j][k] = rhs[0][i][j][k] + dx1tx1 *
(u[0][i+1][j][k] - 2.0*u[0][i][j][k] +
u[0][i-1][j][k]) -
tx2 * (u[1][i+1][j][k] - u[1][i-1][j][k]);
rhs[1][i][j][k] = rhs[1][i][j][k] + dx2tx1 *
(u[1][i+1][j][k] - 2.0*u[1][i][j][k] +
u[1][i-1][j][k]) +
xxcon2*con43 * (up1 - 2.0*uijk + um1) -
tx2 * (u[1][i+1][j][k]*up1 -
u[1][i-1][j][k]*um1 +
(u[4][i+1][j][k]- square[i+1][j][k]-
u[4][i-1][j][k]+ square[i-1][j][k])*
c2);
rhs[2][i][j][k] = rhs[2][i][j][k] + dx3tx1 *
(u[2][i+1][j][k] - 2.0*u[2][i][j][k] +
u[2][i-1][j][k]) +
xxcon2 * (vs[i+1][j][k] - 2.0*vs[i][j][k] +
vs[i-1][j][k]) -
tx2 * (u[2][i+1][j][k]*up1 -
u[2][i-1][j][k]*um1);
rhs[3][i][j][k] = rhs[3][i][j][k] + dx4tx1 *
(u[3][i+1][j][k] - 2.0*u[3][i][j][k] +
u[3][i-1][j][k]) +
xxcon2 * (ws[i+1][j][k] - 2.0*ws[i][j][k] +
ws[i-1][j][k]) -
tx2 * (u[3][i+1][j][k]*up1 -
u[3][i-1][j][k]*um1);
rhs[4][i][j][k] = rhs[4][i][j][k] + dx5tx1 *
(u[4][i+1][j][k] - 2.0*u[4][i][j][k] +
u[4][i-1][j][k]) +
xxcon3 * (qs[i+1][j][k] - 2.0*qs[i][j][k] +
qs[i-1][j][k]) +
xxcon4 * (up1*up1 - 2.0*uijk*uijk +
um1*um1) +
xxcon5 * (u[4][i+1][j][k]*rho_i[i+1][j][k] -
2.0*u[4][i][j][k]*rho_i[i][j][k] +
u[4][i-1][j][k]*rho_i[i-1][j][k]) -
tx2 * ( (c1*u[4][i+1][j][k] -
c2*square[i+1][j][k])*up1 -
(c1*u[4][i-1][j][k] -
c2*square[i-1][j][k])*um1 );
}
}
}
/*--------------------------------------------------------------------
c add fourth order xi-direction dissipation
c-------------------------------------------------------------------*/
i = 1;
for (m = 0; m < 5; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k]- dssp *
( 5.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] +
u[m][i+2][j][k]);
}
}
}
i = 2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
(-4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] -
4.0*u[m][i+1][j][k] + u[m][i+2][j][k]);
}
}
}
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 3*1; i <= grid_points[0]-3*1-1; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] +
6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] +
u[m][i+2][j][k] );
}
}
}
}
i = grid_points[0]-3;
for (m = 0; m < 5; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] +
6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] );
}
}
}
i = grid_points[0]-2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] +
5.0*u[m][i][j][k] );
}
}
}
#pragma omp barrier
/*--------------------------------------------------------------------
c compute eta-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
vijk = vs[i][j][k];
vp1 = vs[i][j+1][k];
vm1 = vs[i][j-1][k];
rhs[0][i][j][k] = rhs[0][i][j][k] + dy1ty1 *
(u[0][i][j+1][k] - 2.0*u[0][i][j][k] +
u[0][i][j-1][k]) -
ty2 * (u[2][i][j+1][k] - u[2][i][j-1][k]);
rhs[1][i][j][k] = rhs[1][i][j][k] + dy2ty1 *
(u[1][i][j+1][k] - 2.0*u[1][i][j][k] +
u[1][i][j-1][k]) +
yycon2 * (us[i][j+1][k] - 2.0*us[i][j][k] +
us[i][j-1][k]) -
ty2 * (u[1][i][j+1][k]*vp1 -
u[1][i][j-1][k]*vm1);
rhs[2][i][j][k] = rhs[2][i][j][k] + dy3ty1 *
(u[2][i][j+1][k] - 2.0*u[2][i][j][k] +
u[2][i][j-1][k]) +
yycon2*con43 * (vp1 - 2.0*vijk + vm1) -
ty2 * (u[2][i][j+1][k]*vp1 -
u[2][i][j-1][k]*vm1 +
(u[4][i][j+1][k] - square[i][j+1][k] -
u[4][i][j-1][k] + square[i][j-1][k])
*c2);
rhs[3][i][j][k] = rhs[3][i][j][k] + dy4ty1 *
(u[3][i][j+1][k] - 2.0*u[3][i][j][k] +
u[3][i][j-1][k]) +
yycon2 * (ws[i][j+1][k] - 2.0*ws[i][j][k] +
ws[i][j-1][k]) -
ty2 * (u[3][i][j+1][k]*vp1 -
u[3][i][j-1][k]*vm1);
rhs[4][i][j][k] = rhs[4][i][j][k] + dy5ty1 *
(u[4][i][j+1][k] - 2.0*u[4][i][j][k] +
u[4][i][j-1][k]) +
yycon3 * (qs[i][j+1][k] - 2.0*qs[i][j][k] +
qs[i][j-1][k]) +
yycon4 * (vp1*vp1 - 2.0*vijk*vijk +
vm1*vm1) +
yycon5 * (u[4][i][j+1][k]*rho_i[i][j+1][k] -
2.0*u[4][i][j][k]*rho_i[i][j][k] +
u[4][i][j-1][k]*rho_i[i][j-1][k]) -
ty2 * ((c1*u[4][i][j+1][k] -
c2*square[i][j+1][k]) * vp1 -
(c1*u[4][i][j-1][k] -
c2*square[i][j-1][k]) * vm1);
}
}
}
/*--------------------------------------------------------------------
c add fourth order eta-direction dissipation
c-------------------------------------------------------------------*/
j = 1;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k]- dssp *
( 5.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] +
u[m][i][j+2][k]);
}
}
}
j = 2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
(-4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] -
4.0*u[m][i][j+1][k] + u[m][i][j+2][k]);
}
}
}
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 3*1; j <= grid_points[1]-3*1-1; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] +
6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] +
u[m][i][j+2][k] );
}
}
}
}
j = grid_points[1]-3;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] +
6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] );
}
}
}
j = grid_points[1]-2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] +
5.0*u[m][i][j][k] );
}
}
}
#pragma omp barrier
/*--------------------------------------------------------------------
c compute zeta-direction fluxes
c-------------------------------------------------------------------*/
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
wijk = ws[i][j][k];
wp1 = ws[i][j][k+1];
wm1 = ws[i][j][k-1];
rhs[0][i][j][k] = rhs[0][i][j][k] + dz1tz1 *
(u[0][i][j][k+1] - 2.0*u[0][i][j][k] +
u[0][i][j][k-1]) -
tz2 * (u[3][i][j][k+1] - u[3][i][j][k-1]);
rhs[1][i][j][k] = rhs[1][i][j][k] + dz2tz1 *
(u[1][i][j][k+1] - 2.0*u[1][i][j][k] +
u[1][i][j][k-1]) +
zzcon2 * (us[i][j][k+1] - 2.0*us[i][j][k] +
us[i][j][k-1]) -
tz2 * (u[1][i][j][k+1]*wp1 -
u[1][i][j][k-1]*wm1);
rhs[2][i][j][k] = rhs[2][i][j][k] + dz3tz1 *
(u[2][i][j][k+1] - 2.0*u[2][i][j][k] +
u[2][i][j][k-1]) +
zzcon2 * (vs[i][j][k+1] - 2.0*vs[i][j][k] +
vs[i][j][k-1]) -
tz2 * (u[2][i][j][k+1]*wp1 -
u[2][i][j][k-1]*wm1);
rhs[3][i][j][k] = rhs[3][i][j][k] + dz4tz1 *
(u[3][i][j][k+1] - 2.0*u[3][i][j][k] +
u[3][i][j][k-1]) +
zzcon2*con43 * (wp1 - 2.0*wijk + wm1) -
tz2 * (u[3][i][j][k+1]*wp1 -
u[3][i][j][k-1]*wm1 +
(u[4][i][j][k+1] - square[i][j][k+1] -
u[4][i][j][k-1] + square[i][j][k-1])
*c2);
rhs[4][i][j][k] = rhs[4][i][j][k] + dz5tz1 *
(u[4][i][j][k+1] - 2.0*u[4][i][j][k] +
u[4][i][j][k-1]) +
zzcon3 * (qs[i][j][k+1] - 2.0*qs[i][j][k] +
qs[i][j][k-1]) +
zzcon4 * (wp1*wp1 - 2.0*wijk*wijk +
wm1*wm1) +
zzcon5 * (u[4][i][j][k+1]*rho_i[i][j][k+1] -
2.0*u[4][i][j][k]*rho_i[i][j][k] +
u[4][i][j][k-1]*rho_i[i][j][k-1]) -
tz2 * ( (c1*u[4][i][j][k+1] -
c2*square[i][j][k+1])*wp1 -
(c1*u[4][i][j][k-1] -
c2*square[i][j][k-1])*wm1);
}
}
}
/*--------------------------------------------------------------------
c add fourth order zeta-direction dissipation
c-------------------------------------------------------------------*/
k = 1;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k]- dssp *
( 5.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] +
u[m][i][j][k+2]);
}
}
}
k = 2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
(-4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] -
4.0*u[m][i][j][k+1] + u[m][i][j][k+2]);
}
}
}
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 3*1; k <= grid_points[2]-3*1-1; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] +
6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] +
u[m][i][j][k+2] );
}
}
}
}
k = grid_points[2]-3;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] +
6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] );
}
}
}
k = grid_points[2]-2;
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k] - dssp *
( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] +
5.0*u[m][i][j][k] );
}
}
}
for (m = 0; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] * dt;
}
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void set_constants(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
ce[0][0] = 2.0;
ce[1][0] = 0.0;
ce[2][0] = 0.0;
ce[3][0] = 4.0;
ce[4][0] = 5.0;
ce[5][0] = 3.0;
ce[6][0] = 0.5;
ce[7][0] = 0.02;
ce[8][0] = 0.01;
ce[9][0] = 0.03;
ce[10][0] = 0.5;
ce[11][0] = 0.4;
ce[12][0] = 0.3;
ce[0][1] = 1.0;
ce[1][1] = 0.0;
ce[2][1] = 0.0;
ce[3][1] = 0.0;
ce[4][1] = 1.0;
ce[5][1] = 2.0;
ce[6][1] = 3.0;
ce[7][1] = 0.01;
ce[8][1] = 0.03;
ce[9][1] = 0.02;
ce[10][1] = 0.4;
ce[11][1] = 0.3;
ce[12][1] = 0.5;
ce[0][2] = 2.0;
ce[1][2] = 2.0;
ce[2][2] = 0.0;
ce[3][2] = 0.0;
ce[4][2] = 0.0;
ce[5][2] = 2.0;
ce[6][2] = 3.0;
ce[7][2] = 0.04;
ce[8][2] = 0.03;
ce[9][2] = 0.05;
ce[10][2] = 0.3;
ce[11][2] = 0.5;
ce[12][2] = 0.4;
ce[0][3] = 2.0;
ce[1][3] = 2.0;
ce[2][3] = 0.0;
ce[3][3] = 0.0;
ce[4][3] = 0.0;
ce[5][3] = 2.0;
ce[6][3] = 3.0;
ce[7][3] = 0.03;
ce[8][3] = 0.05;
ce[9][3] = 0.04;
ce[10][3] = 0.2;
ce[11][3] = 0.1;
ce[12][3] = 0.3;
ce[0][4] = 5.0;
ce[1][4] = 4.0;
ce[2][4] = 3.0;
ce[3][4] = 2.0;
ce[4][4] = 0.1;
ce[5][4] = 0.4;
ce[6][4] = 0.3;
ce[7][4] = 0.05;
ce[8][4] = 0.04;
ce[9][4] = 0.03;
ce[10][4] = 0.1;
ce[11][4] = 0.3;
ce[12][4] = 0.2;
c1 = 1.4;
c2 = 0.4;
c3 = 0.1;
c4 = 1.0;
c5 = 1.4;
bt = sqrt(0.5);
dnxm1 = 1.0 / (double)(grid_points[0]-1);
dnym1 = 1.0 / (double)(grid_points[1]-1);
dnzm1 = 1.0 / (double)(grid_points[2]-1);
c1c2 = c1 * c2;
c1c5 = c1 * c5;
c3c4 = c3 * c4;
c1345 = c1c5 * c3c4;
conz1 = (1.0-c1c5);
tx1 = 1.0 / (dnxm1 * dnxm1);
tx2 = 1.0 / (2.0 * dnxm1);
tx3 = 1.0 / dnxm1;
ty1 = 1.0 / (dnym1 * dnym1);
ty2 = 1.0 / (2.0 * dnym1);
ty3 = 1.0 / dnym1;
tz1 = 1.0 / (dnzm1 * dnzm1);
tz2 = 1.0 / (2.0 * dnzm1);
tz3 = 1.0 / dnzm1;
dx1 = 0.75;
dx2 = 0.75;
dx3 = 0.75;
dx4 = 0.75;
dx5 = 0.75;
dy1 = 0.75;
dy2 = 0.75;
dy3 = 0.75;
dy4 = 0.75;
dy5 = 0.75;
dz1 = 1.0;
dz2 = 1.0;
dz3 = 1.0;
dz4 = 1.0;
dz5 = 1.0;
dxmax = max(dx3, dx4);
dymax = max(dy2, dy4);
dzmax = max(dz2, dz3);
dssp = 0.25 * max(dx1, max(dy1, dz1) );
c4dssp = 4.0 * dssp;
c5dssp = 5.0 * dssp;
dttx1 = dt*tx1;
dttx2 = dt*tx2;
dtty1 = dt*ty1;
dtty2 = dt*ty2;
dttz1 = dt*tz1;
dttz2 = dt*tz2;
c2dttx1 = 2.0*dttx1;
c2dtty1 = 2.0*dtty1;
c2dttz1 = 2.0*dttz1;
dtdssp = dt*dssp;
comz1 = dtdssp;
comz4 = 4.0*dtdssp;
comz5 = 5.0*dtdssp;
comz6 = 6.0*dtdssp;
c3c4tx3 = c3c4*tx3;
c3c4ty3 = c3c4*ty3;
c3c4tz3 = c3c4*tz3;
dx1tx1 = dx1*tx1;
dx2tx1 = dx2*tx1;
dx3tx1 = dx3*tx1;
dx4tx1 = dx4*tx1;
dx5tx1 = dx5*tx1;
dy1ty1 = dy1*ty1;
dy2ty1 = dy2*ty1;
dy3ty1 = dy3*ty1;
dy4ty1 = dy4*ty1;
dy5ty1 = dy5*ty1;
dz1tz1 = dz1*tz1;
dz2tz1 = dz2*tz1;
dz3tz1 = dz3*tz1;
dz4tz1 = dz4*tz1;
dz5tz1 = dz5*tz1;
c2iv = 2.5;
con43 = 4.0/3.0;
con16 = 1.0/6.0;
xxcon1 = c3c4tx3*con43*tx3;
xxcon2 = c3c4tx3*tx3;
xxcon3 = c3c4tx3*conz1*tx3;
xxcon4 = c3c4tx3*con16*tx3;
xxcon5 = c3c4tx3*c1c5*tx3;
yycon1 = c3c4ty3*con43*ty3;
yycon2 = c3c4ty3*ty3;
yycon3 = c3c4ty3*conz1*ty3;
yycon4 = c3c4ty3*con16*ty3;
yycon5 = c3c4ty3*c1c5*ty3;
zzcon1 = c3c4tz3*con43*tz3;
zzcon2 = c3c4tz3*tz3;
zzcon3 = c3c4tz3*conz1*tz3;
zzcon4 = c3c4tz3*con16*tz3;
zzcon5 = c3c4tz3*c1c5*tz3;
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void txinvr(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c block-diagonal matrix-vector multiplication
--------------------------------------------------------------------*/
int i, j, k;
double t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3,
r4, r5, ac2inv;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
ru1 = rho_i[i][j][k];
uu = us[i][j][k];
vv = vs[i][j][k];
ww = ws[i][j][k];
ac = speed[i][j][k];
ac2inv = ainv[i][j][k]*ainv[i][j][k];
r1 = rhs[0][i][j][k];
r2 = rhs[1][i][j][k];
r3 = rhs[2][i][j][k];
r4 = rhs[3][i][j][k];
r5 = rhs[4][i][j][k];
t1 = c2 * ac2inv * ( qs[i][j][k]*r1 - uu*r2 -
vv*r3 - ww*r4 + r5 );
t2 = bt * ru1 * ( uu * r1 - r2 );
t3 = ( bt * ru1 * ac ) * t1;
rhs[0][i][j][k] = r1 - t1;
rhs[1][i][j][k] = - ru1 * ( ww*r1 - r4 );
rhs[2][i][j][k] = ru1 * ( vv*r1 - r3 );
rhs[3][i][j][k] = - t2 + t3;
rhs[4][i][j][k] = t2 + t3;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void tzetar(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c block-diagonal matrix-vector multiplication
c-------------------------------------------------------------------*/
int i, j, k;
double t1, t2, t3, ac, xvel, yvel, zvel, r1, r2, r3,
r4, r5, btuz, acinv, ac2u, uzik1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
xvel = us[i][j][k];
yvel = vs[i][j][k];
zvel = ws[i][j][k];
ac = speed[i][j][k];
acinv = ainv[i][j][k];
ac2u = ac*ac;
r1 = rhs[0][i][j][k];
r2 = rhs[1][i][j][k];
r3 = rhs[2][i][j][k];
r4 = rhs[3][i][j][k];
r5 = rhs[4][i][j][k];
uzik1 = u[0][i][j][k];
btuz = bt * uzik1;
t1 = btuz*acinv * (r4 + r5);
t2 = r3 + t1;
t3 = btuz * (r4 - r5);
rhs[0][i][j][k] = t2;
rhs[1][i][j][k] = -uzik1*r2 + xvel*t2;
rhs[2][i][j][k] = uzik1*r1 + yvel*t2;
rhs[3][i][j][k] = zvel*t2 + t3;
rhs[4][i][j][k] = uzik1*(-xvel*r2 + yvel*r1) +
qs[i][j][k]*t2 + c2iv*ac2u*t1 + zvel*t3;
}
}
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void verify(int no_time_steps, char *cclass, boolean *verified) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c verification routine
--------------------------------------------------------------------*/
double xcrref[5],xceref[5],xcrdif[5],xcedif[5],
epsilon, xce[5], xcr[5], dtref;
int m;
/*--------------------------------------------------------------------
c tolerance level
--------------------------------------------------------------------*/
epsilon = 1.0e-08;
/*--------------------------------------------------------------------
c compute the error norm and the residual norm, and exit if not printing
--------------------------------------------------------------------*/
error_norm(xce);
compute_rhs();
rhs_norm(xcr);
for (m = 0; m < 5; m++) {
xcr[m] = xcr[m] / dt;
}
*cclass = 'U';
*verified = TRUE;
for (m = 0; m < 5; m++) {
xcrref[m] = 1.0;
xceref[m] = 1.0;
}
/*--------------------------------------------------------------------
c reference data for 12X12X12 grids after 100 time steps, with DT = 1.50d-02
--------------------------------------------------------------------*/
if ( grid_points[0] == 12 &&
grid_points[1] == 12 &&
grid_points[2] == 12 &&
no_time_steps == 100) {
*cclass = 'S';
dtref = 1.5e-2;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
--------------------------------------------------------------------*/
xcrref[0] = 2.7470315451339479e-02;
xcrref[1] = 1.0360746705285417e-02;
xcrref[2] = 1.6235745065095532e-02;
xcrref[3] = 1.5840557224455615e-02;
xcrref[4] = 3.4849040609362460e-02;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
--------------------------------------------------------------------*/
xceref[0] = 2.7289258557377227e-05;
xceref[1] = 1.0364446640837285e-05;
xceref[2] = 1.6154798287166471e-05;
xceref[3] = 1.5750704994480102e-05;
xceref[4] = 3.4177666183390531e-05;
/*--------------------------------------------------------------------
c reference data for 36X36X36 grids after 400 time steps, with DT = 1.5d-03
--------------------------------------------------------------------*/
} else if (grid_points[0] == 36 &&
grid_points[1] == 36 &&
grid_points[2] == 36 &&
no_time_steps == 400) {
*cclass = 'W';
dtref = 1.5e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
--------------------------------------------------------------------*/
xcrref[0] = 0.1893253733584e-02;
xcrref[1] = 0.1717075447775e-03;
xcrref[2] = 0.2778153350936e-03;
xcrref[3] = 0.2887475409984e-03;
xcrref[4] = 0.3143611161242e-02;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
--------------------------------------------------------------------*/
xceref[0] = 0.7542088599534e-04;
xceref[1] = 0.6512852253086e-05;
xceref[2] = 0.1049092285688e-04;
xceref[3] = 0.1128838671535e-04;
xceref[4] = 0.1212845639773e-03;
/*--------------------------------------------------------------------
c reference data for 64X64X64 grids after 400 time steps, with DT = 1.5d-03
--------------------------------------------------------------------*/
} else if (grid_points[0] == 64 &&
grid_points[1] == 64 &&
grid_points[2] == 64 &&
no_time_steps == 400 ) {
*cclass = 'A';
dtref = 1.5e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
--------------------------------------------------------------------*/
xcrref[0] = 2.4799822399300195;
xcrref[1] = 1.1276337964368832;
xcrref[2] = 1.5028977888770491;
xcrref[3] = 1.4217816211695179;
xcrref[4] = 2.1292113035138280;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
--------------------------------------------------------------------*/
xceref[0] = 1.0900140297820550e-04;
xceref[1] = 3.7343951769282091e-05;
xceref[2] = 5.0092785406541633e-05;
xceref[3] = 4.7671093939528255e-05;
xceref[4] = 1.3621613399213001e-04;
/*--------------------------------------------------------------------
c reference data for 102X102X102 grids after 400 time steps,
c with DT = 1.0d-03
--------------------------------------------------------------------*/
} else if (grid_points[0] == 102 &&
grid_points[1] == 102 &&
grid_points[2] == 102 &&
no_time_steps == 400) {
*cclass = 'B';
dtref = 1.0e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
--------------------------------------------------------------------*/
xcrref[0] = 0.6903293579998e+02;
xcrref[1] = 0.3095134488084e+02;
xcrref[2] = 0.4103336647017e+02;
xcrref[3] = 0.3864769009604e+02;
xcrref[4] = 0.5643482272596e+02;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
--------------------------------------------------------------------*/
xceref[0] = 0.9810006190188e-02;
xceref[1] = 0.1022827905670e-02;
xceref[2] = 0.1720597911692e-02;
xceref[3] = 0.1694479428231e-02;
xceref[4] = 0.1847456263981e-01;
/*--------------------------------------------------------------------
c reference data for 162X162X162 grids after 400 time steps,
c with DT = 0.67d-03
--------------------------------------------------------------------*/
} else if (grid_points[0] == 162 &&
grid_points[1] == 162 &&
grid_points[2] == 162 &&
no_time_steps == 400) {
*cclass = 'C';
dtref = 0.67e-3;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of residual.
--------------------------------------------------------------------*/
xcrref[0] = 0.5881691581829e+03;
xcrref[1] = 0.2454417603569e+03;
xcrref[2] = 0.3293829191851e+03;
xcrref[3] = 0.3081924971891e+03;
xcrref[4] = 0.4597223799176e+03;
/*--------------------------------------------------------------------
c Reference values of RMS-norms of solution error.
--------------------------------------------------------------------*/
xceref[0] = 0.2598120500183e+00;
xceref[1] = 0.2590888922315e-01;
xceref[2] = 0.5132886416320e-01;
xceref[3] = 0.4806073419454e-01;
xceref[4] = 0.5483377491301e+00;
} else {
*verified = FALSE;
}
/*--------------------------------------------------------------------
c verification test for residuals if gridsize is either 12X12X12 or
c 64X64X64 or 102X102X102 or 162X162X162
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c Compute the difference of solution values and the known reference values.
--------------------------------------------------------------------*/
for (m = 0; m < 5; m++) {
xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]) ;
xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]);
}
/*--------------------------------------------------------------------
c Output the comparison of computed results to known cases.
--------------------------------------------------------------------*/
if (*cclass != 'U') {
printf(" Verification being performed for cclass %1c\n", *cclass);
printf(" accuracy setting for epsilon = %20.13e\n", epsilon);
if (fabs(dt-dtref) > epsilon) {
*verified = FALSE;
*cclass = 'U';
printf(" DT does not match the reference value of %15.8e\n", dtref);
}
} else {
printf(" Unknown cclass\n");
}
if (*cclass != 'U') {
printf(" Comparison of RMS-norms of residual\n");
} else {
printf(" RMS-norms of residual\n");
}
for (m = 0; m < 5; m++) {
if (*cclass == 'U') {
printf(" %2d%20.13e\n", m, xcr[m]);
} else if (xcrdif[m] > epsilon) {
*verified = FALSE;
printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n",
m,xcr[m],xcrref[m],xcrdif[m]);
} else {
printf(" %2d%20.13e%20.13e%20.13e\n",
m,xcr[m],xcrref[m],xcrdif[m]);
}
}
if (*cclass != 'U') {
printf(" Comparison of RMS-norms of solution error\n");
} else {
printf(" RMS-norms of solution error\n");
}
for (m = 0; m < 5; m++) {
if (*cclass == 'U') {
printf(" %2d%20.13e\n", m, xce[m]);
} else if (xcedif[m] > epsilon) {
*verified = FALSE;
printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n",
m,xce[m],xceref[m],xcedif[m]);
} else {
printf(" %2d%20.13e%20.13e%20.13e\n",
m,xce[m],xceref[m],xcedif[m]);
}
}
if (*cclass == 'U') {
printf(" No reference values provided\n");
printf(" No verification performed\n");
} else if (*verified) {
printf(" Verification Successful\n");
} else {
printf(" Verification failed\n");
}
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void x_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function performs the solution of the approximate factorization
c step in the x-direction for all five matrix components
c simultaneously. The Thomas algorithm is employed to solve the
c systems for the x-lines. Boundary conditions are non-periodic
--------------------------------------------------------------------*/
int i, j, k, n, i1, i2, m;
double fac1, fac2;
/*--------------------------------------------------------------------
c FORWARD ELIMINATION
--------------------------------------------------------------------*/
lhsx();
/*--------------------------------------------------------------------
c perform the Thomas algorithm; first, FORWARD ELIMINATION
--------------------------------------------------------------------*/
n = 0;
for (i = 0; i <= grid_points[0]-3; i++) {
i1 = i + 1;
i2 = i + 2;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+3][i][j][k];
lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i1][j][k] = rhs[m][i1][j][k] -
lhs[n+1][i1][j][k]*rhs[m][i][j][k];
}
lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] -
lhs[n+0][i2][j][k]*lhs[n+3][i][j][k];
lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] -
lhs[n+0][i2][j][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i2][j][k] = rhs[m][i2][j][k] -
lhs[n+0][i2][j][k]*rhs[m][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c The last two rows in this grid block are a bit different,
c since they do not have two more rows available for the
c elimination of off-diagonal entries
--------------------------------------------------------------------*/
i = grid_points[0]-2;
i1 = grid_points[0]-1;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1.0/lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+3][i][j][k];
lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i1][j][k] = rhs[m][i1][j][k] -
lhs[n+1][i1][j][k]*rhs[m][i][j][k];
}
/*--------------------------------------------------------------------
c scale the last row immediately
--------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i1][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k];
}
}
}
/*--------------------------------------------------------------------
c do the u+c and the u-c factors
--------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
for (i = 0; i <= grid_points[0]-3; i++) {
i1 = i + 1;
i2 = i + 2;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+3][i][j][k];
lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+4][i][j][k];
rhs[m][i1][j][k] = rhs[m][i1][j][k] -
lhs[n+1][i1][j][k]*rhs[m][i][j][k];
lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] -
lhs[n+0][i2][j][k]*lhs[n+3][i][j][k];
lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] -
lhs[n+0][i2][j][k]*lhs[n+4][i][j][k];
rhs[m][i2][j][k] = rhs[m][i2][j][k] -
lhs[n+0][i2][j][k]*rhs[m][i][j][k];
}
}
}
/*--------------------------------------------------------------------
c And again the last two rows separately
--------------------------------------------------------------------*/
i = grid_points[0]-2;
i1 = grid_points[0]-1;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+3][i][j][k];
lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] -
lhs[n+1][i1][j][k]*lhs[n+4][i][j][k];
rhs[m][i1][j][k] = rhs[m][i1][j][k] -
lhs[n+1][i1][j][k]*rhs[m][i][j][k];
/*--------------------------------------------------------------------
c Scale the last row immediately
--------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i1][j][k];
rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k];
}
}
}
/*--------------------------------------------------------------------
c BACKSUBSTITUTION
--------------------------------------------------------------------*/
i = grid_points[0]-2;
i1 = grid_points[0]-1;
n = 0;
for (m = 0; m < 3; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i1][j][k];
}
}
}
for (m = 3; m < 5; m++) {
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
n = (m-3+1)*5;
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i1][j][k];
}
}
}
/*--------------------------------------------------------------------
c The first three factors
--------------------------------------------------------------------*/
n = 0;
for (i = grid_points[0]-3; i >= 0; i--) {
i1 = i + 1;
i2 = i + 2;
#pragma omp for
for (m = 0; m < 3; m++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i1][j][k] -
lhs[n+4][i][j][k]*rhs[m][i2][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c And the remaining two
--------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
for (i = grid_points[0]-3; i >= 0; i--) {
i1 = i + 1;
i2 = i + 2;
#pragma omp for
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i1][j][k] -
lhs[n+4][i][j][k]*rhs[m][i2][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c Do the block-diagonal inversion
--------------------------------------------------------------------*/
ninvr();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void y_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function performs the solution of the approximate factorization
c step in the y-direction for all five matrix components
c simultaneously. The Thomas algorithm is employed to solve the
c systems for the y-lines. Boundary conditions are non-periodic
--------------------------------------------------------------------*/
int i, j, k, n, j1, j2, m;
double fac1, fac2;
/*--------------------------------------------------------------------
c FORWARD ELIMINATION
--------------------------------------------------------------------*/
lhsy();
n = 0;
for (j = 0; j <= grid_points[1]-3; j++) {
j1 = j + 1;
j2 = j + 2;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+3][i][j][k];
lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j1][k] = rhs[m][i][j1][k] -
lhs[n+1][i][j1][k]*rhs[m][i][j][k];
}
lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] -
lhs[n+0][i][j2][k]*lhs[n+3][i][j][k];
lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] -
lhs[n+0][i][j2][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j2][k] = rhs[m][i][j2][k] -
lhs[n+0][i][j2][k]*rhs[m][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c The last two rows in this grid block are a bit different,
c since they do not have two more rows available for the
c elimination of off-diagonal entries
--------------------------------------------------------------------*/
j = grid_points[1]-2;
j1 = grid_points[1]-1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+3][i][j][k];
lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j1][k] = rhs[m][i][j1][k] -
lhs[n+1][i][j1][k]*rhs[m][i][j][k];
}
/*--------------------------------------------------------------------
c scale the last row immediately
--------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i][j1][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k];
}
}
}
/*--------------------------------------------------------------------
c do the u+c and the u-c factors
--------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
for (j = 0; j <= grid_points[1]-3; j++) {
j1 = j + 1;
j2 = j + 2;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+3][i][j][k];
lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+4][i][j][k];
rhs[m][i][j1][k] = rhs[m][i][j1][k] -
lhs[n+1][i][j1][k]*rhs[m][i][j][k];
lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] -
lhs[n+0][i][j2][k]*lhs[n+3][i][j][k];
lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] -
lhs[n+0][i][j2][k]*lhs[n+4][i][j][k];
rhs[m][i][j2][k] = rhs[m][i][j2][k] -
lhs[n+0][i][j2][k]*rhs[m][i][j][k];
}
}
}
/*--------------------------------------------------------------------
c And again the last two rows separately
--------------------------------------------------------------------*/
j = grid_points[1]-2;
j1 = grid_points[1]-1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+3][i][j][k];
lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] -
lhs[n+1][i][j1][k]*lhs[n+4][i][j][k];
rhs[m][i][j1][k] = rhs[m][i][j1][k] -
lhs[n+1][i][j1][k]*rhs[m][i][j][k];
/*--------------------------------------------------------------------
c Scale the last row immediately
--------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i][j1][k];
rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k];
}
}
}
/*--------------------------------------------------------------------
c BACKSUBSTITUTION
--------------------------------------------------------------------*/
j = grid_points[1]-2;
j1 = grid_points[1]-1;
n = 0;
for (m = 0; m < 3; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j1][k];
}
}
}
for (m = 3; m < 5; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
n = (m-3+1)*5;
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j1][k];
}
}
}
/*--------------------------------------------------------------------
c The first three factors
--------------------------------------------------------------------*/
n = 0;
for (m = 0; m < 3; m++) {
for (j = grid_points[1]-3; j >= 0; j--) {
j1 = j + 1;
j2 = j + 2;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j1][k] -
lhs[n+4][i][j][k]*rhs[m][i][j2][k];
}
}
}
}
/*--------------------------------------------------------------------
c And the remaining two
--------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
for (j = grid_points[1]-3; j >= 0; j--) {
j1 = j + 1;
j2 = j1 + 1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (k = 1; k <= grid_points[2]-2; k++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j1][k] -
lhs[n+4][i][j][k]*rhs[m][i][j2][k];
}
}
}
}
pinvr();
}
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
static void z_solve(void) {
/*--------------------------------------------------------------------
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c this function performs the solution of the approximate factorization
c step in the z-direction for all five matrix components
c simultaneously. The Thomas algorithm is employed to solve the
c systems for the z-lines. Boundary conditions are non-periodic
c-------------------------------------------------------------------*/
int i, j, k, n, k1, k2, m;
double fac1, fac2;
/*--------------------------------------------------------------------
c FORWARD ELIMINATION
c-------------------------------------------------------------------*/
lhsz();
n = 0;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 0; k <= grid_points[2]-3; k++) {
k1 = k + 1;
k2 = k + 2;
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+3][i][j][k];
lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k1] = rhs[m][i][j][k1] -
lhs[n+1][i][j][k1]*rhs[m][i][j][k];
}
lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] -
lhs[n+0][i][j][k2]*lhs[n+3][i][j][k];
lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] -
lhs[n+0][i][j][k2]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k2] = rhs[m][i][j][k2] -
lhs[n+0][i][j][k2]*rhs[m][i][j][k];
}
}
}
}
/*--------------------------------------------------------------------
c The last two rows in this grid block are a bit different,
c since they do not have two more rows available for the
c elimination of off-diagonal entries
c-------------------------------------------------------------------*/
k = grid_points[2]-2;
k1 = grid_points[2]-1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
}
lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+3][i][j][k];
lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+4][i][j][k];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k1] = rhs[m][i][j][k1] -
lhs[n+1][i][j][k1]*rhs[m][i][j][k];
}
/*--------------------------------------------------------------------
c scale the last row immediately
c-------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i][j][k1];
for (m = 0; m < 3; m++) {
rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1];
}
}
}
/*--------------------------------------------------------------------
c do the u+c and the u-c factors
c-------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = 0; k <= grid_points[2]-3; k++) {
k1 = k + 1;
k2 = k + 2;
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+3][i][j][k];
lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+4][i][j][k];
rhs[m][i][j][k1] = rhs[m][i][j][k1] -
lhs[n+1][i][j][k1]*rhs[m][i][j][k];
lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] -
lhs[n+0][i][j][k2]*lhs[n+3][i][j][k];
lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] -
lhs[n+0][i][j][k2]*lhs[n+4][i][j][k];
rhs[m][i][j][k2] = rhs[m][i][j][k2] -
lhs[n+0][i][j][k2]*rhs[m][i][j][k];
}
}
}
/*--------------------------------------------------------------------
c And again the last two rows separately
c-------------------------------------------------------------------*/
k = grid_points[2]-2;
k1 = grid_points[2]-1;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
fac1 = 1./lhs[n+2][i][j][k];
lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k];
lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k];
rhs[m][i][j][k] = fac1*rhs[m][i][j][k];
lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+3][i][j][k];
lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] -
lhs[n+1][i][j][k1]*lhs[n+4][i][j][k];
rhs[m][i][j][k1] = rhs[m][i][j][k1] -
lhs[n+1][i][j][k1]*rhs[m][i][j][k];
/*--------------------------------------------------------------------
c Scale the last row immediately (some of this is overkill
c if this is the last cell)
c-------------------------------------------------------------------*/
fac2 = 1./lhs[n+2][i][j][k1];
rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1];
}
}
}
/*--------------------------------------------------------------------
c BACKSUBSTITUTION
c-------------------------------------------------------------------*/
k = grid_points[2]-2;
k1 = grid_points[2]-1;
n = 0;
for (m = 0; m < 3; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j][k1];
}
}
}
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j][k1];
}
}
}
/*--------------------------------------------------------------------
c Whether or not this is the last processor, we always have
c to complete the back-substitution
c-------------------------------------------------------------------*/
/*--------------------------------------------------------------------
c The first three factors
c-------------------------------------------------------------------*/
n = 0;
for (m = 0; m < 3; m++) {
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = grid_points[2]-3; k >= 0; k--) {
k1 = k + 1;
k2 = k + 2;
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j][k1] -
lhs[n+4][i][j][k]*rhs[m][i][j][k2];
}
}
}
}
/*--------------------------------------------------------------------
c And the remaining two
c-------------------------------------------------------------------*/
for (m = 3; m < 5; m++) {
n = (m-3+1)*5;
#pragma omp for
for (i = 1; i <= grid_points[0]-2; i++) {
for (j = 1; j <= grid_points[1]-2; j++) {
for (k = grid_points[2]-3; k >= 0; k--) {
k1 = k + 1;
k2 = k + 2;
rhs[m][i][j][k] = rhs[m][i][j][k] -
lhs[n+3][i][j][k]*rhs[m][i][j][k1] -
lhs[n+4][i][j][k]*rhs[m][i][j][k2];
}
}
}
}
tzetar();
}
/* cat ./common/c_print_results.c */
/*****************************************************************/
/****** C _ P R I N T _ R E S U L T S ******/
/*****************************************************************/
void c_print_results( char *name,
char cclass,
int n1,
int n2,
int n3,
int niter,
int nthreads,
double t,
double mops,
char *optype,
int passed_verification,
char *npbversion,
char *compiletime,
char *cc,
char *clink,
char *c_lib,
char *c_inc,
char *cflags,
char *clinkflags,
char *rand)
{
char *evalue="1000";
printf( "\n\n %s Benchmark Completed\n", name );
printf( " Class = %c\n", cclass );
if( n2 == 0 && n3 == 0 )
printf( " Size = %12d\n", n1 ); /* as in IS */
else
printf( " Size = %3dx%3dx%3d\n", n1,n2,n3 );
printf( " Iterations = %12d\n", niter );
printf( " Threads = %12d\n", nthreads );
printf( " Time in seconds = %12.2f\n", t );
printf( " Mop/s total = %12.2f\n", mops );
printf( " Operation type = %24s\n", optype);
if( passed_verification )
printf( " Verification = SUCCESSFUL\n" );
else
printf( " Verification = UNSUCCESSFUL\n" );
printf( " Version = %12s\n", npbversion );
printf( " Compile date = %12s\n", compiletime );
printf( "\n Compile options:\n" );
printf( " CC = %s\n", cc );
printf( " CLINK = %s\n", clink );
printf( " C_LIB = %s\n", c_lib );
printf( " C_INC = %s\n", c_inc );
printf( " CFLAGS = %s\n", cflags );
printf( " CLINKFLAGS = %s\n", clinkflags );
printf( " RAND = %s\n", rand );
#ifdef SMP
evalue = getenv("MP_SET_NUMTHREADS");
printf( " MULTICPUS = %s\n", evalue );
#endif
/* printf( "\n\n" );
printf( " Please send the results of this run to:\n\n" );
printf( " NPB Development Team\n" );
printf( " Internet: npb@nas.nasa.gov\n \n" );
printf( " If email is not available, send this to:\n\n" );
printf( " MS T27A-1\n" );
printf( " NASA Ames Research Center\n" );
printf( " Moffett Field, CA 94035-1000\n\n" );
printf( " Fax: 415-604-3957\n\n" );*/
}
/*
cat ./common/c_timers.c
*/
/*
#include "wtime.h"
#if defined(IBM)
#define wtime wtime
#elif defined(CRAY)
#define wtime WTIME
#else
#define wtime wtime_
#endif
*/
/* Prototype */
void wtime( double * );
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time( void )
{
double t;
wtime( &t );
return( t );
}
double start[64], elapsed[64];
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear( int n )
{
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start( int n )
{
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop( int n )
{
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read( int n )
{
return( elapsed[n] );
}
void wtime(double *t)
{
static int sec = -1;
struct timeval tv;
// gettimeofday(&tv, (void *)0);
gettimeofday(&tv, (struct timezone *)0);
if (sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec;
}
// common/c_randdp.c
/*
*/
#if defined(USE_POW)
#define r23 pow(0.5, 23.0)
#define r46 (r23*r23)
#define t23 pow(2.0, 23.0)
#define t46 (t23*t23)
#else
#define r23 (0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5)
#define r46 (r23*r23)
#define t23 (2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0)
#define t46 (t23*t23)
#endif
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
double randlc (double *x, double a) {
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
/*c---------------------------------------------------------------------
c
c This routine returns a uniform pseudorandom double precision number in the
c range (0, 1) by using the linear congruential generator
c
c x_{k+1} = a x_k (mod 2^46)
c
c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
c before repeating. The argument A is the same as 'a' in the above formula,
c and X is the same as x_0. A and X must be odd double precision integers
c in the range (1, 2^46). The returned value RANDLC is normalized to be
c between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain
c the new seed x_1, so that subsequent calls to RANDLC using the same
c arguments will generate a continuous sequence.
c
c This routine should produce the same results on any computer with at least
c 48 mantissa bits in double precision floating point data. On 64 bit
c systems, double precision should be disabled.
c
c David H. Bailey October 26, 1990
c
c---------------------------------------------------------------------*/
double t1,t2,t3,t4,a1,a2,x1,x2,z;
/*c---------------------------------------------------------------------
c Break A into two parts such that A = 2^23 * A1 + A2.
c---------------------------------------------------------------------*/
t1 = r23 * a;
a1 = (int)t1;
a2 = a - t23 * a1;
/*c---------------------------------------------------------------------
c Break X into two parts such that X = 2^23 * X1 + X2, compute
c Z = A1 * X2 + A2 * X1 (mod 2^23), and then
c X = 2^23 * Z + A2 * X2 (mod 2^46).
c---------------------------------------------------------------------*/
t1 = r23 * (*x);
x1 = (int)t1;
x2 = (*x) - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int)(r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int)(r46 * t3);
(*x) = t3 - t46 * t4;
return (r46 * (*x));
}
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
void vranlc (int n, double *x_seed, double a, double* y) {
/* void vranlc (int n, double *x_seed, double a, double y[]) { */
/*c---------------------------------------------------------------------
c---------------------------------------------------------------------*/
/*c---------------------------------------------------------------------
c
c This routine generates N uniform pseudorandom double precision numbers in
c the range (0, 1) by using the linear congruential generator
c
c x_{k+1} = a x_k (mod 2^46)
c
c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
c before repeating. The argument A is the same as 'a' in the above formula,
c and X is the same as x_0. A and X must be odd double precision integers
c in the range (1, 2^46). The N results are placed in Y and are normalized
c to be between 0 and 1. X is updated to contain the new seed, so that
c subsequent calls to VRANLC using the same arguments will generate a
c continuous sequence. If N is zero, only initialization is performed, and
c the variables X, A and Y are ignored.
c
c This routine is the standard version designed for scalar or RISC systems.
c However, it should produce the same results on any single processor
c computer with at least 48 mantissa bits in double precision floating point
c data. On 64 bit systems, double precision should be disabled.
c
c---------------------------------------------------------------------*/
int i;
double x,t1,t2,t3,t4,a1,a2,x1,x2,z;
/*c---------------------------------------------------------------------
c Break A into two parts such that A = 2^23 * A1 + A2.
c---------------------------------------------------------------------*/
t1 = r23 * a;
a1 = (int)t1;
a2 = a - t23 * a1;
x = *x_seed;
/*c---------------------------------------------------------------------
c Generate N results. This loop is not vectorizable.
c---------------------------------------------------------------------*/
for (i = 1; i <= n; i++) {
/*c---------------------------------------------------------------------
c Break X into two parts such that X = 2^23 * X1 + X2, compute
c Z = A1 * X2 + A2 * X1 (mod 2^23), and then
c X = 2^23 * Z + A2 * X2 (mod 2^46).
c---------------------------------------------------------------------*/
t1 = r23 * x;
x1 = (int)t1;
x2 = x - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int)(r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int)(r46 * t3);
x = t3 - t46 * t4;
y[i] = r46 * x;
}
*x_seed = x;
}
|
GB_binop__isle_fp32.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__isle_fp32
// A.*B function (eWiseMult): GB_AemultB__isle_fp32
// A*D function (colscale): GB_AxD__isle_fp32
// D*A function (rowscale): GB_DxB__isle_fp32
// C+=B function (dense accum): GB_Cdense_accumB__isle_fp32
// C+=b function (dense accum): GB_Cdense_accumb__isle_fp32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isle_fp32
// C=scalar+B GB_bind1st__isle_fp32
// C=scalar+B' GB_bind1st_tran__isle_fp32
// C=A+scalar GB_bind2nd__isle_fp32
// C=A'+scalar GB_bind2nd_tran__isle_fp32
// C type: float
// A type: float
// B,b type: float
// 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) \
float aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
float bij = Bx [pB]
// 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) \
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) ;
// 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_ISLE || GxB_NO_FP32 || GxB_NO_ISLE_FP32)
//------------------------------------------------------------------------------
// 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__isle_fp32
(
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__isle_fp32
(
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__isle_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__isle_fp32
(
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
float *GB_RESTRICT Cx = (float *) 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__isle_fp32
(
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
float *GB_RESTRICT Cx = (float *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#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__isle_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 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__isle_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 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__isle_fp32
(
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
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
float 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__isle_fp32
(
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 ;
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 = 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) \
{ \
float aij = Ax [pA] ; \
Cx [pC] = (x <= aij) ; \
}
GrB_Info GB_bind1st_tran__isle_fp32
(
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 \
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 = Ax [pA] ; \
Cx [pC] = (aij <= y) ; \
}
GrB_Info GB_bind2nd_tran__isle_fp32
(
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
float y = (*((const float *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
j3d7pt.gold.h | #include <cstring>
using std::memcpy;
void jacobi_gold(double *fout, const double *fin, double h2inv, double a, double b, int L, int M, int N) {
double (*out)[M][N] = (double (*)[M][N]) fout;
double (*in)[M][N] = (double (*)[M][N]) fin;
auto ftemp1 = new double[L * M * N];
auto ftemp2 = new double[L * M * N];
memset(ftemp1, 0, sizeof(double)*L*M*N);
memset(ftemp2, 0, sizeof(double)*L*M*N);
double (*temp1)[M][N] = (double (*)[M][N]) ftemp1;
double (*temp2)[M][N] = (double (*)[M][N]) ftemp2;
memcpy(ftemp1, fin, sizeof(double)*L*M*N);
double c = b * h2inv;
for (int t = 0; t < 4; t++) {
#pragma omp parallel for
for (int k = 1; k < L - 1; ++k) {
for (int j = 1; j < M - 1; ++j) {
for (int i = 1; i < N - 1; ++i) {
if (!(t%2)) {
temp2[k][j][i] = a*temp1[k][j][i] - c*temp1[k][j][i+1]
+ c*temp1[k][j][i-1]
+ c*temp1[k][j+1][i]
+ c*temp1[k][j-1][i]
+ c*temp1[k+1][j][i]
+ c*temp1[k-1][j][i]
- c*temp1[k][j][i]*6.0;
} else {
temp1[k][j][i] = a*temp2[k][j][i] - c*temp2[k][j][i+1]
+ c*temp2[k][j][i-1]
+ c*temp2[k][j+1][i]
+ c*temp2[k][j-1][i]
+ c*temp2[k+1][j][i]
+ c*temp2[k-1][j][i]
- c*temp2[k][j][i]*6.0;
}
}
}
}
}
memcpy(fout, ftemp1, sizeof(double)*L*M*N);
}
|
aho.c | /*
* author: alessandro bitocchi
*/
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef _OPENMP
# include <omp.h>
#endif
#include "../lib/include/ahocorasick.h"
#include "../lib/include/reader.h"
void callback_match_total(void *arg, struct aho_match_t* m){
long long int* match_total = (long long int*)arg;
(*match_total)++;
}
int main(int argc, char** argv){
struct ahocorasick aho;
long long int match_total = 0;
unsigned int total_match = 0;
struct timespec begin, end;
int thread_count = 2;
aho_init(&aho);
printf("AHO | ");
if (argv[1] == NULL || argv[2] == NULL){
perror("ERROR: Input command\n");
return 1;
}
if (argv[3] != NULL)
thread_count = atoi(argv[3]);
stringList* strings = read_from_file(argv[1]);
stringList* packets = read_from_file(argv[2]);
//int id[strings->len] = {0};
//#pragma omp parallel for num_threads(thread_count)
for (int i = 0; i < strings->len; i++)
aho_add_match_text(&aho, strings->array[i],
strlen(strings->array[i]));
aho_create_trie(&aho);
aho_register_match_callback(&aho, callback_match_total, &match_total);
clock_gettime(CLOCK_REALTIME, &begin);
#pragma omp parallel for num_threads(thread_count) \
reduction(+: total_match)
for (int i = 0; i < packets->len; i++)
total_match += aho_findtext(&aho, packets->array[i], strlen(packets->array[i]));
clock_gettime(CLOCK_REALTIME, &end);
//printf("total match:%u\n", aho_findtext(&aho, "PROVAstringaSCRIVENDOqUDPualcUDosaPDUPDkicaom",
// strlen("PROVAstringaSCRIVENDOqUDPualcUDosaPDUPDkicaom")));
aho_destroy(&aho);
long seconds = end.tv_sec - begin.tv_sec;
long nanoseconds = end.tv_nsec - begin.tv_nsec;
double elapsed = seconds + nanoseconds*1e-9;
printf("total match: %d | ", total_match);
printf("Elapsed time: %f seconds\n", elapsed);
freeStringList(strings);
freeStringList(packets);
return 0;
}
|
Par-17-ParForLoopNoWaitBarrier.c |
int main(int argc, char **argv) {
int a[4] = {1,2,3,4};
#pragma omp parallel
{
#pragma omp for nowait
for (int i = 0; i < 4; ++i) {
a[i] = 3*a[i];
}
#pragma omp barrier
#pragma omp for nowait
for (int i = 0; i < 4; ++i) {
a[i] += a[i];
}
}
return 0;
}
|
GB_binop__ge_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 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__ge_uint64)
// A.*B function (eWiseMult): GB (_AemultB_08__ge_uint64)
// A.*B function (eWiseMult): GB (_AemultB_02__ge_uint64)
// A.*B function (eWiseMult): GB (_AemultB_04__ge_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_uint64)
// A*D function (colscale): GB (_AxD__ge_uint64)
// D*A function (rowscale): GB (_DxB__ge_uint64)
// C+=B function (dense accum): GB (_Cdense_accumB__ge_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__ge_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_uint64)
// C=scalar+B GB (_bind1st__ge_uint64)
// C=scalar+B' GB (_bind1st_tran__ge_uint64)
// C=A+scalar GB (_bind2nd__ge_uint64)
// C=A'+scalar GB (_bind2nd_tran__ge_uint64)
// C type: bool
// A type: uint64_t
// A pattern? 0
// B type: uint64_t
// B pattern? 0
// BinaryOp: cij = (aij >= bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
bool
// 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 \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint64_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) \
uint64_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) \
bool 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_GE || GxB_NO_UINT64 || GxB_NO_GE_UINT64)
//------------------------------------------------------------------------------
// 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__ge_uint64)
(
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__ge_uint64)
(
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
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__ge_uint64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// 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) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__ge_uint64)
(
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
bool *restrict Cx = (bool *) 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__ge_uint64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *restrict Cx = (bool *) 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__ge_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 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) ;
uint64_t alpha_scalar ;
uint64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ;
beta_scalar = (*((uint64_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__ge_uint64)
(
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__ge_uint64)
(
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__ge_uint64)
(
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__ge_uint64)
(
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__ge_uint64)
(
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
bool *Cx = (bool *) 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 < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint64_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__ge_uint64)
(
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 ;
bool *Cx = (bool *) 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 = 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) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x >= aij) ; \
}
GrB_Info GB (_bind1st_tran__ge_uint64)
(
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 \
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 = GBX (Ax, pA, false) ; \
Cx [pC] = (aij >= y) ; \
}
GrB_Info GB (_bind2nd_tran__ge_uint64)
(
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
uint64_t y = (*((const uint64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_binop__lt_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__lt_uint8)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__lt_uint8)
// A.*B function (eWiseMult): GB (_AemultB_03__lt_uint8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lt_uint8)
// A*D function (colscale): GB (_AxD__lt_uint8)
// D*A function (rowscale): GB (_DxB__lt_uint8)
// C+=B function (dense accum): GB (_Cdense_accumB__lt_uint8)
// C+=b function (dense accum): GB (_Cdense_accumb__lt_uint8)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lt_uint8)
// C=scalar+B GB (_bind1st__lt_uint8)
// C=scalar+B' GB (_bind1st_tran__lt_uint8)
// C=A+scalar GB (_bind2nd__lt_uint8)
// C=A'+scalar GB (_bind2nd_tran__lt_uint8)
// C type: bool
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
bool
// 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 \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
bool 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_LT || GxB_NO_UINT8 || GxB_NO_LT_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__lt_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__lt_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
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__lt_uint8)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// 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) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__lt_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
bool *restrict Cx = (bool *) 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__lt_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
bool *restrict Cx = (bool *) 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__lt_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__lt_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__lt_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__lt_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__lt_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
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__lt_uint8)
(
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
bool *Cx = (bool *) 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 ;
uint8_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__lt_uint8)
(
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 ;
bool *Cx = (bool *) 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 ;
uint8_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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__lt_uint8)
(
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
}
//------------------------------------------------------------------------------
// 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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__lt_uint8)
(
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
|
example-omp.c | // PWD009: Incorrect privatization in parallel region
// https://www.appentra.com/knowledge/checks/pwd009
void example(int m, double *A, double *B, double *C) {
double temp;
// "C" should be shared
#pragma omp parallel for private(temp, C)
for (int i = 0; i < m; i++) {
temp = A[i] * B[i];
C[i] = C[i] + temp;
}
}
|
buggy_version.c | #include <stdio.h>
int main(){
int T[5];
int sum = 0;
// initializing array T
for (int i = 0; i < 10; i ++) {
T[i] = i;
}
// running the loop 10 times using openmp
#pragma omp parallel for shared (T,sum) reduction (+ : sum)
for ( int i = 0; i < 10; i ++) {
// assign value for elements in array T
for (int j =0; j < 5; j++) {
T[j] = i ;
}
// increase "sum" by the toal of T array module by 2
sum += (T[0] + T[1] + T[2] + T[3] + T[4]) % 2;
}
}
|
rhs_fv_term.c | #include "mex.h"
#include "blas.h"
#include "conv2d.h"
#define DEBUG 0
void inner_fv_term(int Np, int K, double *h, double *u, double *v,
int Nedge, double *v1, double *v2,
double *nx, double *ny, double *ds,
signed char *EToR, double *rhs)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(DG_THREADS)
#endif
for (int k = 0; k < K; k++)
{
if ((cell_type)EToR[k] != REFINE)
continue;
int n, ind = k * Nedge;
for (n = 0; n < Nedge; n++)
{
int n1 = (int)v1[n] + k*Np - 1; // change to C type
int n2 = (int)v2[n] + k*Np - 1;
double nx_ = nx[ind];
double ny_ = ny[ind];
double delta_s = ds[ind];
double num_flux;
upwind_flux(h[n1], h[n2], u[n1], v[n1], nx_, ny_, &num_flux);
rhs[n1] -= num_flux * delta_s;
rhs[n2] += num_flux * delta_s;
#if DEBUG
mexPrintf("k=%d, n=%d, n1=%d, n2=%d, nx=%e, ny=%e, delta=%e, flux=%e, rhs1=%e, rhs2=%e\n",
k, n, n1, n2, nx_, ny_, delta_s, num_flux, rhs[n1], rhs[n2]);
#endif
ind++;
}
}
#if DEBUG
mexPrintf("inner_rhs = \n");
int n;
for (n = 0; n < Np; n++)
{
mexPrintf("\t");
for (k = 0; k < K; k++)
{
mexPrintf("%e\t", rhs[k * Np + n]);
}
mexPrintf("\n");
}
#endif
return;
}
void surface_fv_term(size_t Np, size_t Nfp, size_t K,
double *h, double *h_ext, double *u, double *v,
signed char *EToR, signed char *eidtype,
double *eidM, double *eidP,
double *nx, double *ny, double *Js, double *LIFT,
double *rhs)
{
int k;
double *flux = calloc(Nfp * K, sizeof(double));
// #ifdef _OPENMP
// #pragma omp parallel for num_threads(DG_THREADS)
// #endif
for (k = 0; k < K; k++)
{
if ((cell_type)EToR[k] != REFINE)
continue;
int j, ind = k * Nfp;
for (j = 0; j < Nfp; j++)
{
int iM = (int)eidM[ind] - 1; // change index to C type
int iP = (int)eidP[ind] - 1;
double f_M = h[iM]; // local and adjacent node values
double hP = h[iP];
double uM = u[iM], vM = v[iM];
// outward normal vector of local element
double nx_ = nx[ind];
double ny_ = ny[ind];
double f_ext; // external values on local nodes
f_ext = h_ext[iM];
bc_type type = (bc_type)eidtype[ind];
// get adjacent values hP, qxP, qyP, considering
// various boudnary conditions
double f_P;
int info = bound_cond(f_M, hP, f_ext, nx_, ny_, type, &f_P);
// if(info) mexErrMsgTxt("Unknown boundary conditions.");
double numflux;
upwind_flux(f_M, f_P, uM, vM, nx_, ny_, &numflux);
flux[ind] = -numflux;
ind++;
}
}
#if DEBUG
mexPrintf("flux = \n");
int n;
for (n = 0; n < Nfp; n++)
{
mexPrintf("\t");
for (k = 0; k < K; k++)
{
mexPrintf("%e\t", flux[k * Nfp + n]);
}
mexPrintf("\n");
}
#endif
double *stemp = calloc(Nfp * K, sizeof(double));
dvecm(Nfp * K, 1, flux, Js, stemp);
char *chn = "N";
double one = 1.0;
mwSignedIndex Np_ = Np, K_ = K, Nfp_ = Nfp;
dgemm(chn, chn, &Np_, &K_, &Nfp_, &one, LIFT, &Np_, stemp, &Nfp_, &one, rhs, &Np_);
free(flux);
free(stemp);
return;
}
/*
* @brief calculate the sub-cell discretization by finite volume scheme.
* Usages:
* [ rhsQ ] = rhs_fv_term(f_Q, f_ext, u, v, Nedge, v1, v2, nx, ny, ds, ...
* eidM, eidP, nxM, nyM, Js, LIFT, vol, ...
* eidtype, EToR)
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
/* check input */
if (nrhs != 19)
{
mexErrMsgIdAndTxt("MATLAB:rhs_fv_term:invalidNumInputs",
"20 input required.");
}
else if (nlhs > 1)
{
mexErrMsgIdAndTxt("MATLAB:rhs_fv_term:maxlhs",
"Too many output arguments.");
}
double *f_Q = mxGetPr(prhs[0]);
double *f_extQ = mxGetPr(prhs[1]);
double *u = mxGetPr(prhs[2]);
double *v = mxGetPr(prhs[3]);
double Nedge = mxGetScalar(prhs[4]);
double *v1 = mxGetPr(prhs[5]);
double *v2 = mxGetPr(prhs[6]);
double *nx = mxGetPr(prhs[7]);
double *ny = mxGetPr(prhs[8]);
double *ds = mxGetPr(prhs[9]);
double *eidM = mxGetPr(prhs[10]);
double *eidP = mxGetPr(prhs[11]);
double *nxM = mxGetPr(prhs[12]);
double *nyM = mxGetPr(prhs[13]);
double *Js = mxGetPr(prhs[14]);
double *LIFT = mxGetPr(prhs[15]);
double *vol = mxGetPr(prhs[16]);
signed char *eidtype = (signed char *)mxGetData(prhs[17]);
signed char *EToR = (signed char *)mxGetData(prhs[18]);
/* get dimensions */
size_t Np = mxGetM(prhs[0]);
size_t K = mxGetN(prhs[0]);
size_t Nfp = mxGetM(prhs[10]);
/* allocate output array */
plhs[0] = mxCreateDoubleMatrix((mwSize)Np, (mwSize)K, mxREAL);
double *rhsQ = mxGetPr(plhs[0]);
double *vtemp = calloc(Np * K, sizeof(double));
inner_fv_term(Np, K, f_Q, u, v,
(int)Nedge, v1, v2, nx, ny, ds, EToR, vtemp);
surface_fv_term(Np, Nfp, K, f_Q, f_extQ, u, v,
EToR, eidtype, eidM, eidP, nxM, nyM, Js, LIFT, vtemp);
dvecd(Np * K, 1, vtemp, vol, rhsQ);
free(vtemp);
return;
} |
GB_binop__second_int32.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__second_int32)
// A.*B function (eWiseMult): GB (_AemultB_08__second_int32)
// A.*B function (eWiseMult): GB (_AemultB_02__second_int32)
// A.*B function (eWiseMult): GB (_AemultB_04__second_int32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__second_int32)
// A*D function (colscale): GB (_AxD__second_int32)
// D*A function (rowscale): GB (_DxB__second_int32)
// C+=B function (dense accum): GB (_Cdense_accumB__second_int32)
// C+=b function (dense accum): GB (_Cdense_accumb__second_int32)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_int32)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: int32_t
// A type: int32_t
// A pattern? 1
// B type: int32_t
// B pattern? 0
// BinaryOp: cij = bij
#define GB_ATYPE \
int32_t
#define GB_BTYPE \
int32_t
#define GB_CTYPE \
int32_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) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int32_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) \
int32_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 = y ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
1
// 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_SECOND || GxB_NO_INT32 || GxB_NO_SECOND_INT32)
//------------------------------------------------------------------------------
// 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__second_int32)
(
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__second_int32)
(
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__second_int32)
(
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 int32_t
int32_t bwork = (*((int32_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__second_int32)
(
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
int32_t *restrict Cx = (int32_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__second_int32)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *restrict Cx = (int32_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__second_int32)
(
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) ;
int32_t alpha_scalar ;
int32_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int32_t *) alpha_scalar_in)) ;
beta_scalar = (*((int32_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__second_int32)
(
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__second_int32)
(
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__second_int32)
(
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__second_int32)
(
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 bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t *Cx = (int32_t *) Cx_output ;
int32_t x = (*((int32_t *) x_input)) ;
int32_t *Bx = (int32_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 ;
int32_t bij = GBX (Bx, p, false) ;
Cx [p] = bij ;
}
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 ;
int32_t *Cx = (int32_t *) Cx_output ;
int32_t *Ax = (int32_t *) Ax_input ;
int32_t y = (*((int32_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] = y ;
}
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) \
{ \
int32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = aij ; \
}
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 \
int32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int32_t x = (*((const int32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int32_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] = y ; \
}
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
int32_t y = (*((const int32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
integral_reduction.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <math.h>
#include <time.h>
double integrand(double x) {
return 4 / (1 + x * x);
}
int main(int argc, char* argv[]) {
double begin, end;
int t_count = 1;
if (argc != 1) {
t_count = (int) strtol(argv[1], NULL, 10);
}
omp_set_num_threads(t_count);
double int_value = 0;
int iters_count = pow(10, 8);
begin = omp_get_wtime();
#pragma omp parallel reduction(+:int_value)
{
#pragma omp for
for(int i = 0; i < iters_count - 1; i++) {
double left = i * 1.0 / iters_count;
double right = (i + 1) * 1.0 / iters_count;
int_value += (integrand(left) + integrand(right)) / 2;
}
}
end = omp_get_wtime();
printf("The value of the integral is %f\n", int_value / iters_count);
printf("time: %f\n", end - begin);
return 0;
}
|
GB_binop__islt_fp64.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__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__islt_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_fp64)
// A*D function (colscale): GB (_AxD__islt_fp64)
// D*A function (rowscale): GB (_DxB__islt_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__islt_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__islt_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_fp64)
// C=scalar+B GB (_bind1st__islt_fp64)
// C=scalar+B' GB (_bind1st_tran__islt_fp64)
// C=A+scalar GB (_bind2nd__islt_fp64)
// C=A'+scalar GB (_bind2nd_tran__islt_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (aij < bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// 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) \
double 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) \
double 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) \
double 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_ISLT || GxB_NO_FP64 || GxB_NO_ISLT_FP64)
//------------------------------------------------------------------------------
// 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__islt_fp64)
(
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__islt_fp64)
(
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__islt_fp64)
(
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 double
double bwork = (*((double *) 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__islt_fp64)
(
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
double *restrict Cx = (double *) 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__islt_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) 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__islt_fp64)
(
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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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__islt_fp64)
(
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__islt_fp64)
(
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__islt_fp64)
(
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__islt_fp64)
(
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__islt_fp64)
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
double 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__islt_fp64)
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB (_bind1st_tran__islt_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB (_bind2nd_tran__islt_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
QLA_F3_r1_veq_norm2_V.c | /**************** QLA_F3_r_veq_norm2_V.c ********************/
#include <stdio.h>
#include <qla_config.h>
#include <qla_types.h>
#include <qla_random.h>
#include <qla_cmath.h>
#include <qla_f3.h>
#include <math.h>
static void start_slice(){
__asm__ __volatile__ ("");
}
static void end_slice(){
__asm__ __volatile__ ("");
}
void QLA_F3_r_veq_norm2_V ( QLA_F_Real *restrict r, QLA_F3_ColorVector *restrict a, int n)
{
start_slice();
#ifdef HAVE_XLC
#pragma disjoint(*r,*a)
__alignx(16,r);
__alignx(16,a);
#endif
QLA_D_Real sum;
sum = 0.;
#pragma omp parallel for reduction(+:sum)
for(int i=0; i<n; i++) {
for(int i_c=0; i_c<3; i_c++) {
QLA_F_Complex at;
QLA_c_eq_c(at,QLA_F3_elem_V(a[i],i_c));
sum += QLA_norm2_c(at);
}
}
*r = sum;
end_slice();
}
|
GB_binop__ne_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary 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_ek_slice.h"
#include "GB_dense.h"
#include "GB_mkl.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB_AaddB__ne_uint64
// A.*B function (eWiseMult): GB_AemultB__ne_uint64
// A*D function (colscale): GB_AxD__ne_uint64
// D*A function (rowscale): GB_DxB__ne_uint64
// C+=B function (dense accum): GB_Cdense_accumB__ne_uint64
// C+=b function (dense accum): GB_Cdense_accumb__ne_uint64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ne_uint64
// C=scalar+B GB_bind1st__ne_uint64
// C=scalar+B' GB_bind1st_tran__ne_uint64
// C=A+scalar GB_bind2nd__ne_uint64
// C=A'+scalar GB_bind2nd_tran__ne_uint64
// C type: bool
// A type: uint64_t
// B,b type: uint64_t
// BinaryOp: cij = (aij != bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
uint64_t
#define GB_CTYPE \
bool
// 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 \
0
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
0
// 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) \
bool 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) \
z = (x != y) ;
// 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_NE || GxB_NO_UINT64 || GxB_NO_NE_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__ne_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__ne_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
#if 0
{
#include "GB_dense_subassign_23_template.c"
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB_Cdense_accumb__ne_uint64
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if 0
{
// 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) ;
}
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB_AxD__ne_uint64
(
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
bool *GB_RESTRICT Cx = (bool *) 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__ne_uint64
(
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
bool *GB_RESTRICT Cx = (bool *) 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__ne_uint64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
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 ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_add_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB_AemultB__ne_uint64
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
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 ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_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__ne_uint64
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
bool *Cx = (bool *) 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++)
{
uint64_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__ne_uint64
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
bool *Cx = (bool *) 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++)
{
uint64_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 typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = (x != aij) ; \
}
GrB_Info GB_bind1st_tran__ne_uint64
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
// 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)) ;
#define GB_PHASE_2_OF_2
#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 typcasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = Ax [pA] ; \
Cx [pC] = (aij != y) ; \
}
GrB_Info GB_bind2nd_tran__ne_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
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
uint64_t y = (*((const uint64_t *) y_input)) ;
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
BFSFriends.h | /****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.4 -------------------------------------------------*/
/* date: 1/17/2014 ---------------------------------------------*/
/* authors: Aydin Buluc (abuluc@lbl.gov), Adam Lugowski --------*/
/****************************************************************/
/*
Copyright (c) 2010-2014, The Regents of the University of California
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _BFS_FRIENDS_H_
#define _BFS_FRIENDS_H_
#include "mpi.h"
#include <iostream>
#include "SpParMat.h"
#include "SpParHelper.h"
#include "MPIType.h"
#include "Friends.h"
#include "OptBuf.h"
#include "ParFriends.h"
#include "BitMap.h"
#include "BitMapCarousel.h"
#include "BitMapFringe.h"
namespace combblas {
template <class IT, class NT, class DER>
class SpParMat;
/*************************************************************************************************/
/*********************** FRIEND FUNCTIONS FOR BFS ONLY (NO SEMIRINGS) RUNS **********************/
/***************************** BOTH PARALLEL AND SEQUENTIAL FUNCTIONS ****************************/
/*************************************************************************************************/
/**
* Multithreaded SpMV with sparse vector and preset buffers
* the assembly of outgoing buffers sendindbuf/sendnumbuf are done here
*/
template <typename IT, typename VT>
void dcsc_gespmv_threaded_setbuffers (const SpDCCols<IT, bool> & A, const int32_t * indx, const VT * numx, int32_t nnzx,
int32_t * sendindbuf, VT * sendnumbuf, int * cnts, int * dspls, int p_c)
{
Select2ndSRing<bool, VT, VT> BFSsring;
if(A.getnnz() > 0 && nnzx > 0)
{
int splits = A.getnsplit();
if(splits > 0)
{
std::vector< std::vector<int32_t> > indy(splits);
std::vector< std::vector< VT > > numy(splits);
int32_t nlocrows = static_cast<int32_t>(A.getnrow());
int32_t perpiece = nlocrows / splits;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(int i=0; i<splits; ++i)
{
if(i != splits-1)
SpMXSpV_ForThreading<BFSsring>(*(A.GetDCSC(i)), perpiece, indx, numx, nnzx, indy[i], numy[i], i*perpiece);
else
SpMXSpV_ForThreading<BFSsring>(*(A.GetDCSC(i)), nlocrows - perpiece*i, indx, numx, nnzx, indy[i], numy[i], i*perpiece);
}
int32_t perproc = nlocrows / p_c;
int32_t last_rec = p_c-1;
// keep recipients of last entries in each split (-1 for an empty split)
// so that we can delete indy[] and numy[] contents as soon as they are processed
std::vector<int32_t> end_recs(splits);
for(int i=0; i<splits; ++i)
{
if(indy[i].empty())
end_recs[i] = -1;
else
end_recs[i] = std::min(indy[i].back() / perproc, last_rec);
}
int ** loc_rec_cnts = new int *[splits];
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(int i=0; i<splits; ++i)
{
loc_rec_cnts[i] = new int[p_c](); // thread-local recipient data
if(!indy[i].empty()) // guarantee that .begin() and .end() are not null
{
int32_t cur_rec = std::min( indy[i].front() / perproc, last_rec);
int32_t lastdata = (cur_rec+1) * perproc; // one past last entry that goes to this current recipient
for(typename std::vector<int32_t>::iterator it = indy[i].begin(); it != indy[i].end(); ++it)
{
if( ( (*it) >= lastdata ) && cur_rec != last_rec)
{
cur_rec = std::min( (*it) / perproc, last_rec);
lastdata = (cur_rec+1) * perproc;
}
++loc_rec_cnts[i][cur_rec];
}
}
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(int i=0; i<splits; ++i)
{
if(!indy[i].empty()) // guarantee that .begin() and .end() are not null
{
// FACT: Data is sorted, so if the recipient of begin is the same as the owner of end,
// then the whole data is sent to the same processor
int32_t beg_rec = std::min( indy[i].front() / perproc, last_rec);
int32_t alreadysent = 0; // already sent per recipient
for(int before = i-1; before >= 0; before--)
alreadysent += loc_rec_cnts[before][beg_rec];
if(beg_rec == end_recs[i]) // fast case
{
std::transform(indy[i].begin(), indy[i].end(), indy[i].begin(), std::bind2nd(std::minus<int32_t>(), perproc*beg_rec));
std::copy(indy[i].begin(), indy[i].end(), sendindbuf + dspls[beg_rec] + alreadysent);
std::copy(numy[i].begin(), numy[i].end(), sendnumbuf + dspls[beg_rec] + alreadysent);
}
else // slow case
{
int32_t cur_rec = beg_rec;
int32_t lastdata = (cur_rec+1) * perproc; // one past last entry that goes to this current recipient
for(typename std::vector<int32_t>::iterator it = indy[i].begin(); it != indy[i].end(); ++it)
{
if( ( (*it) >= lastdata ) && cur_rec != last_rec )
{
cur_rec = std::min( (*it) / perproc, last_rec);
lastdata = (cur_rec+1) * perproc;
// if this split switches to a new recipient after sending some data
// then it's sure that no data has been sent to that recipient yet
alreadysent = 0;
}
sendindbuf[ dspls[cur_rec] + alreadysent ] = (*it) - perproc*cur_rec; // convert to receiver's local index
sendnumbuf[ dspls[cur_rec] + (alreadysent++) ] = *(numy[i].begin() + (it-indy[i].begin()));
}
}
}
}
// Deallocated rec counts serially once all threads complete
for(int i=0; i< splits; ++i)
{
for(int j=0; j< p_c; ++j)
cnts[j] += loc_rec_cnts[i][j];
delete [] loc_rec_cnts[i];
}
delete [] loc_rec_cnts;
}
else
{
std::cout << "Something is wrong, splits should be nonzero for multithreaded execution" << std::endl;
}
}
}
/**
* Step 3 of the sparse SpMV algorithm, without the semiring (BFS only)
* @param[in,out] optbuf {scratch space for all-to-all (fold) communication}
* @param[in,out] indacc, numacc {index and values of the input vector, deleted upon exit}
* @param[in,out] sendindbuf, sendnumbuf {index and values of the output vector, created}
**/
template<typename VT, typename IT, typename UDER>
void LocalSpMV(const SpParMat<IT,bool,UDER> & A, int rowneighs, OptBuf<int32_t, VT > & optbuf, int32_t * & indacc, VT * & numacc, int * sendcnt, int accnz)
{
#ifdef TIMING
double t0=MPI_Wtime();
#endif
if(optbuf.totmax > 0) // graph500 optimization enabled
{
if(A.spSeq->getnsplit() > 0)
{
// optbuf.{inds/nums/dspls} and sendcnt are all pre-allocated and only filled by dcsc_gespmv_threaded
generic_gespmv_threaded_setbuffers< Select2ndSRing<bool, VT, VT> > (*(A.spSeq), indacc, numacc, (int32_t) accnz, optbuf.inds, optbuf.nums, sendcnt, optbuf.dspls, rowneighs);
}
else
{
// by-pass dcsc_gespmv call
if(A.getlocalnnz() > 0 && accnz > 0)
{
// ABAB: ignoring optbuf.isthere here
// \TODO: Remove .isthere from optbuf definition
SpMXSpV< Select2ndSRing<bool, VT, VT> >(*((A.spSeq)->GetInternal()), (int32_t) A.getlocalrows(), indacc, numacc,
accnz, optbuf.inds, optbuf.nums, sendcnt, optbuf.dspls, rowneighs);
}
}
DeleteAll(indacc,numacc);
}
else
{
SpParHelper::Print("BFS only (no semiring) function only work with optimization buffers\n");
}
#ifdef TIMING
double t1=MPI_Wtime();
cblas_localspmvtime += (t1-t0);
#endif
}
template <typename IU, typename VT>
void MergeContributions(FullyDistSpVec<IU,VT> & y, int * & recvcnt, int * & rdispls, int32_t * & recvindbuf, VT * & recvnumbuf, int rowneighs)
{
#ifdef TIMING
double t0=MPI_Wtime();
#endif
// free memory of y, in case it was aliased
std::vector<IU>().swap(y.ind);
std::vector<VT>().swap(y.num);
#ifndef HEAPMERGE
IU ysize = y.MyLocLength(); // my local length is only O(n/p)
bool * isthere = new bool[ysize];
std::vector< std::pair<IU,VT> > ts_pairs;
std::fill_n(isthere, ysize, false);
// We don't need to keep a "merger" because minimum will always come from the processor
// with the smallest rank; so a linear sweep over the received buffer is enough
for(int i=0; i<rowneighs; ++i)
{
for(int j=0; j< recvcnt[i]; ++j)
{
int32_t index = recvindbuf[rdispls[i] + j];
if(!isthere[index])
ts_pairs.push_back(std::make_pair(index, recvnumbuf[rdispls[i] + j]));
}
}
DeleteAll(recvcnt, rdispls);
DeleteAll(isthere, recvindbuf, recvnumbuf);
__gnu_parallel::sort(ts_pairs.begin(), ts_pairs.end());
int nnzy = ts_pairs.size();
y.ind.resize(nnzy);
y.num.resize(nnzy);
for(int i=0; i< nnzy; ++i)
{
y.ind[i] = ts_pairs[i].first;
y.num[i] = ts_pairs[i].second;
}
#else
// Alternative 2: Heap-merge
int32_t hsize = 0;
int32_t inf = std::numeric_limits<int32_t>::min();
int32_t sup = std::numeric_limits<int32_t>::max();
KNHeap< int32_t, int32_t > sHeap(sup, inf);
int * processed = new int[rowneighs]();
for(int32_t i=0; i<rowneighs; ++i)
{
if(recvcnt[i] > 0)
{
// key, proc_id
sHeap.insert(recvindbuf[rdispls[i]], i);
++hsize;
}
}
int32_t key, locv;
if(hsize > 0)
{
sHeap.deleteMin(&key, &locv);
y.ind.push_back( static_cast<IU>(key));
y.num.push_back(recvnumbuf[rdispls[locv]]); // nothing is processed yet
if( (++(processed[locv])) < recvcnt[locv] )
sHeap.insert(recvindbuf[rdispls[locv]+processed[locv]], locv);
else
--hsize;
}
// ofstream oput;
// y.commGrid->OpenDebugFile("Merge", oput);
// oput << "From displacements: "; copy(rdispls, rdispls+rowneighs, ostream_iterator<int>(oput, " ")); oput << endl;
// oput << "From counts: "; copy(recvcnt, recvcnt+rowneighs, ostream_iterator<int>(oput, " ")); oput << endl;
while(hsize > 0)
{
sHeap.deleteMin(&key, &locv);
IU deref = rdispls[locv] + processed[locv];
if(y.ind.back() != static_cast<IU>(key)) // y.ind is surely not empty
{
y.ind.push_back(static_cast<IU>(key));
y.num.push_back(recvnumbuf[deref]);
}
if( (++(processed[locv])) < recvcnt[locv] )
sHeap.insert(recvindbuf[rdispls[locv]+processed[locv]], locv);
else
--hsize;
}
DeleteAll(recvcnt, rdispls,processed);
DeleteAll(recvindbuf, recvnumbuf);
#endif
#ifdef TIMING
double t1=MPI_Wtime();
cblas_mergeconttime += (t1-t0);
#endif
}
/**
* This is essentially a SpMV for BFS because it lacks the semiring.
* It naturally justs selects columns of A (adjacencies of frontier) and
* merges with the minimum entry succeeding. SpParMat has to be boolean
* input and output vectors are of type VT but their indices are IT
*/
template <typename VT, typename IT, typename UDER>
FullyDistSpVec<IT,VT> SpMV (const SpParMat<IT,bool,UDER> & A, const FullyDistSpVec<IT,VT> & x, OptBuf<int32_t, VT > & optbuf)
{
CheckSpMVCompliance(A,x);
optbuf.MarkEmpty();
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int accnz;
int32_t trxlocnz;
IT lenuntil;
int32_t *trxinds, *indacc;
VT *trxnums, *numacc;
#ifdef TIMING
double t0=MPI_Wtime();
#endif
TransposeVector(World, x, trxlocnz, lenuntil, trxinds, trxnums, true); // trxinds (and potentially trxnums) is allocated
#ifdef TIMING
double t1=MPI_Wtime();
cblas_transvectime += (t1-t0);
#endif
AllGatherVector(ColWorld, trxlocnz, lenuntil, trxinds, trxnums, indacc, numacc, accnz, true); // trxinds (and potentially trxnums) is deallocated, indacc/numacc allocated
FullyDistSpVec<IT, VT> y ( x.commGrid, A.getnrow()); // identity doesn't matter for sparse vectors
int rowneighs; MPI_Comm_size(RowWorld,&rowneighs);
int * sendcnt = new int[rowneighs]();
LocalSpMV(A, rowneighs, optbuf, indacc, numacc, sendcnt, accnz); // indacc/numacc deallocated
int * rdispls = new int[rowneighs];
int * recvcnt = new int[rowneighs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, RowWorld); // share the request counts
// receive displacements are exact whereas send displacements have slack
rdispls[0] = 0;
for(int i=0; i<rowneighs-1; ++i)
{
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
int totrecv = std::accumulate(recvcnt,recvcnt+rowneighs,0);
int32_t * recvindbuf = new int32_t[totrecv];
VT * recvnumbuf = new VT[totrecv];
#ifdef TIMING
double t2=MPI_Wtime();
#endif
if(optbuf.totmax > 0 ) // graph500 optimization enabled
{
MPI_Alltoallv(optbuf.inds, sendcnt, optbuf.dspls, MPIType<int32_t>(), recvindbuf, recvcnt, rdispls, MPIType<int32_t>(), RowWorld);
MPI_Alltoallv(optbuf.nums, sendcnt, optbuf.dspls, MPIType<VT>(), recvnumbuf, recvcnt, rdispls, MPIType<VT>(), RowWorld);
delete [] sendcnt;
}
else
{
SpParHelper::Print("BFS only (no semiring) function only work with optimization buffers\n");
}
#ifdef TIMING
double t3=MPI_Wtime();
cblas_alltoalltime += (t3-t2);
#endif
MergeContributions(y,recvcnt, rdispls, recvindbuf, recvnumbuf, rowneighs);
return y;
}
template <typename VT, typename IT, typename UDER>
SpDCCols<int,bool>::SpColIter* CalcSubStarts(SpParMat<IT,bool,UDER> & A, FullyDistSpVec<IT,VT> & x, BitMapCarousel<IT,VT> &done) {
std::shared_ptr<CommGrid> cg = A.getcommgrid();
IT rowuntil = x.LengthUntil();
MPI_Comm RowWorld = cg->GetRowWorld();
MPI_Bcast(&rowuntil, 1, MPIType<IT>(), 0, RowWorld);
int numcols = cg->GetGridCols();
SpDCCols<int,bool>::SpColIter colit = A.seq().begcol();
#ifdef THREADED
SpDCCols<int,bool>::SpColIter* starts = new SpDCCols<int,bool>::SpColIter[numcols*cblas_splits+1];
for(int c=0; c<numcols; c++) {
IT curr_sub_start = done.GetGlobalStartOfLocal(c) - rowuntil;
IT next_sub_start = done.GetGlobalEndOfLocal(c) - rowuntil;
IT sub_range = next_sub_start - curr_sub_start;
IT per_thread = (sub_range + cblas_splits - 1) / cblas_splits;
IT curr_thread_start = curr_sub_start;
for (int t=0; t<cblas_splits; t++) {
while(colit.colid() < curr_thread_start) {
++colit;
}
starts[c*cblas_splits + t] = colit;
curr_thread_start = std::min(curr_thread_start + per_thread, next_sub_start);
}
}
starts[numcols*cblas_splits] = A.seq().endcol();
#else
SpDCCols<int,bool>::SpColIter* starts = new SpDCCols<int,bool>::SpColIter[numcols+1];
for(int c=0; c<numcols; c++) {
IT next_start = done.GetGlobalStartOfLocal(c) - rowuntil;
while(colit.colid() < next_start) {
++colit;
}
starts[c] = colit;
}
starts[numcols] = A.seq().endcol();
#endif
return starts;
}
template <typename VT, typename IT>
void UpdateParents(MPI_Comm & RowWorld, std::pair<IT,IT> *updates, int num_updates, FullyDistVec<IT,VT> &parents, int source, int dest, BitMapFringe<int64_t,int64_t> &bm_fringe) {
int send_words = num_updates<<1, recv_words;
MPI_Status status;
MPI_Sendrecv(&send_words, 1, MPI_INT, dest, PUPSIZE,
&recv_words, 1, MPI_INT, source, PUPSIZE, RowWorld, &status);
std::pair<IT,IT>* recv_buff = new std::pair<IT,IT>[recv_words>>1];
MPI_Sendrecv(updates, send_words, MPIType<IT>(), dest, PUPDATA,
recv_buff, recv_words, MPIType<IT>(), source, PUPDATA, RowWorld, &status);
#ifdef THREADED
#pragma omp parallel for
#endif
for (int i=0; i<recv_words>>1; i++) {
parents.SetLocalElement(recv_buff[i].first, recv_buff[i].second);
}
bm_fringe.IncrementNumSet((recv_words>>1));
delete[] recv_buff;
}
template <typename VT, typename IT, typename UDER>
void BottomUpStep(SpParMat<IT,bool,UDER> & A, FullyDistSpVec<IT,VT> & x, BitMapFringe<int64_t,int64_t> &bm_fringe, FullyDistVec<IT,VT> & parents, BitMapCarousel<IT,VT> &done, SpDCCols<int,bool>::SpColIter* starts)
{
std::shared_ptr<CommGrid> cg = A.getcommgrid();
MPI_Comm World = cg->GetWorld();
MPI_Comm ColWorld = cg->GetColWorld();
MPI_Comm RowWorld = cg->GetRowWorld();
MPI_Status status;
// get row and column offsets
IT rowuntil = x.LengthUntil(), my_coluntil = x.LengthUntil(), coluntil;
int diagneigh = cg->GetComplementRank();
MPI_Sendrecv(&my_coluntil, 1, MPIType<IT>(), diagneigh, TROST, &coluntil, 1, MPIType<IT>(), diagneigh, TROST, World, &status);
MPI_Bcast(&coluntil, 1, MPIType<IT>(), 0, ColWorld);
MPI_Bcast(&rowuntil, 1, MPIType<IT>(), 0, RowWorld);
BitMap* frontier = bm_fringe.TransposeGather();
done.SaveOld();
#ifdef THREADED
const int buff_size = 8192;
std::pair<IT,IT>* local_update_heads[cblas_splits];
for (int t=0; t<cblas_splits; t++)
local_update_heads[t] = new std::pair<IT,IT>[buff_size];
#endif
// do bottom up work
int numcols = cg->GetGridCols();
int mycol = cg->GetRankInProcRow();
std::pair<IT,IT>* parent_updates = new std::pair<IT,IT>[done.SizeOfChunk()<<1]; // over-allocated
for (int sub_step=0; sub_step<numcols; sub_step++) {
int num_updates = 0;
IT sub_start = done.GetGlobalStartOfLocal();
int dest_slice = (mycol + sub_step) % numcols;
int source_slice = (mycol - sub_step + numcols) % numcols;
#ifdef BOTTOMUPTIME
double t1 = MPI_Wtime();
#endif
#ifdef THREADED
#pragma omp parallel
{
int id = omp_get_thread_num();
int num_locals=0;
SpDCCols<int,bool>::SpColIter::NzIter nzit, nzit_end;
SpDCCols<int,bool>::SpColIter colit, colit_end;
std::pair<IT,IT>* local_updates = local_update_heads[id];
// vector<pair<IT,IT> > local_updates;
colit_end = starts[dest_slice*cblas_splits + id + 1];
for(colit = starts[dest_slice*cblas_splits + id]; colit != colit_end; ++colit) {
int32_t local_row_ind = colit.colid();
IT row = local_row_ind + rowuntil;
if (!done.GetBit(row)) {
nzit_end = A.seq().endnz(colit);
for(nzit = A.seq().begnz(colit); nzit != nzit_end; ++nzit) {
int32_t local_col_ind = nzit.rowid();
IT col = local_col_ind + coluntil;
if (frontier->get_bit(local_col_ind)) {
// local_updates.push_back(make_pair(row-sub_start, col));
if (num_locals == buff_size) {
int copy_start = __sync_fetch_and_add(&num_updates, buff_size);
std::copy(local_updates, local_updates + buff_size, parent_updates + copy_start);
num_locals = 0;
}
local_updates[num_locals++] = std::make_pair(row-sub_start, col);
done.SetBit(row);
break;
}
}
}
}
int copy_start = __sync_fetch_and_add(&num_updates, num_locals);
std::copy(local_updates, local_updates + num_locals, parent_updates + copy_start);
}
#else
SpDCCols<int,bool>::SpColIter::NzIter nzit, nzit_end;
SpDCCols<int,bool>::SpColIter colit, colit_end;
colit_end = starts[dest_slice+1];
for(colit = starts[dest_slice]; colit != colit_end; ++colit)
{
int32_t local_row_ind = colit.colid();
IT row = local_row_ind + rowuntil;
if (!done.GetBit(row))
{
nzit_end = A.seq().endnz(colit);
for(nzit = A.seq().begnz(colit); nzit != nzit_end; ++nzit)
{
int32_t local_col_ind = nzit.rowid();
IT col = local_col_ind + coluntil;
if (frontier->get_bit(local_col_ind))
{
parent_updates[num_updates++] = std::make_pair(row-sub_start, col);
done.SetBit(row);
break;
}
} // end_for
} // end_if
} // end_for
#endif
#ifdef BOTTOMUPTIME
double t2 = MPI_Wtime();
bu_local += (t2-t1);
t1 = MPI_Wtime();
#endif
done.RotateAlongRow();
#ifdef BOTTOMUPTIME
t2 = MPI_Wtime();
bu_rotate += (t2-t1);
t1 = MPI_Wtime();
#endif
UpdateParents(RowWorld, parent_updates, num_updates, parents, source_slice, dest_slice, bm_fringe);
#ifdef BOTTOMUPTIME
t2 = MPI_Wtime();
bu_update += (t2-t1);
#endif
}
bm_fringe.LoadFromNext();
done.UpdateFringe(bm_fringe);
#ifdef THREADED
for (int t=0; t<cblas_splits; t++)
delete[] local_update_heads[t];
#endif
delete[] parent_updates;
}
}
#endif
|
generator_spgemm_csr_asparse.c | /******************************************************************************
** Copyright (c) 2015-2018, Intel Corporation **
** All rights reserved. **
** **
** Redistribution and use in source and binary forms, with or without **
** modification, are permitted provided that the following conditions **
** are met: **
** 1. Redistributions of source code must retain the above copyright **
** notice, this list of conditions and the following disclaimer. **
** 2. Redistributions in binary form must reproduce the above copyright **
** notice, this list of conditions and the following disclaimer in the **
** documentation and/or other materials provided with the distribution. **
** 3. Neither the name of the copyright holder nor the names of its **
** contributors may be used to endorse or promote products derived **
** from this software without specific prior written permission. **
** **
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS **
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT **
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR **
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT **
** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, **
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED **
** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR **
** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF **
** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING **
** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS **
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **
******************************************************************************/
/* Alexander Heinecke (Intel Corp.)
******************************************************************************/
#include "generator_spgemm_csr_asparse.h"
#include "generator_common.h"
#include "libxsmm_main.h"
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(push,target(LIBXSMM_OFFLOAD_TARGET))
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#if defined(LIBXSMM_OFFLOAD_TARGET)
# pragma offload_attribute(pop)
#endif
LIBXSMM_API_INTERN
void libxsmm_generator_spgemm_csr_asparse( libxsmm_generated_code* io_generated_code,
const libxsmm_gemm_descriptor* i_xgemm_desc,
const char* i_arch,
const unsigned int* i_row_idx,
const unsigned int* i_column_idx,
const double* i_values ) {
unsigned int l_m;
unsigned int l_z;
unsigned int l_row_elements;
unsigned int l_flop_count = 0;
char l_new_code[512];
int l_max_code_length = 511;
int l_code_length = 0;
LIBXSMM_UNUSED(i_values);
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_n = 0;\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
/* reset C if beta is zero */
if (0 != (LIBXSMM_GEMM_FLAG_BETA_0 & i_xgemm_desc->flags)) { /* Beta=0 */
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " unsigned int l_m = 0;\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_m = 0; l_m < %u; l_m++) {\n", (unsigned int)i_xgemm_desc->m);
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
if ( i_xgemm_desc->m > 1 ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
if ( LIBXSMM_GEMM_PRECISION_F64 == LIBXSMM_GETENUM_INP( i_xgemm_desc->datatype ) ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) { C[(l_m*%u)+l_n] = 0.0; }\n", (unsigned int)i_xgemm_desc->ldc, (unsigned int)i_xgemm_desc->ldc);
} else {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) { C[(l_m*%u)+l_n] = 0.0f; }\n", (unsigned int)i_xgemm_desc->ldc, (unsigned int)i_xgemm_desc->ldc);
}
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
/* determine the correct simd pragma for each architecture */
if ( ( strcmp( i_arch, "noarch" ) == 0 ) ||
( strcmp( i_arch, "wsm" ) == 0 ) ||
( strcmp( i_arch, "snb" ) == 0 ) ||
( strcmp( i_arch, "hsw" ) == 0 ) ) {
if ( i_xgemm_desc->n > 7 ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(8)\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
} else if ( i_xgemm_desc->n > 3 ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(4)\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
} else if ( i_xgemm_desc->n > 1 ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(2)\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
} else {}
} else if ( ( strcmp( i_arch, "knc" ) == 0 ) ||
( strcmp( i_arch, "knl" ) == 0 ) ||
( strcmp( i_arch, "knm" ) == 0 ) ||
( strcmp( i_arch, "icl" ) == 0 ) ||
( strcmp( i_arch, "skx" ) == 0 ) ) {
if ( (i_xgemm_desc->n > 1) ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma simd vectorlength(16)\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
} else {
LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_ARCH );
return;
}
if ( (i_xgemm_desc->n > 1) &&
((LIBXSMM_GEMM_FLAG_ALIGN_A & i_xgemm_desc->flags) != 0) &&
((LIBXSMM_GEMM_FLAG_ALIGN_C & i_xgemm_desc->flags) != 0) ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " #pragma vector aligned\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
/* generate the actuel kernel */
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " for ( l_n = 0; l_n < %u; l_n++) {\n", (unsigned int)i_xgemm_desc->n);
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
for ( l_m = 0; l_m < (unsigned int)i_xgemm_desc->m; l_m++ ) {
l_row_elements = i_row_idx[l_m+1] - i_row_idx[l_m];
for ( l_z = 0; l_z < l_row_elements; l_z++ ) {
/* check k such that we just use columns which actually need to be multiplied */
if ( i_column_idx[i_row_idx[l_m] + l_z] < (unsigned int)i_xgemm_desc->k ) {
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " C[%u+l_n] += A[%u] * B[%u+l_n];\n", l_m * i_xgemm_desc->ldc, i_row_idx[l_m] + l_z, i_column_idx[i_row_idx[l_m] + l_z]*i_xgemm_desc->ldb );
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
l_flop_count += 2;
}
}
}
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, " }\n");
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
/* add flop counter */
l_code_length = LIBXSMM_SNPRINTF(l_new_code, l_max_code_length, "\n#ifndef NDEBUG\n#ifdef _OPENMP\n#pragma omp atomic\n#endif\nlibxsmm_num_total_flops += %u;\n#endif\n", l_flop_count * (unsigned int)i_xgemm_desc->m);
libxsmm_append_code_as_string( io_generated_code, l_new_code, l_code_length );
}
|
omp_taskloop_num_tasks.c | // This test is known to be fragile on NetBSD kernel at the moment.
// UNSUPPORTED: netbsd
// RUN: %libomp-compile-and-run
// RUN: %libomp-compile && env KMP_TASKLOOP_MIN_TASKS=1 %libomp-run
// These compilers don't support the taskloop construct
// UNSUPPORTED: gcc-4, gcc-5, icc-16
// This test is known to be fragile on NetBSD kernel at the moment,
// https://bugs.llvm.org/show_bug.cgi?id=42020.
// UNSUPPORTED: netbsd
/*
* Test for taskloop
* Method: caculate how many times the iteration space is dispatched
* and judge if each dispatch has the requested grainsize
* It is possible for two adjacent chunks are executed by the same thread
*/
#include <stdio.h>
#include <omp.h>
#include <stdlib.h>
#include "omp_testsuite.h"
#define CFDMAX_SIZE 1120
int test_omp_taskloop_num_tasks()
{
int i;
int *tids;
int *tidsArray;
int count;
int result = 0;
int num_tasks;
for (num_tasks = 1; num_tasks < 120; ++num_tasks) {
count = 0;
tidsArray = (int *)malloc(sizeof(int) * CFDMAX_SIZE);
tids = tidsArray;
#pragma omp parallel shared(tids)
{
int i;
#pragma omp master
#pragma omp taskloop num_tasks(num_tasks)
for (i = 0; i < CFDMAX_SIZE; i++) {
tids[i] = omp_get_thread_num();
}
}
for (i = 0; i < CFDMAX_SIZE - 1; ++i) {
if (tids[i] != tids[i + 1]) {
count++;
}
}
if (count > num_tasks) {
fprintf(stderr, "counted too many tasks: (wanted %d, got %d)\n",
num_tasks, count);
result++;
}
}
return (result==0);
}
int main()
{
int i;
int num_failed=0;
for (i = 0; i < REPETITIONS; i++) {
if (!test_omp_taskloop_num_tasks()) {
num_failed++;
}
}
return num_failed;
}
|
alloc_benchmark.c | // SPDX-License-Identifier: BSD-2-Clause
/* Copyright (C) 2016 - 2020 Intel Corporation. */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdint.h>
#include <limits.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#if defined(HBWMALLOC)
#include <hbwmalloc.h>
#define MALLOC_FN hbw_malloc
#define FREE_FN hbw_free
#elif defined (TBBMALLOC)
#include "tbbmalloc.h"
void *(*scalable_malloc)(size_t);
void *(*scalable_realloc)(void *, size_t);
void *(*scalable_calloc)(size_t, size_t);
void (*scalable_free)(void *);
#define MALLOC_FN scalable_malloc
#define FREE_FN scalable_free
#elif defined (PMEMMALLOC)
#include <sys/stat.h>
#include "memkind.h"
#define MALLOC_FN(x) memkind_malloc(pmem_bench_kind, (x))
#define FREE_FN(x) memkind_free(pmem_bench_kind, (x))
static const size_t PMEM_PART_SIZE = 0;
static const char *PMEM_DIR = "/tmp/";
static memkind_t pmem_bench_kind;
#else
#define MALLOC_FN malloc
#define FREE_FN free
#endif
double ctimer(void);
void usage(char *name);
int main(int argc, char *argv[])
{
#ifdef _OPENMP
int nthr = omp_get_max_threads();
#else
int nthr = 1;
#endif
long n, size;
size_t alloc_size;
unsigned long i;
double dt, t_start, t_end, t_malloc, t_free, t_first_malloc, t_first_free,
malloc_time = 0.0, free_time = 0.0, first_malloc_time, first_free_time;
void *ptr;
#ifdef TBBMALLOC
int ret;
ret = load_tbbmalloc_symbols();
if (ret) {
printf("Error: TBB symbols not loaded (ret: %d)\n", ret);
return EXIT_FAILURE;
}
#endif
#ifdef PMEMMALLOC
struct stat st;
/* Handle command line arguments */
if (argc == 3 || argc == 4) {
n = atol(argv[1]);
size = atol(argv[2]);
if (argc == 4) {
if (stat(argv[3], &st) != 0 || !S_ISDIR(st.st_mode)) {
usage(argv[0]);
return EXIT_FAILURE;
} else {
PMEM_DIR = argv[3];
}
}
}
if ((argc != 3 && argc != 4) || n < 0 || size < 0 || size > (LONG_MAX >> 10)) {
usage(argv[0]);
return EXIT_FAILURE;
}
int err = memkind_create_pmem(PMEM_DIR, PMEM_PART_SIZE, &pmem_bench_kind);
if (err) {
printf("Error: memkind_create_pmem failed %d\n", err);
return EXIT_FAILURE;
}
#else
/* Handle command line arguments */
if (argc == 3) {
n = atol(argv[1]);
size = atol(argv[2]);
}
if (argc != 3 || n < 0 || size < 0 || size > (LONG_MAX >> 10)) {
usage(argv[0]);
return EXIT_FAILURE;
}
#endif
alloc_size = (size_t) size * 1024;
/* Get pagesize and compute page_mask */
const size_t page_size = sysconf(_SC_PAGESIZE);
const size_t page_mask = ~(page_size-1);
/* Warm up */
t_first_malloc = ctimer();
ptr = MALLOC_FN(alloc_size);
first_malloc_time = ctimer() - t_first_malloc;
if (ptr == NULL) {
printf("Error: first allocation failed\n");
return EXIT_FAILURE;
}
t_first_free = ctimer();
FREE_FN(ptr);
first_free_time = ctimer() - t_first_free;
ptr = NULL;
t_start = ctimer();
#pragma omp parallel private(i,t_malloc,t_free,ptr) reduction(max:malloc_time,free_time)
{
malloc_time = 0.0;
free_time = 0.0;
for (i=0; i<n; i++) {
t_malloc = ctimer();
ptr = (void *) MALLOC_FN(alloc_size);
malloc_time += ctimer() - t_malloc;
#pragma omp critical
{
if (ptr == NULL) {
printf("Error: allocation failed\n");
exit(EXIT_FAILURE);
}
}
/* Make sure to touch every page */
char *end = ptr + alloc_size;
char *aligned_beg = (char *)((uintptr_t)ptr & page_mask);
while(aligned_beg < end) {
char *temp_ptr = (char *) aligned_beg;
char value = temp_ptr[0];
temp_ptr[0] = value;
aligned_beg += page_size;
}
t_free = ctimer();
FREE_FN(ptr);
free_time += ctimer() - t_free;
ptr = NULL;
}
}
t_end = ctimer();
dt = t_end - t_start;
printf("%d %lu %8.6f %8.6f %8.6f %8.6f %8.6f\n",
nthr, size, dt/n, malloc_time/n, free_time/n, first_malloc_time,
first_free_time);
#ifdef PMEMMALLOC
err = memkind_destroy_kind(pmem_bench_kind);
if (err) {
printf("Error: memkind_destroy_kind failed %d\n", err);
return EXIT_FAILURE;
}
#endif
return EXIT_SUCCESS;
}
void usage(char *name)
{
#ifdef PMEMMALLOC
printf("Usage: %s <N> <SIZE> [DIR], where \n"
"N is an number of repetitions \n"
"SIZE is an allocation size in kbytes\n"
"DIR is a custom path for PMEM kind, (default: \"/tmp/\")\n",
name);
#else
printf("Usage: %s <N> <SIZE>, where \n"
"N is an number of repetitions \n"
"SIZE is an allocation size in kbytes\n", name);
#endif
}
inline double ctimer()
{
struct timeval tmr;
gettimeofday(&tmr, NULL);
/* Return time in ms */
return (tmr.tv_sec + tmr.tv_usec/1000000.0)*1000;
}
|
GB_unaryop__ainv_uint16_fp32.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__ainv_uint16_fp32
// op(A') function: GB_tran__ainv_uint16_fp32
// C type: uint16_t
// A type: float
// cast: uint16_t cij ; GB_CAST_UNSIGNED(cij,aij,16)
// unaryop: cij = -aij
#define GB_ATYPE \
float
#define GB_CTYPE \
uint16_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 ;
// casting
#define GB_CASTING(z, aij) \
uint16_t z ; GB_CAST_UNSIGNED(z,aij,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 (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_AINV || GxB_NO_UINT16 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__ainv_uint16_fp32
(
uint16_t *Cx, // Cx and Ax may be aliased
float *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__ainv_uint16_fp32
(
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
|
updater_basemaker-inl.h | /*!
* Copyright 2014 by Contributors
* \file updater_basemaker-inl.h
* \brief implement a common tree constructor
* \author Tianqi Chen
*/
#ifndef XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
#define XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
#include <rabit/rabit.h>
#include <vector>
#include <algorithm>
#include <string>
#include <limits>
#include <utility>
#include "xgboost/base.h"
#include "xgboost/json.h"
#include "xgboost/tree_updater.h"
#include "param.h"
#include "constraints.h"
#include "../common/io.h"
#include "../common/random.h"
#include "../common/quantile.h"
namespace xgboost {
namespace tree {
/*!
* \brief base tree maker class that defines common operation
* needed in tree making
*/
class BaseMaker: public TreeUpdater {
public:
void Configure(const Args& args) override {
param_.UpdateAllowUnknown(args);
}
void LoadConfig(Json const& in) override {
auto const& config = get<Object const>(in);
FromJson(config.at("train_param"), &this->param_);
}
void SaveConfig(Json* p_out) const override {
auto& out = *p_out;
out["train_param"] = ToJson(param_);
}
protected:
// helper to collect and query feature meta information
struct FMetaHelper {
public:
/*! \brief find type of each feature, use column format */
inline void InitByCol(DMatrix* p_fmat,
const RegTree& tree) {
fminmax_.resize(tree.param.num_feature * 2);
std::fill(fminmax_.begin(), fminmax_.end(),
-std::numeric_limits<bst_float>::max());
// start accumulating statistics
for (const auto &batch : p_fmat->GetBatches<SortedCSCPage>()) {
for (bst_uint fid = 0; fid < batch.Size(); ++fid) {
auto c = batch[fid];
if (c.size() != 0) {
CHECK_LT(fid * 2, fminmax_.size());
fminmax_[fid * 2 + 0] =
std::max(-c[0].fvalue, fminmax_[fid * 2 + 0]);
fminmax_[fid * 2 + 1] =
std::max(c[c.size() - 1].fvalue, fminmax_[fid * 2 + 1]);
}
}
}
}
/*! \brief synchronize the information */
inline void SyncInfo() {
rabit::Allreduce<rabit::op::Max>(dmlc::BeginPtr(fminmax_), fminmax_.size());
}
// get feature type, 0:empty 1:binary 2:real
inline int Type(bst_uint fid) const {
CHECK_LT(fid * 2 + 1, fminmax_.size())
<< "FeatHelper fid exceed query bound ";
bst_float a = fminmax_[fid * 2];
bst_float b = fminmax_[fid * 2 + 1];
if (a == -std::numeric_limits<bst_float>::max()) return 0;
if (-a == b) {
return 1;
} else {
return 2;
}
}
bst_float MaxValue(bst_uint fid) const {
return fminmax_[fid *2 + 1];
}
void SampleCol(float p, std::vector<bst_feature_t> *p_findex) const {
std::vector<bst_feature_t> &findex = *p_findex;
findex.clear();
for (size_t i = 0; i < fminmax_.size(); i += 2) {
const auto fid = static_cast<bst_uint>(i / 2);
if (this->Type(fid) != 0) findex.push_back(fid);
}
auto n = static_cast<unsigned>(p * findex.size());
std::shuffle(findex.begin(), findex.end(), common::GlobalRandom());
findex.resize(n);
// sync the findex if it is subsample
std::string s_cache;
common::MemoryBufferStream fc(&s_cache);
dmlc::Stream& fs = fc;
if (rabit::GetRank() == 0) {
fs.Write(findex);
}
rabit::Broadcast(&s_cache, 0);
fs.Read(&findex);
}
private:
std::vector<bst_float> fminmax_;
};
// ------static helper functions ------
// helper function to get to next level of the tree
/*! \brief this is helper function for row based data*/
inline static int NextLevel(const SparsePage::Inst &inst, const RegTree &tree, int nid) {
const RegTree::Node &n = tree[nid];
bst_uint findex = n.SplitIndex();
for (const auto& ins : inst) {
if (findex == ins.index) {
if (ins.fvalue < n.SplitCond()) {
return n.LeftChild();
} else {
return n.RightChild();
}
}
}
return n.DefaultChild();
}
// ------class member helpers---------
/*! \brief initialize temp data structure */
inline void InitData(const std::vector<GradientPair> &gpair,
const DMatrix &fmat,
const RegTree &tree) {
{
// setup position
position_.resize(gpair.size());
std::fill(position_.begin(), position_.end(), 0);
// mark delete for the deleted datas
for (size_t i = 0; i < position_.size(); ++i) {
if (gpair[i].GetHess() < 0.0f) position_[i] = ~position_[i];
}
// mark subsample
if (param_.subsample < 1.0f) {
CHECK_EQ(param_.sampling_method, TrainParam::kUniform)
<< "Only uniform sampling is supported, "
<< "gradient-based sampling is only support by GPU Hist.";
std::bernoulli_distribution coin_flip(param_.subsample);
auto& rnd = common::GlobalRandom();
for (size_t i = 0; i < position_.size(); ++i) {
if (gpair[i].GetHess() < 0.0f) continue;
if (!coin_flip(rnd)) position_[i] = ~position_[i];
}
}
}
{
// expand query
qexpand_.reserve(256); qexpand_.clear();
qexpand_.push_back(0);
this->UpdateNode2WorkIndex(tree);
}
this->interaction_constraints_.Configure(param_, fmat.Info().num_col_);
}
/*! \brief update queue expand add in new leaves */
inline void UpdateQueueExpand(const RegTree &tree) {
std::vector<int> newnodes;
for (int nid : qexpand_) {
if (!tree[nid].IsLeaf()) {
newnodes.push_back(tree[nid].LeftChild());
newnodes.push_back(tree[nid].RightChild());
}
}
// use new nodes for qexpand
qexpand_ = newnodes;
this->UpdateNode2WorkIndex(tree);
}
// return decoded position
inline int DecodePosition(bst_uint ridx) const {
const int pid = position_[ridx];
return pid < 0 ? ~pid : pid;
}
// encode the encoded position value for ridx
inline void SetEncodePosition(bst_uint ridx, int nid) {
if (position_[ridx] < 0) {
position_[ridx] = ~nid;
} else {
position_[ridx] = nid;
}
}
/*!
* \brief this is helper function uses column based data structure,
* reset the positions to the lastest one
* \param nodes the set of nodes that contains the split to be used
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
inline void ResetPositionCol(const std::vector<int> &nodes,
DMatrix *p_fmat,
const RegTree &tree) {
// set the positions in the nondefault
this->SetNonDefaultPositionCol(nodes, p_fmat, tree);
this->SetDefaultPostion(p_fmat, tree);
}
/*!
* \brief helper function to set the non-leaf positions to default direction.
* This function can be applied multiple times and will get the same result.
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
inline void SetDefaultPostion(DMatrix *p_fmat,
const RegTree &tree) {
// set default direct nodes to default
// for leaf nodes that are not fresh, mark then to ~nid,
// so that they are ignored in future statistics collection
const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_);
#pragma omp parallel for schedule(static)
for (bst_omp_uint ridx = 0; ridx < ndata; ++ridx) {
const int nid = this->DecodePosition(ridx);
if (tree[nid].IsLeaf()) {
// mark finish when it is not a fresh leaf
if (tree[nid].RightChild() == -1) {
position_[ridx] = ~nid;
}
} else {
// push to default branch
if (tree[nid].DefaultLeft()) {
this->SetEncodePosition(ridx, tree[nid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[nid].RightChild());
}
}
}
}
/*!
* \brief this is helper function uses column based data structure,
* to CORRECT the positions of non-default directions that WAS set to default
* before calling this function.
* \param batch The column batch
* \param sorted_split_set The set of index that contains split solutions.
* \param tree the regression tree structure
*/
inline void CorrectNonDefaultPositionByBatch(
const SparsePage &batch, const std::vector<bst_uint> &sorted_split_set,
const RegTree &tree) {
for (size_t fid = 0; fid < batch.Size(); ++fid) {
auto col = batch[fid];
auto it = std::lower_bound(sorted_split_set.begin(), sorted_split_set.end(), fid);
if (it != sorted_split_set.end() && *it == fid) {
const auto ndata = static_cast<bst_omp_uint>(col.size());
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_uint ridx = col[j].index;
const bst_float fvalue = col[j].fvalue;
const int nid = this->DecodePosition(ridx);
CHECK(tree[nid].IsLeaf());
int pid = tree[nid].Parent();
// go back to parent, correct those who are not default
if (!tree[nid].IsRoot() && tree[pid].SplitIndex() == fid) {
if (fvalue < tree[pid].SplitCond()) {
this->SetEncodePosition(ridx, tree[pid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[pid].RightChild());
}
}
}
}
}
}
/*!
* \brief this is helper function uses column based data structure,
* \param nodes the set of nodes that contains the split to be used
* \param tree the regression tree structure
* \param out_split_set The split index set
*/
inline void GetSplitSet(const std::vector<int> &nodes,
const RegTree &tree,
std::vector<unsigned>* out_split_set) {
std::vector<unsigned>& fsplits = *out_split_set;
fsplits.clear();
// step 1, classify the non-default data into right places
for (int nid : nodes) {
if (!tree[nid].IsLeaf()) {
fsplits.push_back(tree[nid].SplitIndex());
}
}
std::sort(fsplits.begin(), fsplits.end());
fsplits.resize(std::unique(fsplits.begin(), fsplits.end()) - fsplits.begin());
}
/*!
* \brief this is helper function uses column based data structure,
* update all positions into nondefault branch, if any, ignore the default branch
* \param nodes the set of nodes that contains the split to be used
* \param p_fmat feature matrix needed for tree construction
* \param tree the regression tree structure
*/
virtual void SetNonDefaultPositionCol(const std::vector<int> &nodes,
DMatrix *p_fmat,
const RegTree &tree) {
std::vector<unsigned> fsplits;
this->GetSplitSet(nodes, tree, &fsplits);
for (const auto &batch : p_fmat->GetBatches<SortedCSCPage>()) {
for (auto fid : fsplits) {
auto col = batch[fid];
const auto ndata = static_cast<bst_omp_uint>(col.size());
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_uint ridx = col[j].index;
const bst_float fvalue = col[j].fvalue;
const int nid = this->DecodePosition(ridx);
// go back to parent, correct those who are not default
if (!tree[nid].IsLeaf() && tree[nid].SplitIndex() == fid) {
if (fvalue < tree[nid].SplitCond()) {
this->SetEncodePosition(ridx, tree[nid].LeftChild());
} else {
this->SetEncodePosition(ridx, tree[nid].RightChild());
}
}
}
}
}
}
/*! \brief helper function to get statistics from a tree */
template<typename TStats>
inline void GetNodeStats(const std::vector<GradientPair> &gpair,
const DMatrix &fmat,
const RegTree &tree,
std::vector< std::vector<TStats> > *p_thread_temp,
std::vector<TStats> *p_node_stats) {
std::vector< std::vector<TStats> > &thread_temp = *p_thread_temp;
thread_temp.resize(omp_get_max_threads());
p_node_stats->resize(tree.param.num_nodes);
#pragma omp parallel
{
const int tid = omp_get_thread_num();
thread_temp[tid].resize(tree.param.num_nodes, TStats());
for (unsigned int nid : qexpand_) {
thread_temp[tid][nid] = TStats();
}
}
// setup position
const auto ndata = static_cast<bst_omp_uint>(fmat.Info().num_row_);
#pragma omp parallel for schedule(static)
for (bst_omp_uint ridx = 0; ridx < ndata; ++ridx) {
const int nid = position_[ridx];
const int tid = omp_get_thread_num();
if (nid >= 0) {
thread_temp[tid][nid].Add(gpair[ridx]);
}
}
// sum the per thread statistics together
for (int nid : qexpand_) {
TStats &s = (*p_node_stats)[nid];
s = TStats();
for (size_t tid = 0; tid < thread_temp.size(); ++tid) {
s.Add(thread_temp[tid][nid]);
}
}
}
/*! \brief common helper data structure to build sketch */
struct SketchEntry {
/*! \brief total sum of amount to be met */
double sum_total;
/*! \brief statistics used in the sketch */
double rmin, wmin;
/*! \brief last seen feature value */
bst_float last_fvalue;
/*! \brief current size of sketch */
double next_goal;
// pointer to the sketch to put things in
common::WXQuantileSketch<bst_float, bst_float> *sketch;
// initialize the space
inline void Init(unsigned max_size) {
next_goal = -1.0f;
rmin = wmin = 0.0f;
sketch->temp.Reserve(max_size + 1);
sketch->temp.size = 0;
}
/*!
* \brief push a new element to sketch
* \param fvalue feature value, comes in sorted ascending order
* \param w weight
* \param max_size
*/
inline void Push(bst_float fvalue, bst_float w, unsigned max_size) {
if (next_goal == -1.0f) {
next_goal = 0.0f;
last_fvalue = fvalue;
wmin = w;
return;
}
if (last_fvalue != fvalue) {
double rmax = rmin + wmin;
if (rmax >= next_goal && sketch->temp.size != max_size) {
if (sketch->temp.size == 0 ||
last_fvalue > sketch->temp.data[sketch->temp.size-1].value) {
// push to sketch
sketch->temp.data[sketch->temp.size] =
common::WXQuantileSketch<bst_float, bst_float>::
Entry(static_cast<bst_float>(rmin),
static_cast<bst_float>(rmax),
static_cast<bst_float>(wmin), last_fvalue);
CHECK_LT(sketch->temp.size, max_size)
<< "invalid maximum size max_size=" << max_size
<< ", stemp.size" << sketch->temp.size;
++sketch->temp.size;
}
if (sketch->temp.size == max_size) {
next_goal = sum_total * 2.0f + 1e-5f;
} else {
next_goal = static_cast<bst_float>(sketch->temp.size * sum_total / max_size);
}
} else {
if (rmax >= next_goal) {
LOG(TRACKER) << "INFO: rmax=" << rmax
<< ", sum_total=" << sum_total
<< ", naxt_goal=" << next_goal
<< ", size=" << sketch->temp.size;
}
}
rmin = rmax;
wmin = w;
last_fvalue = fvalue;
} else {
wmin += w;
}
}
/*! \brief push final unfinished value to the sketch */
inline void Finalize(unsigned max_size) {
double rmax = rmin + wmin;
if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) {
CHECK_LE(sketch->temp.size, max_size)
<< "Finalize: invalid maximum size, max_size=" << max_size
<< ", stemp.size=" << sketch->temp.size;
// push to sketch
sketch->temp.data[sketch->temp.size] =
common::WXQuantileSketch<bst_float, bst_float>::
Entry(static_cast<bst_float>(rmin),
static_cast<bst_float>(rmax),
static_cast<bst_float>(wmin), last_fvalue);
++sketch->temp.size;
}
sketch->PushTemp();
}
};
/*! \brief training parameter of tree grower */
TrainParam param_;
/*! \brief queue of nodes to be expanded */
std::vector<int> qexpand_;
/*!
* \brief map active node to is working index offset in qexpand,
* can be -1, which means the node is node actively expanding
*/
std::vector<int> node2workindex_;
/*!
* \brief position of each instance in the tree
* can be negative, which means this position is no longer expanding
* see also Decode/EncodePosition
*/
std::vector<int> position_;
FeatureInteractionConstraintHost interaction_constraints_;
private:
inline void UpdateNode2WorkIndex(const RegTree &tree) {
// update the node2workindex
std::fill(node2workindex_.begin(), node2workindex_.end(), -1);
node2workindex_.resize(tree.param.num_nodes);
for (size_t i = 0; i < qexpand_.size(); ++i) {
node2workindex_[qexpand_[i]] = static_cast<int>(i);
}
}
};
} // namespace tree
} // namespace xgboost
#endif // XGBOOST_TREE_UPDATER_BASEMAKER_INL_H_
|
radmin_fmt_plug.c | /* RAdmin v2.x cracker patch for JtR. Hacked together during
* May of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>.
*
* This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com>,
* and it is hereby released to the general public under the following terms:
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* Input Format => user:$radmin2$hash */
#if FMT_EXTERNS_H
extern struct fmt_main fmt_radmin;
#elif FMT_REGISTERS_H
john_register_one(&fmt_radmin);
#else
#include "md5.h"
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#ifdef _OPENMP
#include <omp.h>
// Tuned on core i7 quad HT
// 1 7445K
// 16 12155K
// 32 12470K ** this was chosen.
// 64 12608k
// 128 12508k
#ifndef OMP_SCALE
#define OMP_SCALE 32
#endif
#endif
#include "memdbg.h"
#define FORMAT_LABEL "RAdmin"
#define FORMAT_NAME "v2.x"
#define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH -1
#define PLAINTEXT_LENGTH 99
#define CIPHERTEXT_LENGTH 32
#define BINARY_SIZE 16
#define SALT_SIZE 0
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 64
#define BINARY_ALIGN 4
#define SALT_ALIGN 1
static struct fmt_tests radmin_tests[] = {
{"$radmin2$B137F09CF92F465CABCA06AB1B283C1F", "lastwolf"},
{"$radmin2$14e897b1a9354f875df51047bb1a0765", "podebradka"},
{"$radmin2$02ba5e187e2589be6f80da0046aa7e3c", "12345678"},
{"$radmin2$b4e13c7149ebde51e510959f30319ac7", "firebaLL"},
{"$radmin2$3d2c8cae4621edf8abb081408569482b", "yamaha12345"},
{"$radmin2$60cb8e411b02c10ecc3c98e29e830de8", "xplicit"},
{"$radmin2$53b1dc4fd27e58a075b196f99b2ac992", "UPPERCASE"},
{"$radmin2$6d0bb00954ceb7fbee436bb55a8397a9", ""},
{NULL}
};
static char (*saved_key)[PLAINTEXT_LENGTH+1];
static ARCH_WORD_32 (*crypt_out)[8];
static void init(struct fmt_main *self)
{
#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(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_out = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_out));
}
static void done(void)
{
MEM_FREE(saved_key);
MEM_FREE(crypt_out);
}
static char *split(char *ciphertext, int index, struct fmt_main *self) {
static char buf[CIPHERTEXT_LENGTH + 10]; // $radmin2$ is 9 bytes
strnzcpy(buf, ciphertext, CIPHERTEXT_LENGTH + 10);
strlwr(buf);
return buf;
}
static int valid(char *ciphertext, struct fmt_main *self)
{
char *p;
if (strncmp(ciphertext, "$radmin2$", 9))
return 0;
p = ciphertext + 9;
if (hexlen(p) != CIPHERTEXT_LENGTH)
return 0;
return 1;
}
static void *get_binary(char *ciphertext)
{
static union {
unsigned char c[BINARY_SIZE+1];
ARCH_WORD dummy;
} buf;
unsigned char *out = buf.c;
char *p;
int i;
p = strrchr(ciphertext, '$') + 1;
for (i = 0; i < BINARY_SIZE; i++) {
out[i] =
(atoi16[ARCH_INDEX(*p)] << 4) |
atoi16[ARCH_INDEX(p[1])];
p += 2;
}
return out;
}
static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; }
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < count; index++)
{
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, saved_key[index], sizeof(saved_key[index]));
MD5_Final((unsigned char *)crypt_out[index], &ctx);
}
return count;
}
static int cmp_all(void *binary, int count)
{
int index;
for (index = 0; index < count; index++)
if (*(ARCH_WORD_32 *)binary == crypt_out[index][0])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
return *(ARCH_WORD_32 *)binary == crypt_out[index][0];
}
static int cmp_exact(char *source, int index)
{
void *binary = get_binary(source);
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static void radmin_set_key(char *key, int index)
{
// this code assures that both saved_key[index] gets null-terminated (without buffer overflow)
char *cp = &saved_key[index][strnzcpyn(saved_key[index], key, PLAINTEXT_LENGTH + 1)+1];
// and is null padded up to 100 bytes. We simply clean up prior buffer, up to element 99, but that element will never be written to
while (*cp) *cp++ = 0;
}
static char *get_key(int index)
{
// assured null teminated string. Just return it.
return saved_key[index];
}
struct fmt_main fmt_radmin = {
{
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_OMP_BAD | FMT_SPLIT_UNIFIES_CASE,
{ NULL },
radmin_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
valid,
split,
get_binary,
fmt_default_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
},
fmt_default_salt_hash,
NULL,
fmt_default_set_salt,
radmin_set_key,
get_key,
fmt_default_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
}
};
#endif /* plugin stanza */
|
RadixSort.h | // Copyright 2021 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <algorithm>
#include <cstddef>
#include <vector>
#include "wrap_omp.h"
namespace anari {
namespace example_device {
// Helper functions ///////////////////////////////////////////////////////////
template <typename TO, typename FROM>
inline TO safe_cast(FROM from)
{
static_assert(sizeof(TO) == sizeof(FROM), "safe_cast<> type size mismatch");
TO to;
std::memcpy(&to, &from, sizeof(from));
return to;
}
// RadixSort //////////////////////////////////////////////////////////////////
/// Parallel implementation of the radix sort algorithm.
template <size_t BITS_PER_ITERATION>
class RadixSort
{
public:
/// Performs the sort. Must be called from a parallel region.
template <typename Key, typename Value>
void sort_in_parallel(Key *BVH_RESTRICT &keys,
Key *BVH_RESTRICT &keys_copy,
Value *BVH_RESTRICT &values,
Value *BVH_RESTRICT &values_copy,
size_t count,
size_t bit_count)
{
ASSERT_PARALLEL();
static constexpr size_t bucket_count = 1 << BITS_PER_ITERATION;
static constexpr Key mask = (Key(1) << BITS_PER_ITERATION) - 1;
size_t thread_count = OMP_GET_NUM_THREADS();
size_t thread_id = OMP_GET_THREAD_NUM();
#pragma omp single
{
allThreadBuckets.clear();
allThreadBuckets.resize((thread_count + 1) * bucket_count);
}
for (size_t bit = 0; bit < bit_count; bit += BITS_PER_ITERATION) {
auto localBuckets = &allThreadBuckets[thread_id * bucket_count];
std::fill(localBuckets, localBuckets + bucket_count, 0);
#pragma omp for schedule(static)
for (size_t i = 0; i < count; ++i)
localBuckets[(keys[i] >> bit) & mask]++;
#pragma omp for
for (size_t i = 0; i < bucket_count; i++) {
// Do a prefix sum of the elements in one bucket over all threads
size_t sum = 0;
for (size_t j = 0; j < thread_count; ++j) {
size_t old_sum = sum;
sum += allThreadBuckets[j * bucket_count + i];
allThreadBuckets[j * bucket_count + i] = old_sum;
}
allThreadBuckets[thread_count * bucket_count + i] = sum;
}
for (size_t i = 0, sum = 0; i < bucket_count; ++i) {
size_t old_sum = sum;
sum += allThreadBuckets[thread_count * bucket_count + i];
localBuckets[i] += old_sum;
}
#pragma omp for schedule(static)
for (size_t i = 0; i < count; ++i) {
size_t j = localBuckets[(keys[i] >> bit) & mask]++;
keys_copy[j] = keys[i];
values_copy[j] = values[i];
}
#pragma omp single
{
std::swap(keys_copy, keys);
std::swap(values_copy, values);
}
}
}
static uint32_t make_key(float x)
{
auto mask = uint32_t(1) << (sizeof(float) * CHAR_BIT - 1);
auto y = safe_cast<uint32_t>(x);
return (y & mask ? (-y) ^ mask : y) ^ mask;
}
private:
std::vector<size_t> allThreadBuckets;
};
} // namespace example_device
} // namespace anari
|
operators.c | // for license information, see the accompanying LICENSE file
#include "vars_nuclear.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <assert.h>
#include <mpi.h>
void i2xyz( const int i , int * ix , int * iy , int * iz , const int ny , const int nz );
void gradient_real( double * f , const int n , double * g_x , double * g_y , double * g_z , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz , const int ired )
{
/*
ired = 1: reduction
= anything else : no reduction
*/
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
double * gr_x , * gr_y , * gr_z , sum ;
int nx1 , ny1 , nz1 ;
assert( gr_x = malloc( n * sizeof( double ) ) ) ;
assert( gr_y = malloc( n * sizeof( double ) ) ) ;
assert( gr_z = malloc( n * sizeof( double ) ) ) ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
for( i = 0 ; i < n ; i++ )
{
*( gr_x + i ) = 0.0 ;
*( gr_y + i ) = 0.0 ;
*( gr_z + i ) = 0.0 ;
}
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
sum = 0. ;
#pragma omp parallel for default(shared) private(ix2) \
reduction(+:sum)
for( ix2 = 0 ; ix2 < nx ; ix2++ )
sum += creal( d1_x[ ix1 - ix2 + nx1 ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) ] ) ;
gr_x[ i ] += sum ;
sum = 0. ;
#pragma omp parallel for default(shared) private(iz2) \
reduction(+:sum)
for( iz2 = 0 ; iz2 < nz ; iz2++ )
sum += creal( d1_z[ iz1 - iz2 + nz1 ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) ] ) ;
gr_z[ i ] += sum ;
sum = 0. ;
#pragma omp parallel for default(shared) private(iy2) \
reduction(+:sum)
for( iy2 = 0 ; iy2 < ny ; iy2++ )
sum += creal( d1_y[ iy1 - iy2 + ny1 ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) ] ) ;
gr_y[ i ] += sum ;
}
if( ired == 1 ) /* all reduce */
{
MPI_Allreduce( gr_x , g_x , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gr_y , g_y , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gr_z , g_z , n , MPI_DOUBLE , MPI_SUM , comm ) ;
}
else {
#pragma omp parallel for default(shared) private(i)
for( i = 0 ; i < n ; i++ )
{
*( g_x + i ) = *( gr_x + i ) ;
*( g_y + i ) = *( gr_y + i ) ;
*( g_z + i ) = *( gr_z + i ) ;
}
}
free( gr_x ) ; free( gr_y ) ; free( gr_z ) ;
}
void gradient_real_orig( double * f , const int n , double * g_x , double * g_y , double * g_z , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz , const int ired )
{
/*
ired = 1: reduction
= anything else : no reduction
*/
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
double * gr_x , * gr_y , * gr_z ;
int nx1 , ny1 , nz1 ;
assert( gr_x = malloc( n * sizeof( double ) ) ) ;
assert( gr_y = malloc( n * sizeof( double ) ) ) ;
assert( gr_z = malloc( n * sizeof( double ) ) ) ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
for( i = 0 ; i < n ; i++ )
{
*( gr_x + i ) = 0.0 ;
*( gr_y + i ) = 0.0 ;
*( gr_z + i ) = 0.0 ;
}
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
for( j = 0 ; j < n ; j++ )
{
i2xyz( j , &ix2 , &iy2 , &iz2 , ny , nz ) ;
if( iy1 == iy2 && iz1 == iz2 )
gr_x[ i ] += creal( d1_x[ ix1 - ix2 + nx1 ] * f[ j ] ) ;
if( iy1 == iy2 && ix1 == ix2 )
gr_z[ i ] += creal( d1_z[ iz1 - iz2 + nz1 ] * f[ j ] ) ;
if( ix1 == ix2 && iz1 == iz2 )
gr_y[ i ] += creal( d1_y[ iy1 - iy2 + ny1 ] * f[ j ] ) ;
}
}
if( ired == 1 ) /* all reduce */
{
MPI_Allreduce( gr_x , g_x , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gr_y , g_y , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gr_z , g_z , n , MPI_DOUBLE , MPI_SUM , comm ) ;
}
else
for( i = 0 ; i < n ; i++ )
{
*( g_x + i ) = *( gr_x + i ) ;
*( g_y + i ) = *( gr_y + i ) ;
*( g_z + i ) = *( gr_z + i ) ;
}
free( gr_x ) ; free( gr_y ) ; free( gr_z ) ;
}
void gradient( double complex * f , const int n , double complex * g_x , double complex * g_y , double complex * g_z , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz , const int ired )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
int nx1 , ny1 , nz1 ;
double complex * gx , * gy , * gz , sum ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
#pragma omp parallel for default(shared) private(i)
for( i = 0 ; i < n ; i++ )
{
*( g_x + i ) = 0.0 + 0. * I ;
*( g_y + i ) = 0.0 + 0. * I ;
*( g_z + i ) = 0.0 + 0. * I ;
}
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
sum = 0. + I * 0. ;
#pragma omp parallel for default(shared) private(ix2) \
reduction(+:sum)
for( ix2 = 0 ; ix2 < nx ; ix2++ )
sum += d1_x[ ix1 - ix2 + nx1 ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) ] ;
g_x[ i ] += sum ;
sum = 0. + 0. * I ;
#pragma omp parallel for default(shared) private(iz2) \
reduction(+:sum)
for( iz2 = 0 ; iz2 < nz ; iz2++ )
sum += d1_z[ iz1 - iz2 + nz1 ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) ] ;
g_z[ i ] += sum ;
sum = 0. + 0. * I ;
#pragma omp parallel for default(shared) private(iy2) \
reduction(+:sum)
for( iy2 = 0 ; iy2 < ny ; iy2++ )
sum += d1_y[ iy1 - iy2 + ny1 ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) ] ;
g_y[ i ] += sum ;
}
if( ired == 1 )
{
assert( gx = malloc( n * sizeof( double ) ) ) ;
assert( gy = malloc( n * sizeof( double ) ) ) ;
assert( gz = malloc( n * sizeof( double ) ) ) ;
for( i = 0 ; i < n ; i++ )
{
gx[ i ] = g_x[ i ] ;
gy[ i ] = g_y[ i ] ;
gz[ i ] = g_z[ i ] ;
}
MPI_Allreduce( gx , g_x , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gy , g_y , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gz , g_z , n , MPI_DOUBLE , MPI_SUM , comm ) ;
free( gx ) ; free( gy ) ; free( gz ) ;
}
}
void gradient_ud( double complex * f , const int n , double complex * g_x , double complex * g_y , double complex * g_z , double complex * g_xd , double complex * g_yd , double complex * g_zd , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
int nx1 , ny1 , nz1 ;
double complex sum1 , sum2 ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
for( i = 0 ; i < nstop - nstart ; i++ )
{
g_x[ i ] = 0.0 + 0. * I ;
g_y[ i ] = 0.0 + 0. * I ;
g_z[ i ] = 0.0 + 0. * I ;
g_xd[ i ] = 0.0 + 0. * I ;
g_yd[ i ] = 0.0 + 0. * I ;
g_zd[ i ] = 0.0 + 0. * I ;
}
for( i = 0 ; i < nstop - nstart ; i++ )
{
i2xyz( i + nstart , &ix1 , &iy1 , &iz1 , ny , nz ) ;
sum1 = 0. + I * 0. ;
sum2 = 0. + I * 0. ;
#pragma omp parallel for default(shared) private(ix2) \
reduction(+:sum1,sum2)
for( ix2 = 0 ; ix2 < nx ; ix2++ )
{
sum1 += d1_x[ ix1 - ix2 + nx1 ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) ] ;
sum2 += d1_x[ ix1 - ix2 + nx1 ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) + n ] ;
}
g_x[ i ] += sum1 ;
g_xd[ i ] += sum2 ;
sum1 = 0. + I * 0. ;
sum2 = 0. + I * 0. ;
#pragma omp parallel for default(shared) private(iz2) \
reduction(+:sum1,sum2)
for( iz2 = 0 ; iz2 < nz ; iz2++ )
{
sum1 += d1_z[ iz1 - iz2 + nz1 ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) ] ;
sum2 += d1_z[ iz1 - iz2 + nz1 ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) + n ] ;
}
g_z[ i ] += sum1 ;
g_zd[ i ] += sum2 ;
sum1 = 0. + I * 0. ;
sum2 = 0. + I * 0. ;
#pragma omp parallel for default(shared) private(iy2) \
reduction(+:sum1,sum2)
for( iy2 = 0 ; iy2 < ny ; iy2++ )
{
sum1 += d1_y[ iy1 - iy2 + ny1 ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) ] ;
sum2 += d1_y[ iy1 - iy2 + ny1 ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) + n ] ;
}
g_y[ i ] += sum1 ;
g_yd[ i ] += sum2 ;
}
}
void gradient_orig( double complex * f , const int n , double complex * g_x , double complex * g_y , double complex * g_z , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz , const int ired )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
int nx1 , ny1 , nz1 ;
double complex * gx , * gy , * gz ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
for( i = 0 ; i < n ; i++ )
{
*( g_x + i ) = 0.0 + 0. * I ;
*( g_y + i ) = 0.0 + 0. * I ;
*( g_z + i ) = 0.0 + 0. * I ;
}
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
for( j = 0 ; j < n ; j++ )
{
i2xyz( j , &ix2 , &iy2 , &iz2 , ny , nz ) ;
if( iy1 == iy2 && iz1 == iz2 )
g_x[ i ] += d1_x[ ix1 - ix2 + nx1 ] * f[ j ] ;
if( iy1 == iy2 && ix1 == ix2 )
g_z[ i ] += d1_z[ iz1 - iz2 + nz1 ] * f[ j ] ;
if( ix1 == ix2 && iz1 == iz2 )
g_y[ i ] += d1_y[ iy1 - iy2 + ny1 ] * f[ j ] ;
}
}
if( ired == 1 )
{
assert( gx = malloc( n * sizeof( double ) ) ) ;
assert( gy = malloc( n * sizeof( double ) ) ) ;
assert( gz = malloc( n * sizeof( double ) ) ) ;
for( i = 0 ; i < n ; i++ )
{
gx[ i ] = g_x[ i ] ;
gy[ i ] = g_y[ i ] ;
gz[ i ] = g_z[ i ] ;
}
MPI_Allreduce( gx , g_x , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gy , g_y , n , MPI_DOUBLE , MPI_SUM , comm ) ;
MPI_Allreduce( gz , g_z , n , MPI_DOUBLE , MPI_SUM , comm ) ;
free( gx ) ; free( gy ) ; free( gz ) ;
}
}
void laplacean_complex( double complex * f , const int n , double complex * lapf , const int nstart , const int nstop , const MPI_Comm comm , double * k1d_x , double * k1d_y , double * k1d_z , const int nx , const int ny , const int nz , const int ired )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
double complex * tmp;
for( i = 0 ; i < n ; i++ )
*( lapf + i ) = 0.0 ;
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
for( ix2 = 0 ; ix2 < nx ; ix2++)
lapf[ i ] -= ( k1d_x[ abs( ix1 - ix2 ) ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) ] ) ;
for( iz2 = 0 ; iz2 < nz ; iz2++)
lapf[ i ] -= ( k1d_z[ abs( iz1 - iz2 ) ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) ] ) ;
for( iy2 = 0 ; iy2 < ny ; iy2++)
lapf[ i ] -= ( k1d_y[ abs( iy1 - iy2 ) ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) ] ) ;
}
if( ired == 1 )
{
assert( tmp = malloc( n * sizeof( double complex) ) ) ;
for( i = 0 ; i < n ; i++ )
*( tmp + i ) = *( lapf + i ) ;
MPI_Allreduce( tmp , lapf , n , MPI_DOUBLE_COMPLEX , MPI_SUM , comm ) ;
free( tmp ) ;
}
}
void laplacean( double * f , const int n , double * lapf , const int nstart , const int nstop , const MPI_Comm comm , double * k1d_x , double * k1d_y , double * k1d_z , const int nx , const int ny , const int nz , const int ired )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
double * tmp , sum ;
for( i = 0 ; i < n ; i++ )
*( lapf + i ) = 0.0 ;
for( i = nstart ; i < nstop ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
for( ix2 = 0 ; ix2 < nx ; ix2++)
lapf[ i ] -= ( k1d_x[ abs( ix1 - ix2 ) ] * f[ iz1 + nz * ( iy1 + ny * ix2 ) ] ) ;
for( iz2 = 0 ; iz2 < nz ; iz2++)
lapf[ i ] -= ( k1d_z[ abs( iz1 - iz2 ) ] * f[ iz2 + nz * ( iy1 + ny * ix1 ) ] ) ;
for( iy2 = 0 ; iy2 < ny ; iy2++)
lapf[ i ] -= ( k1d_y[ abs( iy1 - iy2 ) ] * f[ iz1 + nz * ( iy2 + ny * ix1 ) ] ) ;
}
if( ired == 1 )
{
assert( tmp = malloc( n * sizeof( double ) ) ) ;
for( i = 0 ; i < n ; i++ )
*( tmp + i ) = *( lapf + i ) ;
MPI_Allreduce( tmp , lapf , n , MPI_DOUBLE , MPI_SUM , comm ) ;
free( tmp ) ;
}
}
void diverg( double * fx , double * fy , double * fz , double * divf , const int n , const int nstart , const int nstop , const MPI_Comm comm , double complex * d1_x , double complex * d1_y , double complex * d1_z , const int nx , const int ny , const int nz )
{
int i , j ;
int ix1 , ix2 , iy1 , iy2 , iz1 , iz2 ;
int nx1 , ny1 , nz1 ;
double * divf_r ;
nx1 = nx - 1 ;
ny1 = ny - 1 ;
nz1 = nz - 1 ;
assert( divf_r = malloc( n * sizeof( double ) ) ) ;
for( i = 0 ; i < n ; i++ )
*( divf_r + i ) = 0.0 ;
for( i = 0 ; i < n ; i++ )
{
i2xyz( i , &ix1 , &iy1 , &iz1 , ny , nz ) ;
for( j = nstart ; j < nstop ; j++ )
{
i2xyz( j , &ix2 , &iy2 , &iz2 , ny , nz ) ;
if( iy1 == iy2 && iz1 == iz2 )
divf_r[ i ] += creal( d1_x[ ix1 - ix2 + nx1 ] * fx[ j ] ) ;
if( iy1 == iy2 && ix1 == ix2 )
divf_r[ i ] += creal( d1_z[ iz1 - iz2 + nz1 ] * fz[ j ] ) ;
if( ix1 == ix2 && iz1 == iz2 )
divf_r[ i ] += creal( d1_y[ iy1 - iy2 + ny1 ] * fy[ j ] ) ;
}
}
MPI_Allreduce( divf_r , divf , n , MPI_DOUBLE , MPI_SUM , comm ) ;
free( divf_r ) ;
}
void match_lattices( Lattice_arrays *latt , Lattice_arrays * latt3 , const int nx , const int ny , const int nz , const int nx3 , const int ny3 , const int nz3 , FFtransf_vars * fftrans , const double Lc ) {
int i , ix , iy , iz , ix3 , iy3 , iz3 ;
int nxyz = nx * ny * nz , nxyz3 = fftrans->nxyz3 ;
double fpi ,xx ;
fpi = 4. * acos( -1. ) * 197.3269631 / 137.035999679 ; /* 4 * pi * e2 */
assert( fftrans->i_l2s = malloc( nxyz3 * sizeof( int ) ) ) ;
assert( fftrans->fc = malloc( nxyz3 * sizeof( double ) ) ) ;
assert( fftrans->i_s2l = malloc( nxyz * sizeof( int ) ) ) ;
for( i = 0 ; i < nxyz3 ; i++ )
fftrans->i_l2s[ i ] = -1 ;
for( ix3 = 0 ; ix3 < nx ; ix3++ ){
ix=ix3;
for( iy3 = 0 ; iy3 < ny ; iy3++ ){
iy=iy3;
for( iz3 = 0 ; iz3 < nz ; iz3++ ){
iz=iz3;
fftrans->i_s2l[ iz + nz * ( iy + ny * ix ) ] = iz3 + nz3 * ( iy3 + ny3 * ix3 ) ;
fftrans->i_l2s[ iz3 + nz3 * ( iy3 + ny3 * ix3 ) ] = iz + nz * ( iy + ny * ix ) ;
}
}
}
fftrans->fc[ 0 ] = fpi * .5 * Lc * Lc ;
for( i = 1 ; i < nxyz3 ; i++ )
fftrans->fc[ i ] = fpi * ( 1. - cos( sqrt( latt3->kin[ i ] ) * Lc ) ) / latt3->kin[ i ] ;
free( latt3->kx ) ; free( latt3->ky ) ; free( latt3->kz ) ; free( latt3->xa ) ; free( latt3->ya ) ; free( latt3->za ) ; free( latt3->kin ) ;
}
void match_lattices_orig( Lattice_arrays *latt , Lattice_arrays * latt3 , const int nx , const int ny , const int nz , const int nx3 , const int ny3 , const int nz3 , FFtransf_vars * fftrans , const double Lc ) {
int i , ix , iy , iz , ix3 , iy3 , iz3 ;
int nxyz = nx * ny * nz , nxyz3 = fftrans->nxyz3 ;
double fpi , sqrt3 ;
sqrt3 = sqrt( 3. ) ;
fpi = 4. * acos( -1. ) * 197.3269631 / 137.035999679 ; /* 4 * pi * e2 */
assert( fftrans->i_l2s = malloc( nxyz3 * sizeof( int ) ) ) ;
assert( fftrans->fc = malloc( nxyz3 * sizeof( double ) ) ) ;
assert( fftrans->i_s2l = malloc( nxyz * sizeof( int ) ) ) ;
for( i = 0 ; i < nxyz3 ; i++ )
fftrans->i_l2s[ i ] = -1 ;
for( ix3 = nx ; ix3 < 2 * nx ; ix3++ ){
ix = ix3 - nx ;
for( iy3 = ny ; iy3 < 2 * ny ; iy3++ ){
iy = iy3 - ny ;
for( iz3 = nz ; iz3 < 2 * nz ; iz3++ ){
iz = iz3 - nz ;
fftrans->i_s2l[ iz + nz * ( iy + ny * ix ) ] = iz3 + nz3 * ( iy3 + ny3 * ix3 ) ;
fftrans->i_l2s[ iz3 + nz3 * ( iy3 + ny3 * ix3 ) ] = iz + nz * ( iy + ny * ix ) ;
}
}
}
fftrans->fc[ 0 ] = fpi * 1.5 * Lc * Lc ;
for( i = 1 ; i < nxyz3 ; i++ )
fftrans->fc[ i ] = fpi * ( 1. - cos( sqrt( latt3->kin[ i ] ) * sqrt3 * Lc ) ) / latt3->kin[ i ] ;
free( latt3->kx ) ; free( latt3->ky ) ; free( latt3->kz ) ; free( latt3->xa ) ; free( latt3->ya ) ; free( latt3->za ) ; free( latt3->kin ) ;
}
|
kmp_taskwait_depend_all.c | // RUN: %libomp-compile-and-run
// The runtime currently does not get dependency information from GCC.
// UNSUPPORTED: gcc
// Tests OMP 5.x task dependence "omp_all_memory",
// emulates compiler codegen versions for new dep kind
//
// Task tree created:
// task0 - task1 (in: i1, i2)
// \
// task2 (inoutset: i2), (in: i1)
// /
// task3 (omp_all_memory) via flag=0x80
// /
// task4 - task5 (in: i1, i2)
// /
// task6 (omp_all_memory) via addr=-1
// /
// task7 (omp_all_memory) via flag=0x80
// /
// task8 (in: i3)
// /
// task9 - no dependences
// /
// taskwait (omp_all_memory) (should not wait for task9, see prints)
//
#include <stdio.h>
#include <omp.h>
#ifdef _WIN32
#include <windows.h>
#define mysleep(n) Sleep(n)
#else
#include <unistd.h>
#define mysleep(n) usleep((n)*1000)
#endif
// to check the # of concurrent tasks (must be 1 for MTX, <3 for other kinds)
static int checker = 0;
static int err = 0;
static int taskwait_flag = 0;
#ifndef DELAY
// set delay interval in ms for dependent tasks
#define DELAY 100
#endif
// ---------------------------------------------------------------------------
// internal data to emulate compiler codegen
typedef struct DEP {
size_t addr;
size_t len;
unsigned char flags;
} dep;
#define DEP_ALL_MEM 0x80
typedef struct task {
void** shareds;
void* entry;
int part_id;
void* destr_thunk;
int priority;
long long device_id;
int f_priv;
} task_t;
#define TIED 1
typedef int(*entry_t)(int, task_t*);
typedef struct ID {
int reserved_1;
int flags;
int reserved_2;
int reserved_3;
char *psource;
} id;
// thunk routine for tasks with ALL dependency
int thunk_m(int gtid, task_t* ptask) {
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker;
th = omp_get_thread_num();
printf("task m_%d, th %d, checker %d\n", ptask->f_priv, th, lcheck);
if (lcheck != 1) { // no more than 1 task at a time
err++;
printf("Error m1, checker %d != 1\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // must still be equal to 1
if (lcheck != 1) {
err++;
printf("Error m2, checker %d != 1\n", lcheck);
}
#pragma omp atomic
--checker;
return 0;
}
// thunk routine for tasks with inoutset dependency
int thunk_s(int gtid, task_t* ptask) {
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1
th = omp_get_thread_num();
printf("task 2_%d, th %d, checker %d\n", ptask->f_priv, th, lcheck);
if (lcheck != 1) { // no more than 1 task at a time
err++;
printf("Error s1, checker %d != 1\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // must still be equal to 1
if (lcheck != 1) {
err++;
printf("Error s2, checker %d != 1\n", lcheck);
}
#pragma omp atomic
--checker;
return 0;
}
#ifdef __cplusplus
extern "C" {
#endif
int __kmpc_global_thread_num(id*);
task_t *__kmpc_omp_task_alloc(id *loc, int gtid, int flags,
size_t sz, size_t shar, entry_t rtn);
int __kmpc_omp_task_with_deps(id *loc, int gtid, task_t *task, int ndeps,
dep *dep_lst, int nd_noalias, dep *noalias_lst);
void __kmpc_omp_wait_deps(id *loc, int gtid, int ndeps, dep *dep_lst,
int ndeps_noalias, dep *noalias_dep_lst);
static id loc = {0, 2, 0, 0, ";file;func;0;0;;"};
#ifdef __cplusplus
} // extern "C"
#endif
// End of internal data
// ---------------------------------------------------------------------------
int main()
{
int i1,i2,i3;
omp_set_num_threads(8);
omp_set_dynamic(0);
#pragma omp parallel
{
#pragma omp single nowait
{
dep sdep[2];
task_t *ptr;
int gtid = __kmpc_global_thread_num(&loc);
int t = omp_get_thread_num();
// Create longest task first to ensure it is stolen.
// The test may hang if the task created last and
// executed by a thread which executes taskwait.
#pragma omp task
{ // task 9 - long running task
int flag;
int th = omp_get_thread_num();
printf("signalled independent task 9_%d, th %d started....\n", t, th);
// Wait for taskwait depend() to finish
// If the taskwait depend() improperly depends on this task
// to finish, then the test will hang and a timeout should trigger
while (1) {
#pragma omp atomic read
flag = taskwait_flag;
if (flag == 1)
break;
}
printf("signalled independent task 9_%d, th %d finished....\n", t, th);
}
#pragma omp task depend(in: i1, i2)
{ // task 0
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1 or 2
th = omp_get_thread_num();
printf("task 0_%d, th %d, checker %d\n", t, th, lcheck);
if (lcheck > 2 || lcheck < 1) {
err++; // no more than 2 tasks concurrently
printf("Error1, checker %d, not 1 or 2\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // 1 or 2
if (lcheck > 2 || lcheck < 1) {
#pragma omp atomic
err++;
printf("Error2, checker %d, not 1 or 2\n", lcheck);
}
#pragma omp atomic
--checker;
}
#pragma omp task depend(in: i1, i2)
{ // task 1
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1 or 2
th = omp_get_thread_num();
printf("task 1_%d, th %d, checker %d\n", t, th, lcheck);
if (lcheck > 2 || lcheck < 1) {
err++; // no more than 2 tasks concurrently
printf("Error3, checker %d, not 1 or 2\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // 1 or 2
if (lcheck > 2 || lcheck < 1) {
err++;
printf("Error4, checker %d, not 1 or 2\n", lcheck);
}
#pragma omp atomic
--checker;
}
// compiler codegen start
// task2
ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_s);
sdep[0].addr = (size_t)&i1;
sdep[0].len = 0; // not used
sdep[0].flags = 1; // IN
sdep[1].addr = (size_t)&i2;
sdep[1].len = 0; // not used
sdep[1].flags = 8; // INOUTSET
ptr->f_priv = t + 10; // init single first-private variable
__kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0);
// task3
ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m);
sdep[0].addr = (size_t)&i1; // to be ignored
sdep[0].len = 0; // not used
sdep[0].flags = 1; // IN
sdep[1].addr = 0;
sdep[1].len = 0; // not used
sdep[1].flags = DEP_ALL_MEM; // omp_all_memory
ptr->f_priv = t + 20; // init single first-private variable
__kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0);
// compiler codegen end
#pragma omp task depend(in: i1, i2)
{ // task 4
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1 or 2
th = omp_get_thread_num();
printf("task 4_%d, th %d, checker %d\n", t, th, lcheck);
if (lcheck > 2 || lcheck < 1) {
err++; // no more than 2 tasks concurrently
printf("Error5, checker %d, not 1 or 2\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // 1 or 2
if (lcheck > 2 || lcheck < 1) {
err++;
printf("Error6, checker %d, not 1 or 2\n", lcheck);
}
#pragma omp atomic
--checker;
}
#pragma omp task depend(in: i1, i2)
{ // task 5
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1 or 2
th = omp_get_thread_num();
printf("task 5_%d, th %d, checker %d\n", t, th, lcheck);
if (lcheck > 2 || lcheck < 1) {
err++; // no more than 2 tasks concurrently
printf("Error7, checker %d, not 1 or 2\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker; // 1 or 2
if (lcheck > 2 || lcheck < 1) {
err++;
printf("Error8, checker %d, not 1 or 2\n", lcheck);
}
#pragma omp atomic
--checker;
}
// compiler codegen start
// task6
ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m);
sdep[0].addr = (size_t)(-1); // omp_all_memory
sdep[0].len = 0; // not used
sdep[0].flags = 2; // OUT
ptr->f_priv = t + 30; // init single first-private variable
__kmpc_omp_task_with_deps(&loc, gtid, ptr, 1, sdep, 0, 0);
// task7
ptr = __kmpc_omp_task_alloc(&loc, gtid, TIED, sizeof(task_t), 0, thunk_m);
sdep[0].addr = 0;
sdep[0].len = 0; // not used
sdep[0].flags = DEP_ALL_MEM; // omp_all_memory
sdep[1].addr = (size_t)&i3; // to be ignored
sdep[1].len = 0; // not used
sdep[1].flags = 4; // MUTEXINOUTSET
ptr->f_priv = t + 40; // init single first-private variable
__kmpc_omp_task_with_deps(&loc, gtid, ptr, 2, sdep, 0, 0);
// compiler codegen end
#pragma omp task depend(in: i3)
{ // task 8
int lcheck, th;
#pragma omp atomic capture
lcheck = ++checker; // 1
th = omp_get_thread_num();
printf("task 8_%d, th %d, checker %d\n", t, th, lcheck);
if (lcheck != 1) {
err++;
printf("Error9, checker %d, != 1\n", lcheck);
}
mysleep(DELAY);
#pragma omp atomic read
lcheck = checker;
if (lcheck != 1) {
err++;
printf("Error10, checker %d, != 1\n", lcheck);
}
#pragma omp atomic
--checker;
}
mysleep(1); // wait a bit to ensure at least first task is stolen
// #pragma omp taskwait depend(omp_all_memory: out)
printf("all 10 tasks generated;\n"
"taskwait depend(omp_all_memory: out) started, th %d\n", t);
__kmpc_omp_wait_deps(&loc, gtid, 1, sdep, 0, 0);
#pragma omp atomic write
taskwait_flag = 1;
printf("taskwait depend(omp_all_memory: out) passed, th %d\n", t);
fflush(0);
} // single
} // parallel
if (err == 0 && checker == 0) {
printf("passed\n");
return 0;
} else {
printf("failed, err = %d, checker = %d\n", err, checker);
return 1;
}
}
|
memory.c | /******************************************************************************
* Copyright (c) 1998 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Memory management utilities
*
*****************************************************************************/
#include "_hypre_utilities.h"
#include "_hypre_utilities.hpp"
#if defined(HYPRE_USE_UMALLOC)
#undef HYPRE_USE_UMALLOC
#endif
/******************************************************************************
*
* Helper routines
*
*****************************************************************************/
/*--------------------------------------------------------------------------
* hypre_OutOfMemory
*--------------------------------------------------------------------------*/
static inline void
hypre_OutOfMemory(size_t size)
{
hypre_error_w_msg(HYPRE_ERROR_MEMORY, "Out of memory trying to allocate too many bytes\n");
hypre_assert(0);
fflush(stdout);
}
static inline void
hypre_WrongMemoryLocation()
{
hypre_error_w_msg(HYPRE_ERROR_MEMORY,
"Wrong HYPRE MEMORY location: Only HYPRE_MEMORY_HOST, HYPRE_MEMORY_DEVICE and HYPRE_MEMORY_HOST_PINNED are supported!\n");
hypre_assert(0);
fflush(stdout);
}
void
hypre_CheckMemoryLocation(void *ptr, hypre_MemoryLocation location)
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) || defined(HYPRE_USING_SYCL)
if (!ptr)
{
return;
}
hypre_MemoryLocation location_ptr;
hypre_GetPointerLocation(ptr, &location_ptr);
/* do not use hypre_assert, which has alloc and free;
* will create an endless loop otherwise */
assert(location == location_ptr);
#endif
}
/*==========================================================================
* Physical memory location (hypre_MemoryLocation) interface
*==========================================================================*/
/*--------------------------------------------------------------------------
* Memset
*--------------------------------------------------------------------------*/
static inline void
hypre_HostMemset(void *ptr, HYPRE_Int value, size_t num)
{
memset(ptr, value, num);
}
static inline void
hypre_DeviceMemset(void *ptr, HYPRE_Int value, size_t num)
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
#pragma omp target teams distribute parallel for is_device_ptr(ptr)
for (size_t i = 0; i < num; i++)
{
((unsigned char *) ptr)[i] = (unsigned char) value;
}
#else
memset(ptr, value, num);
HYPRE_OMPOffload(hypre__offload_device_num, ptr, num, "update", "to");
#endif
/* HYPRE_CUDA_CALL( cudaDeviceSynchronize() ); */
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemset(ptr, value, num) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemset(ptr, value, num) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( (hypre_HandleComputeStream(hypre_handle()))->memset(ptr, value, num).wait() );
#endif
}
static inline void
hypre_UnifiedMemset(void *ptr, HYPRE_Int value, size_t num)
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
#pragma omp target teams distribute parallel for is_device_ptr(ptr)
for (size_t i = 0; i < num; i++)
{
((unsigned char *) ptr)[i] = (unsigned char) value;
}
#else
memset(ptr, value, num);
HYPRE_OMPOffload(hypre__offload_device_num, ptr, num, "update", "to");
#endif
/* HYPRE_CUDA_CALL( cudaDeviceSynchronize() ); */
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemset(ptr, value, num) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemset(ptr, value, num) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( (hypre_HandleComputeStream(hypre_handle()))->memset(ptr, value, num).wait() );
#endif
}
/*--------------------------------------------------------------------------
* Memprefetch
*--------------------------------------------------------------------------*/
static inline void
hypre_UnifiedMemPrefetch(void *ptr, size_t size, hypre_MemoryLocation location)
{
if (!size)
{
return;
}
#if defined(HYPRE_DEBUG)
hypre_CheckMemoryLocation(ptr, hypre_MEMORY_UNIFIED);
#endif
#if defined(HYPRE_USING_CUDA)
if (location == hypre_MEMORY_DEVICE)
{
HYPRE_CUDA_CALL( cudaMemPrefetchAsync(ptr, size, hypre_HandleDevice(hypre_handle()),
hypre_HandleComputeStream(hypre_handle())) );
}
else if (location == hypre_MEMORY_HOST)
{
HYPRE_CUDA_CALL( cudaMemPrefetchAsync(ptr, size, cudaCpuDeviceId,
hypre_HandleComputeStream(hypre_handle())) );
}
#endif
#if defined(HYPRE_USING_HIP)
// Not currently implemented for HIP, but leaving place holder
/*
*if (location == hypre_MEMORY_DEVICE)
*{
* HYPRE_HIP_CALL( hipMemPrefetchAsync(ptr, size, hypre_HandleDevice(hypre_handle()),
* hypre_HandleComputeStream(hypre_handle())) );
*}
*else if (location == hypre_MEMORY_HOST)
*{
* HYPRE_CUDA_CALL( hipMemPrefetchAsync(ptr, size, cudaCpuDeviceId,
* hypre_HandleComputeStream(hypre_handle())) );
*}
*/
#endif
#if defined(HYPRE_USING_SYCL)
if (location == hypre_MEMORY_DEVICE)
{
HYPRE_SYCL_CALL( hypre_HandleComputeStream(hypre_handle())->prefetch(ptr, size).wait() );
}
#endif
}
/*--------------------------------------------------------------------------
* Malloc
*--------------------------------------------------------------------------*/
static inline void *
hypre_HostMalloc(size_t size, HYPRE_Int zeroinit)
{
void *ptr = NULL;
#if defined(HYPRE_USING_UMPIRE_HOST)
hypre_umpire_host_pooled_allocate(&ptr, size);
if (zeroinit)
{
memset(ptr, 0, size);
}
#else
if (zeroinit)
{
ptr = calloc(size, 1);
}
else
{
ptr = malloc(size);
}
#endif
return ptr;
}
static inline void *
hypre_DeviceMalloc(size_t size, HYPRE_Int zeroinit)
{
void *ptr = NULL;
if ( hypre_HandleUserDeviceMalloc(hypre_handle()) )
{
hypre_HandleUserDeviceMalloc(hypre_handle())(&ptr, size);
}
else
{
#if defined(HYPRE_USING_UMPIRE_DEVICE)
hypre_umpire_device_pooled_allocate(&ptr, size);
#else
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
ptr = omp_target_alloc(size, hypre__offload_device_num);
#else
ptr = malloc(size + sizeof(size_t));
size_t *sp = (size_t*) ptr;
sp[0] = size;
ptr = (void *) (&sp[1]);
HYPRE_OMPOffload(hypre__offload_device_num, ptr, size, "enter", "alloc");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_DEVICE_POOL)
HYPRE_CUDA_CALL( hypre_CachingMallocDevice(&ptr, size) );
#else
HYPRE_CUDA_CALL( cudaMalloc(&ptr, size) );
#endif
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMalloc(&ptr, size) );
#endif
#if defined(HYPRE_USING_SYCL)
ptr = (void *)sycl::malloc_device(size, *(hypre_HandleComputeStream(hypre_handle())));
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_DEVICE) */
}
if (ptr && zeroinit)
{
hypre_DeviceMemset(ptr, 0, size);
}
return ptr;
}
static inline void *
hypre_UnifiedMalloc(size_t size, HYPRE_Int zeroinit)
{
void *ptr = NULL;
#if defined(HYPRE_USING_UMPIRE_UM)
hypre_umpire_um_pooled_allocate(&ptr, size);
#else
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
ptr = omp_target_alloc(size, hypre__offload_device_num);
#else
ptr = malloc(size + sizeof(size_t));
size_t *sp = (size_t*) ptr;
sp[0] = size;
ptr = (void *) (&sp[1]);
HYPRE_OMPOffload(hypre__offload_device_num, ptr, size, "enter", "alloc");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_DEVICE_POOL)
HYPRE_CUDA_CALL( hypre_CachingMallocManaged(&ptr, size) );
#else
HYPRE_CUDA_CALL( cudaMallocManaged(&ptr, size, cudaMemAttachGlobal) );
#endif
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMallocManaged(&ptr, size, hipMemAttachGlobal) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( ptr = (void *)sycl::malloc_shared(size,
*(hypre_HandleComputeStream(hypre_handle()))) );
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_UM) */
/* prefecth to device */
if (ptr)
{
hypre_UnifiedMemPrefetch(ptr, size, hypre_MEMORY_DEVICE);
}
if (ptr && zeroinit)
{
hypre_UnifiedMemset(ptr, 0, size);
}
return ptr;
}
static inline void *
hypre_HostPinnedMalloc(size_t size, HYPRE_Int zeroinit)
{
void *ptr = NULL;
#if defined(HYPRE_USING_UMPIRE_PINNED)
hypre_umpire_pinned_pooled_allocate(&ptr, size);
#else
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMallocHost(&ptr, size) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipHostMalloc(&ptr, size) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( ptr = (void *)sycl::malloc_host(size,
*(hypre_HandleComputeStream(hypre_handle()))) );
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_PINNED) */
if (ptr && zeroinit)
{
hypre_HostMemset(ptr, 0, size);
}
return ptr;
}
static inline void *
hypre_MAlloc_core(size_t size, HYPRE_Int zeroinit, hypre_MemoryLocation location)
{
if (size == 0)
{
return NULL;
}
void *ptr = NULL;
switch (location)
{
case hypre_MEMORY_HOST :
ptr = hypre_HostMalloc(size, zeroinit);
break;
case hypre_MEMORY_DEVICE :
ptr = hypre_DeviceMalloc(size, zeroinit);
break;
case hypre_MEMORY_UNIFIED :
ptr = hypre_UnifiedMalloc(size, zeroinit);
break;
case hypre_MEMORY_HOST_PINNED :
ptr = hypre_HostPinnedMalloc(size, zeroinit);
break;
default :
hypre_WrongMemoryLocation();
}
if (!ptr)
{
hypre_OutOfMemory(size);
hypre_MPI_Abort(hypre_MPI_COMM_WORLD, -1);
}
return ptr;
}
void *
_hypre_MAlloc(size_t size, hypre_MemoryLocation location)
{
return hypre_MAlloc_core(size, 0, location);
}
/*--------------------------------------------------------------------------
* Free
*--------------------------------------------------------------------------*/
static inline void
hypre_HostFree(void *ptr)
{
#if defined(HYPRE_USING_UMPIRE_HOST)
hypre_umpire_host_pooled_free(ptr);
#else
free(ptr);
#endif
}
static inline void
hypre_DeviceFree(void *ptr)
{
if ( hypre_HandleUserDeviceMfree(hypre_handle()) )
{
hypre_HandleUserDeviceMfree(hypre_handle())(ptr);
}
else
{
#if defined(HYPRE_USING_UMPIRE_DEVICE)
hypre_umpire_device_pooled_free(ptr);
#else
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
omp_target_free(ptr, hypre__offload_device_num);
#else
HYPRE_OMPOffload(hypre__offload_device_num, ptr, ((size_t *) ptr)[-1], "exit", "delete");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_DEVICE_POOL)
HYPRE_CUDA_CALL( hypre_CachingFreeDevice(ptr) );
#else
HYPRE_CUDA_CALL( cudaFree(ptr) );
#endif
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipFree(ptr) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( sycl::free(ptr, *(hypre_HandleComputeStream(hypre_handle()))) );
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_DEVICE) */
}
}
static inline void
hypre_UnifiedFree(void *ptr)
{
#if defined(HYPRE_USING_UMPIRE_UM)
hypre_umpire_um_pooled_free(ptr);
#else
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
omp_target_free(ptr, hypre__offload_device_num);
#else
HYPRE_OMPOffload(hypre__offload_device_num, ptr, ((size_t *) ptr)[-1], "exit", "delete");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_DEVICE_POOL)
HYPRE_CUDA_CALL( hypre_CachingFreeManaged(ptr) );
#else
HYPRE_CUDA_CALL( cudaFree(ptr) );
#endif
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipFree(ptr) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( sycl::free(ptr, *(hypre_HandleComputeStream(hypre_handle()))) );
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_UM) */
}
static inline void
hypre_HostPinnedFree(void *ptr)
{
#if defined(HYPRE_USING_UMPIRE_PINNED)
hypre_umpire_pinned_pooled_free(ptr);
#else
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaFreeHost(ptr) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipHostFree(ptr) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( sycl::free(ptr, *(hypre_HandleComputeStream(hypre_handle()))) );
#endif
#endif /* #if defined(HYPRE_USING_UMPIRE_PINNED) */
}
static inline void
hypre_Free_core(void *ptr, hypre_MemoryLocation location)
{
if (!ptr)
{
return;
}
#if defined(HYPRE_DEBUG)
hypre_CheckMemoryLocation(ptr, location);
#endif
switch (location)
{
case hypre_MEMORY_HOST :
hypre_HostFree(ptr);
break;
case hypre_MEMORY_DEVICE :
hypre_DeviceFree(ptr);
break;
case hypre_MEMORY_UNIFIED :
hypre_UnifiedFree(ptr);
break;
case hypre_MEMORY_HOST_PINNED :
hypre_HostPinnedFree(ptr);
break;
default :
hypre_WrongMemoryLocation();
}
}
void
_hypre_Free(void *ptr, hypre_MemoryLocation location)
{
hypre_Free_core(ptr, location);
}
/*--------------------------------------------------------------------------
* Memcpy
*--------------------------------------------------------------------------*/
static inline void
hypre_Memcpy_core(void *dst, void *src, size_t size, hypre_MemoryLocation loc_dst,
hypre_MemoryLocation loc_src)
{
#if defined(HYPRE_USING_SYCL)
sycl::queue* q = hypre_HandleComputeStream(hypre_handle());
#endif
if (dst == NULL || src == NULL)
{
if (size)
{
hypre_printf("hypre_Memcpy warning: copy %ld bytes from %p to %p !\n", size, src, dst);
hypre_assert(0);
}
return;
}
if (dst == src)
{
return;
}
#if defined(HYPRE_DEBUG)
if (size > 0)
{
hypre_CheckMemoryLocation(dst, loc_dst);
hypre_CheckMemoryLocation(src, loc_src);
}
#endif
/* Totally 4 x 4 = 16 cases */
/* 4: Host <-- Host, Host <-- Pinned,
* Pinned <-- Host, Pinned <-- Pinned.
*/
if ( loc_dst != hypre_MEMORY_DEVICE && loc_dst != hypre_MEMORY_UNIFIED &&
loc_src != hypre_MEMORY_DEVICE && loc_src != hypre_MEMORY_UNIFIED )
{
memcpy(dst, src, size);
return;
}
/* 3: UVM <-- Device, Device <-- UVM, UVM <-- UVM */
if ( (loc_dst == hypre_MEMORY_UNIFIED && loc_src == hypre_MEMORY_DEVICE) ||
(loc_dst == hypre_MEMORY_DEVICE && loc_src == hypre_MEMORY_UNIFIED) ||
(loc_dst == hypre_MEMORY_UNIFIED && loc_src == hypre_MEMORY_UNIFIED) )
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_device_num, hypre__offload_device_num);
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy(dst, src, size, cudaMemcpyDeviceToDevice) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyDeviceToDevice) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
/* 2: UVM <-- Host, UVM <-- Pinned */
if (loc_dst == hypre_MEMORY_UNIFIED)
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_device_num, hypre__offload_host_num);
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyHostToDevice) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
/* 2: Host <-- UVM, Pinned <-- UVM */
if (loc_src == hypre_MEMORY_UNIFIED)
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_host_num, hypre__offload_device_num);
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy(dst, src, size, cudaMemcpyDeviceToHost) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyDeviceToHost) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
/* 2: Device <-- Host, Device <-- Pinned */
if ( loc_dst == hypre_MEMORY_DEVICE && (loc_src == hypre_MEMORY_HOST ||
loc_src == hypre_MEMORY_HOST_PINNED) )
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_device_num, hypre__offload_host_num);
#else
memcpy(dst, src, size);
HYPRE_OMPOffload(hypre__offload_device_num, dst, size, "update", "to");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy(dst, src, size, cudaMemcpyHostToDevice) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyHostToDevice) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
/* 2: Host <-- Device, Pinned <-- Device */
if ( (loc_dst == hypre_MEMORY_HOST || loc_dst == hypre_MEMORY_HOST_PINNED) &&
loc_src == hypre_MEMORY_DEVICE )
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_host_num, hypre__offload_device_num);
#else
HYPRE_OMPOffload(hypre__offload_device_num, src, size, "update", "from");
memcpy(dst, src, size);
#endif
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy( dst, src, size, cudaMemcpyDeviceToHost) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyDeviceToHost) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
/* 1: Device <-- Device */
if (loc_dst == hypre_MEMORY_DEVICE && loc_src == hypre_MEMORY_DEVICE)
{
#if defined(HYPRE_USING_DEVICE_OPENMP)
#if defined(HYPRE_DEVICE_OPENMP_ALLOC)
omp_target_memcpy(dst, src, size, 0, 0, hypre__offload_device_num, hypre__offload_device_num);
#else
HYPRE_OMPOffload(hypre__offload_device_num, src, size, "update", "from");
memcpy(dst, src, size);
HYPRE_OMPOffload(hypre__offload_device_num, dst, size, "update", "to");
#endif
#endif
#if defined(HYPRE_USING_CUDA)
HYPRE_CUDA_CALL( cudaMemcpy(dst, src, size, cudaMemcpyDeviceToDevice) );
#endif
#if defined(HYPRE_USING_HIP)
HYPRE_HIP_CALL( hipMemcpy(dst, src, size, hipMemcpyDeviceToDevice) );
#endif
#if defined(HYPRE_USING_SYCL)
HYPRE_SYCL_CALL( q->memcpy(dst, src, size).wait() );
#endif
return;
}
hypre_WrongMemoryLocation();
}
/*--------------------------------------------------------------------------*
* ExecPolicy
*--------------------------------------------------------------------------*/
static inline HYPRE_ExecutionPolicy
hypre_GetExecPolicy1_core(hypre_MemoryLocation location)
{
HYPRE_ExecutionPolicy exec = HYPRE_EXEC_UNDEFINED;
switch (location)
{
case hypre_MEMORY_HOST :
case hypre_MEMORY_HOST_PINNED :
exec = HYPRE_EXEC_HOST;
break;
case hypre_MEMORY_DEVICE :
exec = HYPRE_EXEC_DEVICE;
break;
case hypre_MEMORY_UNIFIED :
#if defined(HYPRE_USING_GPU)
exec = hypre_HandleDefaultExecPolicy(hypre_handle());
#endif
break;
default :
hypre_WrongMemoryLocation();
}
hypre_assert(exec != HYPRE_EXEC_UNDEFINED);
return exec;
}
/* for binary operation */
static inline HYPRE_ExecutionPolicy
hypre_GetExecPolicy2_core(hypre_MemoryLocation location1,
hypre_MemoryLocation location2)
{
HYPRE_ExecutionPolicy exec = HYPRE_EXEC_UNDEFINED;
/* HOST_PINNED has the same exec policy as HOST */
if (location1 == hypre_MEMORY_HOST_PINNED)
{
location1 = hypre_MEMORY_HOST;
}
if (location2 == hypre_MEMORY_HOST_PINNED)
{
location2 = hypre_MEMORY_HOST;
}
/* no policy for these combinations */
if ( (location1 == hypre_MEMORY_HOST && location2 == hypre_MEMORY_DEVICE) ||
(location2 == hypre_MEMORY_HOST && location1 == hypre_MEMORY_DEVICE) )
{
exec = HYPRE_EXEC_UNDEFINED;
}
/* this should never happen */
if ( (location1 == hypre_MEMORY_UNIFIED && location2 == hypre_MEMORY_DEVICE) ||
(location2 == hypre_MEMORY_UNIFIED && location1 == hypre_MEMORY_DEVICE) )
{
exec = HYPRE_EXEC_UNDEFINED;
}
if (location1 == hypre_MEMORY_UNIFIED && location2 == hypre_MEMORY_UNIFIED)
{
#if defined(HYPRE_USING_GPU)
exec = hypre_HandleDefaultExecPolicy(hypre_handle());
#endif
}
if (location1 == hypre_MEMORY_HOST || location2 == hypre_MEMORY_HOST)
{
exec = HYPRE_EXEC_HOST;
}
if (location1 == hypre_MEMORY_DEVICE || location2 == hypre_MEMORY_DEVICE)
{
exec = HYPRE_EXEC_DEVICE;
}
hypre_assert(exec != HYPRE_EXEC_UNDEFINED);
return exec;
}
/*==========================================================================
* Conceptual memory location (HYPRE_MemoryLocation) interface
*==========================================================================*/
/*--------------------------------------------------------------------------
* hypre_Memset
* "Sets the first num bytes of the block of memory pointed by ptr to the specified value
* (*** value is interpreted as an unsigned char ***)"
* http://www.cplusplus.com/reference/cstring/memset/
*--------------------------------------------------------------------------*/
void *
hypre_Memset(void *ptr, HYPRE_Int value, size_t num, HYPRE_MemoryLocation location)
{
if (num == 0)
{
return ptr;
}
if (ptr == NULL)
{
if (num)
{
hypre_printf("hypre_Memset warning: set values for %ld bytes at %p !\n", num, ptr);
}
return ptr;
}
#if defined(HYPRE_DEBUG)
hypre_CheckMemoryLocation(ptr, hypre_GetActualMemLocation(location));
#endif
switch (hypre_GetActualMemLocation(location))
{
case hypre_MEMORY_HOST :
case hypre_MEMORY_HOST_PINNED :
hypre_HostMemset(ptr, value, num);
break;
case hypre_MEMORY_DEVICE :
hypre_DeviceMemset(ptr, value, num);
break;
case hypre_MEMORY_UNIFIED :
hypre_UnifiedMemset(ptr, value, num);
break;
default :
hypre_WrongMemoryLocation();
}
return ptr;
}
/*--------------------------------------------------------------------------
* Memprefetch
*--------------------------------------------------------------------------*/
void
hypre_MemPrefetch(void *ptr, size_t size, HYPRE_MemoryLocation location)
{
hypre_UnifiedMemPrefetch( ptr, size, hypre_GetActualMemLocation(location) );
}
/*--------------------------------------------------------------------------*
* hypre_MAlloc, hypre_CAlloc
*--------------------------------------------------------------------------*/
void *
hypre_MAlloc(size_t size, HYPRE_MemoryLocation location)
{
return hypre_MAlloc_core(size, 0, hypre_GetActualMemLocation(location));
}
void *
hypre_CAlloc( size_t count, size_t elt_size, HYPRE_MemoryLocation location)
{
return hypre_MAlloc_core(count * elt_size, 1, hypre_GetActualMemLocation(location));
}
/*--------------------------------------------------------------------------
* hypre_Free
*--------------------------------------------------------------------------*/
void
hypre_Free(void *ptr, HYPRE_MemoryLocation location)
{
hypre_Free_core(ptr, hypre_GetActualMemLocation(location));
}
/*--------------------------------------------------------------------------
* hypre_Memcpy
*--------------------------------------------------------------------------*/
void
hypre_Memcpy(void *dst, void *src, size_t size, HYPRE_MemoryLocation loc_dst,
HYPRE_MemoryLocation loc_src)
{
hypre_Memcpy_core( dst, src, size, hypre_GetActualMemLocation(loc_dst),
hypre_GetActualMemLocation(loc_src) );
}
/*--------------------------------------------------------------------------
* hypre_ReAlloc
*--------------------------------------------------------------------------*/
void *
hypre_ReAlloc(void *ptr, size_t size, HYPRE_MemoryLocation location)
{
if (size == 0)
{
hypre_Free(ptr, location);
return NULL;
}
if (ptr == NULL)
{
return hypre_MAlloc(size, location);
}
if (hypre_GetActualMemLocation(location) != hypre_MEMORY_HOST)
{
hypre_printf("hypre_TReAlloc only works with HYPRE_MEMORY_HOST; Use hypre_TReAlloc_v2 instead!\n");
hypre_assert(0);
hypre_MPI_Abort(hypre_MPI_COMM_WORLD, -1);
return NULL;
}
#if defined(HYPRE_USING_UMPIRE_HOST)
ptr = hypre_umpire_host_pooled_realloc(ptr, size);
#else
ptr = realloc(ptr, size);
#endif
if (!ptr)
{
hypre_OutOfMemory(size);
}
return ptr;
}
void *
hypre_ReAlloc_v2(void *ptr, size_t old_size, size_t new_size, HYPRE_MemoryLocation location)
{
if (new_size == 0)
{
hypre_Free(ptr, location);
return NULL;
}
if (ptr == NULL)
{
return hypre_MAlloc(new_size, location);
}
void *new_ptr = hypre_MAlloc(new_size, location);
size_t smaller_size = new_size > old_size ? old_size : new_size;
hypre_Memcpy(new_ptr, ptr, smaller_size, location, location);
hypre_Free(ptr, location);
ptr = new_ptr;
if (!ptr)
{
hypre_OutOfMemory(new_size);
}
return ptr;
}
/*--------------------------------------------------------------------------*
* hypre_GetExecPolicy: return execution policy based on memory locations
*--------------------------------------------------------------------------*/
/* for unary operation */
HYPRE_ExecutionPolicy
hypre_GetExecPolicy1(HYPRE_MemoryLocation location)
{
return hypre_GetExecPolicy1_core(hypre_GetActualMemLocation(location));
}
/* for binary operation */
HYPRE_ExecutionPolicy
hypre_GetExecPolicy2(HYPRE_MemoryLocation location1,
HYPRE_MemoryLocation location2)
{
return hypre_GetExecPolicy2_core(hypre_GetActualMemLocation(location1),
hypre_GetActualMemLocation(location2));
}
/*--------------------------------------------------------------------------
* Query the actual memory location pointed by ptr
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_GetPointerLocation(const void *ptr, hypre_MemoryLocation *memory_location)
{
HYPRE_Int ierr = 0;
#if defined(HYPRE_USING_GPU)
*memory_location = hypre_MEMORY_UNDEFINED;
#if defined(HYPRE_USING_CUDA)
struct cudaPointerAttributes attr;
#if (CUDART_VERSION >= 10000)
#if (CUDART_VERSION >= 11000)
HYPRE_CUDA_CALL( cudaPointerGetAttributes(&attr, ptr) );
#else
cudaError_t err = cudaPointerGetAttributes(&attr, ptr);
if (err != cudaSuccess)
{
ierr = 1;
/* clear the error */
cudaGetLastError();
}
#endif
if (attr.type == cudaMemoryTypeUnregistered)
{
*memory_location = hypre_MEMORY_HOST;
}
else if (attr.type == cudaMemoryTypeHost)
{
*memory_location = hypre_MEMORY_HOST_PINNED;
}
else if (attr.type == cudaMemoryTypeDevice)
{
*memory_location = hypre_MEMORY_DEVICE;
}
else if (attr.type == cudaMemoryTypeManaged)
{
*memory_location = hypre_MEMORY_UNIFIED;
}
#else
cudaError_t err = cudaPointerGetAttributes(&attr, ptr);
if (err != cudaSuccess)
{
ierr = 1;
/* clear the error */
cudaGetLastError();
if (err == cudaErrorInvalidValue)
{
*memory_location = hypre_MEMORY_HOST;
}
}
else if (attr.isManaged)
{
*memory_location = hypre_MEMORY_UNIFIED;
}
else if (attr.memoryType == cudaMemoryTypeDevice)
{
*memory_location = hypre_MEMORY_DEVICE;
}
else if (attr.memoryType == cudaMemoryTypeHost)
{
*memory_location = hypre_MEMORY_HOST_PINNED;
}
#endif // CUDART_VERSION >= 10000
#endif // defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_HIP)
struct hipPointerAttribute_t attr;
*memory_location = hypre_MEMORY_UNDEFINED;
hipError_t err = hipPointerGetAttributes(&attr, ptr);
if (err != hipSuccess)
{
ierr = 1;
/* clear the error */
hipGetLastError();
if (err == hipErrorInvalidValue)
{
*memory_location = hypre_MEMORY_HOST;
}
}
else if (attr.isManaged)
{
*memory_location = hypre_MEMORY_UNIFIED;
}
else if (attr.memoryType == hipMemoryTypeDevice)
{
*memory_location = hypre_MEMORY_DEVICE;
}
else if (attr.memoryType == hipMemoryTypeHost)
{
*memory_location = hypre_MEMORY_HOST_PINNED;
}
#endif // defined(HYPRE_USING_HIP)
#if defined(HYPRE_USING_SYCL)
/* If the device is not setup, then all allocations are assumed to be on the host */
*memory_location = hypre_MEMORY_HOST;
if (hypre_HandleDeviceData(hypre_handle()))
{
if (hypre_HandleDevice(hypre_handle()))
{
sycl::usm::alloc allocType;
allocType = sycl::get_pointer_type(ptr, (hypre_HandleComputeStream(hypre_handle()))->get_context());
if (allocType == sycl::usm::alloc::unknown)
{
*memory_location = hypre_MEMORY_HOST;
}
else if (allocType == sycl::usm::alloc::host)
{
*memory_location = hypre_MEMORY_HOST_PINNED;
}
else if (allocType == sycl::usm::alloc::device)
{
*memory_location = hypre_MEMORY_DEVICE;
}
else if (allocType == sycl::usm::alloc::shared)
{
*memory_location = hypre_MEMORY_UNIFIED;
}
}
}
#endif //HYPRE_USING_SYCL
#else /* #if defined(HYPRE_USING_GPU) */
*memory_location = hypre_MEMORY_HOST;
#endif
return ierr;
}
#if defined(HYPRE_USING_MEMORY_TRACKER)
/*--------------------------------------------------------------------------
* Memory tracker
* do not use hypre_T* in the following since we don't want to track them *
*--------------------------------------------------------------------------*/
hypre_MemoryTracker *
hypre_MemoryTrackerCreate()
{
hypre_MemoryTracker *ptr = (hypre_MemoryTracker *) calloc(1, sizeof(hypre_MemoryTracker));
return ptr;
}
void
hypre_MemoryTrackerDestroy(hypre_MemoryTracker *tracker)
{
if (tracker)
{
free(tracker->data);
free(tracker);
}
}
void
hypre_MemoryTrackerInsert(const char *action,
void *ptr,
size_t nbytes,
hypre_MemoryLocation memory_location,
const char *filename,
const char *function,
HYPRE_Int line)
{
if (ptr == NULL)
{
return;
}
hypre_MemoryTracker *tracker = hypre_memory_tracker();
if (tracker->alloced_size <= tracker->actual_size)
{
tracker->alloced_size = 2 * tracker->alloced_size + 1;
tracker->data = (hypre_MemoryTrackerEntry *) realloc(tracker->data,
tracker->alloced_size * sizeof(hypre_MemoryTrackerEntry));
}
hypre_assert(tracker->actual_size < tracker->alloced_size);
hypre_MemoryTrackerEntry *entry = tracker->data + tracker->actual_size;
sprintf(entry->_action, "%s", action);
entry->_ptr = ptr;
entry->_nbytes = nbytes;
entry->_memory_location = memory_location;
sprintf(entry->_filename, "%s", filename);
sprintf(entry->_function, "%s", function);
entry->_line = line;
/* -1 is the initial value */
entry->_pair = (size_t) -1;
tracker->actual_size ++;
}
/* do not use hypre_printf, hypre_fprintf, which have TAlloc
* endless loop "for (i = 0; i < tracker->actual_size; i++)" otherwise */
HYPRE_Int
hypre_PrintMemoryTracker()
{
HYPRE_Int myid, ierr = 0;
char filename[256];
FILE *file;
size_t i, j;
hypre_MemoryTracker *tracker = hypre_memory_tracker();
hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid);
hypre_sprintf(filename, "HypreMemoryTrack.log.%05d", myid);
if ((file = fopen(filename, "a")) == NULL)
{
fprintf(stderr, "Error: can't open output file %s\n", filename);
return hypre_error_flag;
}
fprintf(file, "==== Operations:\n");
fprintf(file,
" ID EVENT ADDRESS BYTE LOCATION FILE(LINE) FUNCTION | Memory ( H P D U )\n");
size_t totl_bytes[hypre_MEMORY_UNIFIED + 1] = {0};
size_t peak_bytes[hypre_MEMORY_UNIFIED + 1] = {0};
size_t curr_bytes[hypre_MEMORY_UNIFIED + 1] = {0};
for (i = 0; i < tracker->actual_size; i++)
{
if (strstr(tracker->data[i]._action, "alloc") != NULL)
{
totl_bytes[tracker->data[i]._memory_location] += tracker->data[i]._nbytes;
curr_bytes[tracker->data[i]._memory_location] += tracker->data[i]._nbytes;
peak_bytes[tracker->data[i]._memory_location] =
hypre_max( curr_bytes[tracker->data[i]._memory_location],
peak_bytes[tracker->data[i]._memory_location] );
/* for each unpaired "alloc", find its "free" */
if (tracker->data[i]._pair != (size_t) -1)
{
if ( tracker->data[i]._pair >= tracker->actual_size ||
tracker->data[tracker->data[i]._pair]._pair != i)
{
fprintf(stderr, "hypre memory tracker internal error!\n");
hypre_MPI_Abort(hypre_MPI_COMM_WORLD, 1);
}
continue;
}
for (j = i + 1; j < tracker->actual_size; j++)
{
if ( strstr(tracker->data[j]._action, "free") != NULL &&
tracker->data[j]._pair == (size_t) -1 &&
tracker->data[i]._ptr == tracker->data[j]._ptr &&
tracker->data[i]._memory_location == tracker->data[j]._memory_location )
{
tracker->data[i]._pair = j;
tracker->data[j]._pair = i;
tracker->data[j]._nbytes = tracker->data[i]._nbytes;
break;
}
}
if (tracker->data[i]._pair == (size_t) -1)
{
fprintf(stderr, "%6zu: %16p may not freed\n", i, tracker->data[i]._ptr );
}
}
else if (strstr(tracker->data[i]._action, "free") != NULL)
{
size_t pair = tracker->data[i]._pair;
if (pair == (size_t) -1)
{
fprintf(stderr, "%6zu: unpaired free at %16p\n", i, tracker->data[i]._ptr );
}
else
{
curr_bytes[tracker->data[i]._memory_location] -= tracker->data[pair]._nbytes;
}
}
if (i < tracker->prev_end)
{
continue;
}
char memory_location[256];
char nbytes[32];
if (tracker->data[i]._memory_location == hypre_MEMORY_HOST)
{
sprintf(memory_location, "%s", "HOST");
}
else if (tracker->data[i]._memory_location == hypre_MEMORY_HOST_PINNED)
{
sprintf(memory_location, "%s", "HOST_PINNED");
}
else if (tracker->data[i]._memory_location == hypre_MEMORY_DEVICE)
{
sprintf(memory_location, "%s", "DEVICE");
}
else if (tracker->data[i]._memory_location == hypre_MEMORY_UNIFIED)
{
sprintf(memory_location, "%s", "UNIFIED");
}
else
{
sprintf(memory_location, "%s", "UNDEFINED");
}
if (tracker->data[i]._nbytes != (size_t) -1)
{
sprintf(nbytes, "%zu", tracker->data[i]._nbytes);
}
else
{
sprintf(nbytes, "%s", "");
}
fprintf(file, " %6zu %12s %16p %10s %16s %40s (%5d) %50s | %12zu %12zu %12zu %12zu\n",
i,
tracker->data[i]._action,
tracker->data[i]._ptr,
nbytes,
memory_location,
tracker->data[i]._filename,
tracker->data[i]._line,
tracker->data[i]._function,
curr_bytes[hypre_MEMORY_HOST],
curr_bytes[hypre_MEMORY_HOST_PINNED],
curr_bytes[hypre_MEMORY_DEVICE],
curr_bytes[hypre_MEMORY_UNIFIED]
);
}
fprintf(file, "\n==== Total allocated (byte):\n");
fprintf(file, "HOST: %16zu, HOST_PINNED %16zu, DEVICE %16zu, UNIFIED %16zu\n",
totl_bytes[hypre_MEMORY_HOST],
totl_bytes[hypre_MEMORY_HOST_PINNED],
totl_bytes[hypre_MEMORY_DEVICE],
totl_bytes[hypre_MEMORY_UNIFIED]);
fprintf(file, "\n==== Peak (byte):\n");
fprintf(file, "HOST: %16zu, HOST_PINNED %16zu, DEVICE %16zu, UNIFIED %16zu\n",
peak_bytes[hypre_MEMORY_HOST],
peak_bytes[hypre_MEMORY_HOST_PINNED],
peak_bytes[hypre_MEMORY_DEVICE],
peak_bytes[hypre_MEMORY_UNIFIED]);
fprintf(file, "\n==== Reachable (byte):\n");
fprintf(file, "HOST: %16zu, HOST_PINNED %16zu, DEVICE %16zu, UNIFIED %16zu\n",
curr_bytes[hypre_MEMORY_HOST],
curr_bytes[hypre_MEMORY_HOST_PINNED],
curr_bytes[hypre_MEMORY_DEVICE],
curr_bytes[hypre_MEMORY_UNIFIED]);
fprintf(file, "\n==== Warnings:\n");
for (i = 0; i < tracker->actual_size; i++)
{
if (tracker->data[i]._pair == (size_t) -1)
{
if (strstr(tracker->data[i]._action, "alloc") != NULL)
{
fprintf(file, "%6zu: %p may have not been freed\n", i, tracker->data[i]._ptr );
}
else if (strstr(tracker->data[i]._action, "free") != NULL)
{
fprintf(file, "%6zu: unpaired free at %16p\n", i, tracker->data[i]._ptr );
}
}
}
fclose(file);
tracker->prev_end = tracker->actual_size;
return ierr;
}
#endif
/*--------------------------------------------------------------------------*
* Memory Pool
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_SetCubMemPoolSize(hypre_uint cub_bin_growth,
hypre_uint cub_min_bin,
hypre_uint cub_max_bin,
size_t cub_max_cached_bytes)
{
#if defined(HYPRE_USING_CUDA)
#if defined(HYPRE_USING_DEVICE_POOL)
hypre_HandleCubBinGrowth(hypre_handle()) = cub_bin_growth;
hypre_HandleCubMinBin(hypre_handle()) = cub_min_bin;
hypre_HandleCubMaxBin(hypre_handle()) = cub_max_bin;
hypre_HandleCubMaxCachedBytes(hypre_handle()) = cub_max_cached_bytes;
//TODO XXX RL: cub_min_bin, cub_max_bin are not (re)set
if (hypre_HandleCubDevAllocator(hypre_handle()))
{
hypre_HandleCubDevAllocator(hypre_handle()) -> SetMaxCachedBytes(cub_max_cached_bytes);
}
if (hypre_HandleCubUvmAllocator(hypre_handle()))
{
hypre_HandleCubUvmAllocator(hypre_handle()) -> SetMaxCachedBytes(cub_max_cached_bytes);
}
#endif
#endif
return hypre_error_flag;
}
HYPRE_Int
HYPRE_SetGPUMemoryPoolSize(HYPRE_Int bin_growth,
HYPRE_Int min_bin,
HYPRE_Int max_bin,
size_t max_cached_bytes)
{
return hypre_SetCubMemPoolSize(bin_growth, min_bin, max_bin, max_cached_bytes);
}
#if defined(HYPRE_USING_DEVICE_POOL)
cudaError_t
hypre_CachingMallocDevice(void **ptr, size_t nbytes)
{
if (!hypre_HandleCubDevAllocator(hypre_handle()))
{
hypre_HandleCubDevAllocator(hypre_handle()) =
hypre_DeviceDataCubCachingAllocatorCreate( hypre_HandleCubBinGrowth(hypre_handle()),
hypre_HandleCubMinBin(hypre_handle()),
hypre_HandleCubMaxBin(hypre_handle()),
hypre_HandleCubMaxCachedBytes(hypre_handle()),
false,
false,
false );
}
return hypre_HandleCubDevAllocator(hypre_handle()) -> DeviceAllocate(ptr, nbytes);
}
cudaError_t
hypre_CachingFreeDevice(void *ptr)
{
return hypre_HandleCubDevAllocator(hypre_handle()) -> DeviceFree(ptr);
}
cudaError_t
hypre_CachingMallocManaged(void **ptr, size_t nbytes)
{
if (!hypre_HandleCubUvmAllocator(hypre_handle()))
{
hypre_HandleCubUvmAllocator(hypre_handle()) =
hypre_DeviceDataCubCachingAllocatorCreate( hypre_HandleCubBinGrowth(hypre_handle()),
hypre_HandleCubMinBin(hypre_handle()),
hypre_HandleCubMaxBin(hypre_handle()),
hypre_HandleCubMaxCachedBytes(hypre_handle()),
false,
false,
true );
}
return hypre_HandleCubUvmAllocator(hypre_handle()) -> DeviceAllocate(ptr, nbytes);
}
cudaError_t
hypre_CachingFreeManaged(void *ptr)
{
return hypre_HandleCubUvmAllocator(hypre_handle()) -> DeviceFree(ptr);
}
hypre_cub_CachingDeviceAllocator *
hypre_DeviceDataCubCachingAllocatorCreate(hypre_uint bin_growth,
hypre_uint min_bin,
hypre_uint max_bin,
size_t max_cached_bytes,
bool skip_cleanup,
bool debug,
bool use_managed_memory)
{
hypre_cub_CachingDeviceAllocator *allocator =
new hypre_cub_CachingDeviceAllocator( bin_growth,
min_bin,
max_bin,
max_cached_bytes,
skip_cleanup,
debug,
use_managed_memory );
return allocator;
}
void
hypre_DeviceDataCubCachingAllocatorDestroy(hypre_DeviceData *data)
{
delete hypre_DeviceDataCubDevAllocator(data);
delete hypre_DeviceDataCubUvmAllocator(data);
}
#endif // #if defined(HYPRE_USING_DEVICE_POOL)
#if defined(HYPRE_USING_UMPIRE_HOST)
HYPRE_Int
hypre_umpire_host_pooled_allocate(void **ptr, size_t nbytes)
{
hypre_Handle *handle = hypre_handle();
const char *resource_name = "HOST";
const char *pool_name = hypre_HandleUmpireHostPoolName(handle);
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
umpire_allocator pooled_allocator;
if ( umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name) )
{
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
}
else
{
umpire_allocator allocator;
umpire_resourcemanager_get_allocator_by_name(rm_ptr, resource_name, &allocator);
umpire_resourcemanager_make_allocator_pool(rm_ptr, pool_name, allocator,
hypre_HandleUmpireHostPoolSize(handle),
hypre_HandleUmpireBlockSize(handle), &pooled_allocator);
hypre_HandleOwnUmpireHostPool(handle) = 1;
}
*ptr = umpire_allocator_allocate(&pooled_allocator, nbytes);
return hypre_error_flag;
}
HYPRE_Int
hypre_umpire_host_pooled_free(void *ptr)
{
hypre_Handle *handle = hypre_handle();
const char *pool_name = hypre_HandleUmpireHostPoolName(handle);
umpire_allocator pooled_allocator;
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
hypre_assert(umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name));
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
umpire_allocator_deallocate(&pooled_allocator, ptr);
return hypre_error_flag;
}
void *
hypre_umpire_host_pooled_realloc(void *ptr, size_t size)
{
hypre_Handle *handle = hypre_handle();
const char *pool_name = hypre_HandleUmpireHostPoolName(handle);
umpire_allocator pooled_allocator;
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
hypre_assert(umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name));
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
ptr = umpire_resourcemanager_reallocate_with_allocator(rm_ptr, ptr, size, pooled_allocator);
return ptr;
}
#endif
#if defined(HYPRE_USING_UMPIRE_DEVICE)
HYPRE_Int
hypre_umpire_device_pooled_allocate(void **ptr, size_t nbytes)
{
hypre_Handle *handle = hypre_handle();
const hypre_int device_id = hypre_HandleDevice(handle);
char resource_name[16];
const char *pool_name = hypre_HandleUmpireDevicePoolName(handle);
hypre_sprintf(resource_name, "%s::%d", "DEVICE", device_id);
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
umpire_allocator pooled_allocator;
if ( umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name) )
{
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
}
else
{
umpire_allocator allocator;
umpire_resourcemanager_get_allocator_by_name(rm_ptr, resource_name, &allocator);
umpire_resourcemanager_make_allocator_pool(rm_ptr, pool_name, allocator,
hypre_HandleUmpireDevicePoolSize(handle),
hypre_HandleUmpireBlockSize(handle), &pooled_allocator);
hypre_HandleOwnUmpireDevicePool(handle) = 1;
}
*ptr = umpire_allocator_allocate(&pooled_allocator, nbytes);
return hypre_error_flag;
}
HYPRE_Int
hypre_umpire_device_pooled_free(void *ptr)
{
hypre_Handle *handle = hypre_handle();
const char *pool_name = hypre_HandleUmpireDevicePoolName(handle);
umpire_allocator pooled_allocator;
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
hypre_assert(umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name));
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
umpire_allocator_deallocate(&pooled_allocator, ptr);
return hypre_error_flag;
}
#endif
#if defined(HYPRE_USING_UMPIRE_UM)
HYPRE_Int
hypre_umpire_um_pooled_allocate(void **ptr, size_t nbytes)
{
hypre_Handle *handle = hypre_handle();
const char *resource_name = "UM";
const char *pool_name = hypre_HandleUmpireUMPoolName(handle);
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
umpire_allocator pooled_allocator;
if ( umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name) )
{
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
}
else
{
umpire_allocator allocator;
umpire_resourcemanager_get_allocator_by_name(rm_ptr, resource_name, &allocator);
umpire_resourcemanager_make_allocator_pool(rm_ptr, pool_name, allocator,
hypre_HandleUmpireUMPoolSize(handle),
hypre_HandleUmpireBlockSize(handle), &pooled_allocator);
hypre_HandleOwnUmpireUMPool(handle) = 1;
}
*ptr = umpire_allocator_allocate(&pooled_allocator, nbytes);
return hypre_error_flag;
}
HYPRE_Int
hypre_umpire_um_pooled_free(void *ptr)
{
hypre_Handle *handle = hypre_handle();
const char *pool_name = hypre_HandleUmpireUMPoolName(handle);
umpire_allocator pooled_allocator;
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
hypre_assert(umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name));
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
umpire_allocator_deallocate(&pooled_allocator, ptr);
return hypre_error_flag;
}
#endif
#if defined(HYPRE_USING_UMPIRE_PINNED)
HYPRE_Int
hypre_umpire_pinned_pooled_allocate(void **ptr, size_t nbytes)
{
hypre_Handle *handle = hypre_handle();
const char *resource_name = "PINNED";
const char *pool_name = hypre_HandleUmpirePinnedPoolName(handle);
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
umpire_allocator pooled_allocator;
if ( umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name) )
{
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
}
else
{
umpire_allocator allocator;
umpire_resourcemanager_get_allocator_by_name(rm_ptr, resource_name, &allocator);
umpire_resourcemanager_make_allocator_pool(rm_ptr, pool_name, allocator,
hypre_HandleUmpirePinnedPoolSize(handle),
hypre_HandleUmpireBlockSize(handle), &pooled_allocator);
hypre_HandleOwnUmpirePinnedPool(handle) = 1;
}
*ptr = umpire_allocator_allocate(&pooled_allocator, nbytes);
return hypre_error_flag;
}
HYPRE_Int
hypre_umpire_pinned_pooled_free(void *ptr)
{
const hypre_Handle *handle = hypre_handle();
const char *pool_name = hypre_HandleUmpirePinnedPoolName(handle);
umpire_allocator pooled_allocator;
umpire_resourcemanager *rm_ptr = &hypre_HandleUmpireResourceMan(handle);
hypre_assert(umpire_resourcemanager_is_allocator_name(rm_ptr, pool_name));
umpire_resourcemanager_get_allocator_by_name(rm_ptr, pool_name, &pooled_allocator);
umpire_allocator_deallocate(&pooled_allocator, ptr);
return hypre_error_flag;
}
#endif
|
sl3_fmt_plug.c | /*
* SL3 unlocking. Password is always 15 digits. Run with "-mask=?d"
*
* Input format (IMEI is put in "login field"):
* IMEI:hash
*
* IMEI is 14 or 15 digits 0-9 (only 14 are used)
* hash is hex lowercase (0-9, a-f)
*
* Copyright (c) 2017 magnum.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_sl3;
#elif FMT_REGISTERS_H
john_register_one(&fmt_sl3);
#else
#include "arch.h"
//#undef SIMD_COEF_32
//#undef SIMD_PARA_SHA1
//#undef _OPENMP
#include <string.h>
#ifdef _OPENMP
#ifdef SIMD_COEF_64
#ifndef OMP_SCALE
#define OMP_SCALE 1024
#endif
#else
#ifndef OMP_SCALE
#define OMP_SCALE 2048
#endif
#endif
#include <omp.h>
#endif
#include "misc.h"
#include "formats.h"
#include "options.h"
#include "johnswap.h"
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#endif
#include "simd-intrinsics.h"
#include "common.h"
#include "sha.h"
#include "sl3_common.h"
#include "base64_convert.h"
#include "memdbg.h"
#define FORMAT_LABEL "SL3"
#define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*4*SIMD_COEF_32 ) //for endianity conversion
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static unsigned char *saved_salt;
#ifdef SIMD_COEF_32
static uint32_t (*saved_key)[SHA_BUF_SIZ*NBKEYS];
static uint32_t (*crypt_key)[BINARY_SIZE/4*NBKEYS];
static unsigned int *saved_len;
#else
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static uint32_t (*crypt_key)[BINARY_SIZE / 4];
#endif
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
int omp_t;
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
#ifndef SIMD_COEF_32
saved_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_key));
crypt_key = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*crypt_key));
#else
saved_len = mem_calloc(self->params.max_keys_per_crypt,
sizeof(*saved_len));
saved_key = mem_calloc_align(self->params.max_keys_per_crypt/NBKEYS,
sizeof(*saved_key), MEM_ALIGN_SIMD);
crypt_key = mem_calloc_align(self->params.max_keys_per_crypt/NBKEYS,
sizeof(*crypt_key), MEM_ALIGN_SIMD);
#endif
}
static void done(void)
{
MEM_FREE(crypt_key);
MEM_FREE(saved_key);
#ifdef SIMD_COEF_32
MEM_FREE(saved_len);
#endif
}
static void *get_binary(char *ciphertext) {
static char *out;
if (!out)
out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD);
ciphertext += SL3_MAGIC_LENGTH + 14 + 1;
memset(out, 0, BINARY_SIZE);
base64_convert(ciphertext, e_b64_hex, 2 * BINARY_SIZE,
out, e_b64_raw, BINARY_SIZE, 0, 0);
#ifdef SIMD_COEF_32
alter_endianity((unsigned char*)out, BINARY_SIZE);
#endif
return (void*)out;
}
/* set_key() just fills saved_key[index][n] with key[n] - '0' */
static void set_key(char *_key, int index)
{
#ifdef SIMD_COEF_32
char key[PLAINTEXT_LENGTH + 1];
char *d = key;
int i = PLAINTEXT_LENGTH;
#if ARCH_ALLOWS_UNALIGNED
const uint32_t *wkey = (uint32_t*)key;
#else
char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint32_t));
const uint32_t *wkey = (uint32_t*)(is_aligned(key, sizeof(uint32_t)) ?
key : strcpy(buf_aligned, key));
#endif
uint32_t *keybuffer = &((uint32_t*)saved_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32];
uint32_t *keybuf_word = keybuffer;
/*
* FIXME: Can we do this more efficiently? Perhaps using SIMD and 0x30303030.
*/
do {
*d++ = *_key++ - '0';
} while (i--);
*keybuf_word = JOHNSWAP(*wkey++);
keybuf_word += SIMD_COEF_32;
*keybuf_word = JOHNSWAP(*wkey++);
keybuf_word += SIMD_COEF_32;
*keybuf_word = JOHNSWAP(*wkey++);
keybuf_word += SIMD_COEF_32;
*keybuf_word = JOHNSWAP(*wkey);
#else
char *d = saved_key[index];
int i = PLAINTEXT_LENGTH;
do {
*d++ = *_key++ - '0';
} while (i--);
#endif
}
/* ...and get_key() reverses the (- '0'). */
static char *get_key(int index) {
static char out[PLAINTEXT_LENGTH + 1];
#ifdef SIMD_COEF_32
unsigned int i;
for (i = 0; i < PLAINTEXT_LENGTH; i++)
out[i] = ((char*)saved_key)[GETPOS(i, index)] + '0';
out[PLAINTEXT_LENGTH] = 0;
#else
char *s = saved_key[index], *d = out;
int i = PLAINTEXT_LENGTH;
while (i--) {
*d++ = *s++ + '0';
};
*d = 0;
#endif
return out;
}
static int cmp_all(void *binary, int count) {
unsigned int index;
for (index = 0; index < count; index++)
#ifdef SIMD_COEF_32
if (((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + index/SIMD_COEF_32*5*SIMD_COEF_32])
#else
if ( ((uint32_t*)binary)[0] == ((uint32_t*)&(crypt_key[index][0]))[0] )
#endif
return 1;
return 0;
}
static int cmp_exact(char *source, int index)
{
return 1;
}
static int cmp_one(void *binary, int index)
{
#ifdef SIMD_COEF_32
int i;
for (i = 0; i < BINARY_SIZE/sizeof(uint32_t); i++)
if (((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*5*SIMD_COEF_32+i*SIMD_COEF_32])
return 0;
return 1;
#else
return !memcmp(binary, crypt_key[index], BINARY_SIZE);
#endif
}
static void set_salt(void *salt) {
saved_salt = salt;
}
#ifdef SIMD_COEF_32
inline static void set_onesalt(int index)
{
unsigned int i, idx = index % NBKEYS;
unsigned char *sk = (unsigned char*)&saved_key[index / NBKEYS];
for (i = 0; i < SALT_SIZE; ++i)
sk[GETPOS(PLAINTEXT_LENGTH + i, idx)] = saved_salt[i];
sk[GETPOS(PLAINTEXT_LENGTH + SALT_SIZE, idx)] = 0x80;
((unsigned int*)sk)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + idx/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = (PLAINTEXT_LENGTH + SALT_SIZE) << 3;
}
#endif
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index = 0;
#ifdef _OPENMP
#ifdef SIMD_COEF_32
int inc = NBKEYS;
#else
int inc = 1;
#endif
#pragma omp parallel for
for (index=0; index < count; index += inc)
#endif
{
#ifdef SIMD_COEF_32
unsigned int i;
for (i=0;i<NBKEYS;i++)
set_onesalt(i + index);
SIMDSHA1body(saved_key[index/NBKEYS], crypt_key[index/NBKEYS], NULL, SSEi_MIXED_IN);
#else
SHA_CTX ctx;
SHA1_Init( &ctx );
SHA1_Update( &ctx, (unsigned char*)saved_key[index], PLAINTEXT_LENGTH);
SHA1_Update( &ctx, (unsigned char*)saved_salt, SALT_SIZE);
SHA1_Final( (unsigned char*)crypt_key[index], &ctx);
#endif
}
return count;
}
#ifdef SIMD_COEF_32
#define HASH_OFFSET (index&(SIMD_COEF_32-1))+(((unsigned int)index%NBKEYS)/SIMD_COEF_32)*SIMD_COEF_32*5
static int get_hash_0(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_6; }
#else
static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; }
static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; }
static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; }
static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; }
static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; }
static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; }
static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; }
#endif
struct fmt_main fmt_sl3 = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
PLAINTEXT_MINLEN,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_OMP | FMT_OMP_BAD,
{ NULL },
{ SL3_MAGIC },
sl3_tests
}, {
init,
done,
fmt_default_reset,
sl3_prepare,
sl3_valid,
fmt_default_split,
get_binary,
sl3_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
},
sl3_salt_hash,
NULL,
set_salt,
set_key,
get_key,
fmt_default_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
}
};
#endif /* plugin stanza */
|
Stmt.h | //===- Stmt.h - Classes for representing statements -------------*- 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 Stmt interface and subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMT_H
#define LLVM_CLANG_AST_STMT_H
#include "clang/AST/DeclGroup.h"
#include "clang/AST/StmtIterator.h"
#include "clang/Basic/CapturedStmt.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <string>
namespace llvm {
class FoldingSetNodeID;
} // namespace llvm
namespace clang {
class ASTContext;
class Attr;
class CapturedDecl;
class Decl;
class Expr;
class LabelDecl;
class ODRHash;
class PrinterHelper;
struct PrintingPolicy;
class RecordDecl;
class SourceManager;
class StringLiteral;
class Token;
class VarDecl;
//===----------------------------------------------------------------------===//
// AST classes for statements.
//===----------------------------------------------------------------------===//
/// Stmt - This represents one statement.
///
class alignas(void *) Stmt {
public:
enum StmtClass {
NoStmtClass = 0,
#define STMT(CLASS, PARENT) CLASS##Class,
#define STMT_RANGE(BASE, FIRST, LAST) \
first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class,
#define LAST_STMT_RANGE(BASE, FIRST, LAST) \
first##BASE##Constant=FIRST##Class, last##BASE##Constant=LAST##Class
#define ABSTRACT_STMT(STMT)
#include "clang/AST/StmtNodes.inc"
};
// Make vanilla 'new' and 'delete' illegal for Stmts.
protected:
friend class ASTStmtReader;
friend class ASTStmtWriter;
void *operator new(size_t bytes) noexcept {
llvm_unreachable("Stmts cannot be allocated with regular 'new'.");
}
void operator delete(void *data) noexcept {
llvm_unreachable("Stmts cannot be released with regular 'delete'.");
}
//===--- Statement bitfields classes ---===//
class StmtBitfields {
friend class ASTStmtReader;
friend class ASTStmtWriter;
friend class Stmt;
/// The statement class.
unsigned sClass : 8;
/// This bit is set only for the Stmts that are the structured-block of
/// OpenMP executable directives. Directives that have a structured block
/// are called "non-standalone" directives.
/// I.e. those returned by OMPExecutableDirective::getStructuredBlock().
unsigned IsOMPStructuredBlock : 1;
};
enum { NumStmtBits = 9 };
class NullStmtBitfields {
friend class ASTStmtReader;
friend class ASTStmtWriter;
friend class NullStmt;
unsigned : NumStmtBits;
/// True if the null statement was preceded by an empty macro, e.g:
/// @code
/// #define CALL(x)
/// CALL(0);
/// @endcode
unsigned HasLeadingEmptyMacro : 1;
/// The location of the semi-colon.
SourceLocation SemiLoc;
};
class CompoundStmtBitfields {
friend class ASTStmtReader;
friend class CompoundStmt;
unsigned : NumStmtBits;
unsigned NumStmts : 32 - NumStmtBits;
/// The location of the opening "{".
SourceLocation LBraceLoc;
};
class LabelStmtBitfields {
friend class LabelStmt;
unsigned : NumStmtBits;
SourceLocation IdentLoc;
};
class AttributedStmtBitfields {
friend class ASTStmtReader;
friend class AttributedStmt;
unsigned : NumStmtBits;
/// Number of attributes.
unsigned NumAttrs : 32 - NumStmtBits;
/// The location of the attribute.
SourceLocation AttrLoc;
};
class IfStmtBitfields {
friend class ASTStmtReader;
friend class IfStmt;
unsigned : NumStmtBits;
/// True if this if statement is a constexpr if.
unsigned IsConstexpr : 1;
/// True if this if statement has storage for an else statement.
unsigned HasElse : 1;
/// True if this if statement has storage for a variable declaration.
unsigned HasVar : 1;
/// True if this if statement has storage for an init statement.
unsigned HasInit : 1;
/// The location of the "if".
SourceLocation IfLoc;
};
class SwitchStmtBitfields {
friend class SwitchStmt;
unsigned : NumStmtBits;
/// True if the SwitchStmt has storage for an init statement.
unsigned HasInit : 1;
/// True if the SwitchStmt has storage for a condition variable.
unsigned HasVar : 1;
/// If the SwitchStmt is a switch on an enum value, records whether all
/// the enum values were covered by CaseStmts. The coverage information
/// value is meant to be a hint for possible clients.
unsigned AllEnumCasesCovered : 1;
/// The location of the "switch".
SourceLocation SwitchLoc;
};
class WhileStmtBitfields {
friend class ASTStmtReader;
friend class WhileStmt;
unsigned : NumStmtBits;
/// True if the WhileStmt has storage for a condition variable.
unsigned HasVar : 1;
/// The location of the "while".
SourceLocation WhileLoc;
};
class DoStmtBitfields {
friend class DoStmt;
unsigned : NumStmtBits;
/// The location of the "do".
SourceLocation DoLoc;
};
class ForStmtBitfields {
friend class ForStmt;
unsigned : NumStmtBits;
/// The location of the "for".
SourceLocation ForLoc;
};
class GotoStmtBitfields {
friend class GotoStmt;
friend class IndirectGotoStmt;
unsigned : NumStmtBits;
/// The location of the "goto".
SourceLocation GotoLoc;
};
class ContinueStmtBitfields {
friend class ContinueStmt;
unsigned : NumStmtBits;
/// The location of the "continue".
SourceLocation ContinueLoc;
};
class BreakStmtBitfields {
friend class BreakStmt;
unsigned : NumStmtBits;
/// The location of the "break".
SourceLocation BreakLoc;
};
class ReturnStmtBitfields {
friend class ReturnStmt;
unsigned : NumStmtBits;
/// True if this ReturnStmt has storage for an NRVO candidate.
unsigned HasNRVOCandidate : 1;
/// The location of the "return".
SourceLocation RetLoc;
};
class SwitchCaseBitfields {
friend class SwitchCase;
friend class CaseStmt;
unsigned : NumStmtBits;
/// Used by CaseStmt to store whether it is a case statement
/// of the form case LHS ... RHS (a GNU extension).
unsigned CaseStmtIsGNURange : 1;
/// The location of the "case" or "default" keyword.
SourceLocation KeywordLoc;
};
//===--- Expression bitfields classes ---===//
class ExprBitfields {
friend class ASTStmtReader; // deserialization
friend class AtomicExpr; // ctor
friend class BlockDeclRefExpr; // ctor
friend class CallExpr; // ctor
friend class CXXConstructExpr; // ctor
friend class CXXDependentScopeMemberExpr; // ctor
friend class CXXNewExpr; // ctor
friend class CXXUnresolvedConstructExpr; // ctor
friend class DeclRefExpr; // computeDependence
friend class DependentScopeDeclRefExpr; // ctor
friend class DesignatedInitExpr; // ctor
friend class Expr;
friend class InitListExpr; // ctor
friend class ObjCArrayLiteral; // ctor
friend class ObjCDictionaryLiteral; // ctor
friend class ObjCMessageExpr; // ctor
friend class OffsetOfExpr; // ctor
friend class OpaqueValueExpr; // ctor
friend class OverloadExpr; // ctor
friend class ParenListExpr; // ctor
friend class PseudoObjectExpr; // ctor
friend class ShuffleVectorExpr; // ctor
unsigned : NumStmtBits;
unsigned ValueKind : 2;
unsigned ObjectKind : 3;
unsigned TypeDependent : 1;
unsigned ValueDependent : 1;
unsigned InstantiationDependent : 1;
unsigned ContainsUnexpandedParameterPack : 1;
};
enum { NumExprBits = NumStmtBits + 9 };
class PredefinedExprBitfields {
friend class ASTStmtReader;
friend class PredefinedExpr;
unsigned : NumExprBits;
/// The kind of this PredefinedExpr. One of the enumeration values
/// in PredefinedExpr::IdentKind.
unsigned Kind : 4;
/// True if this PredefinedExpr has a trailing "StringLiteral *"
/// for the predefined identifier.
unsigned HasFunctionName : 1;
/// The location of this PredefinedExpr.
SourceLocation Loc;
};
class DeclRefExprBitfields {
friend class ASTStmtReader; // deserialization
friend class DeclRefExpr;
unsigned : NumExprBits;
unsigned HasQualifier : 1;
unsigned HasTemplateKWAndArgsInfo : 1;
unsigned HasFoundDecl : 1;
unsigned HadMultipleCandidates : 1;
unsigned RefersToEnclosingVariableOrCapture : 1;
/// The location of the declaration name itself.
SourceLocation Loc;
};
enum APFloatSemantics {
IEEEhalf,
IEEEsingle,
IEEEdouble,
x87DoubleExtended,
IEEEquad,
PPCDoubleDouble
};
class FloatingLiteralBitfields {
friend class FloatingLiteral;
unsigned : NumExprBits;
unsigned Semantics : 3; // Provides semantics for APFloat construction
unsigned IsExact : 1;
};
class StringLiteralBitfields {
friend class ASTStmtReader;
friend class StringLiteral;
unsigned : NumExprBits;
/// The kind of this string literal.
/// One of the enumeration values of StringLiteral::StringKind.
unsigned Kind : 3;
/// The width of a single character in bytes. Only values of 1, 2,
/// and 4 bytes are supported. StringLiteral::mapCharByteWidth maps
/// the target + string kind to the appropriate CharByteWidth.
unsigned CharByteWidth : 3;
unsigned IsPascal : 1;
/// The number of concatenated token this string is made of.
/// This is the number of trailing SourceLocation.
unsigned NumConcatenated;
};
class CharacterLiteralBitfields {
friend class CharacterLiteral;
unsigned : NumExprBits;
unsigned Kind : 3;
};
class UnaryOperatorBitfields {
friend class UnaryOperator;
unsigned : NumExprBits;
unsigned Opc : 5;
unsigned CanOverflow : 1;
SourceLocation Loc;
};
class UnaryExprOrTypeTraitExprBitfields {
friend class UnaryExprOrTypeTraitExpr;
unsigned : NumExprBits;
unsigned Kind : 3;
unsigned IsType : 1; // true if operand is a type, false if an expression.
};
class ArraySubscriptExprBitfields {
friend class ArraySubscriptExpr;
unsigned : NumExprBits;
SourceLocation RBracketLoc;
};
class CallExprBitfields {
friend class CallExpr;
unsigned : NumExprBits;
unsigned NumPreArgs : 1;
/// True if the callee of the call expression was found using ADL.
unsigned UsesADL : 1;
/// Padding used to align OffsetToTrailingObjects to a byte multiple.
unsigned : 24 - 2 - NumExprBits;
/// The offset in bytes from the this pointer to the start of the
/// trailing objects belonging to CallExpr. Intentionally byte sized
/// for faster access.
unsigned OffsetToTrailingObjects : 8;
};
enum { NumCallExprBits = 32 };
class MemberExprBitfields {
friend class MemberExpr;
unsigned : NumExprBits;
/// IsArrow - True if this is "X->F", false if this is "X.F".
unsigned IsArrow : 1;
/// True if this member expression used a nested-name-specifier to
/// refer to the member, e.g., "x->Base::f", or found its member via
/// a using declaration. When true, a MemberExprNameQualifier
/// structure is allocated immediately after the MemberExpr.
unsigned HasQualifierOrFoundDecl : 1;
/// True if this member expression specified a template keyword
/// and/or a template argument list explicitly, e.g., x->f<int>,
/// x->template f, x->template f<int>.
/// When true, an ASTTemplateKWAndArgsInfo structure and its
/// TemplateArguments (if any) are present.
unsigned HasTemplateKWAndArgsInfo : 1;
/// True if this member expression refers to a method that
/// was resolved from an overloaded set having size greater than 1.
unsigned HadMultipleCandidates : 1;
/// This is the location of the -> or . in the expression.
SourceLocation OperatorLoc;
};
class CastExprBitfields {
friend class CastExpr;
friend class ImplicitCastExpr;
unsigned : NumExprBits;
unsigned Kind : 6;
unsigned PartOfExplicitCast : 1; // Only set for ImplicitCastExpr.
/// The number of CXXBaseSpecifiers in the cast. 14 bits would be enough
/// here. ([implimits] Direct and indirect base classes [16384]).
unsigned BasePathSize;
};
class BinaryOperatorBitfields {
friend class BinaryOperator;
unsigned : NumExprBits;
unsigned Opc : 6;
/// This is only meaningful for operations on floating point
/// types and 0 otherwise.
unsigned FPFeatures : 3;
SourceLocation OpLoc;
};
class InitListExprBitfields {
friend class InitListExpr;
unsigned : NumExprBits;
/// Whether this initializer list originally had a GNU array-range
/// designator in it. This is a temporary marker used by CodeGen.
unsigned HadArrayRangeDesignator : 1;
};
class ParenListExprBitfields {
friend class ASTStmtReader;
friend class ParenListExpr;
unsigned : NumExprBits;
/// The number of expressions in the paren list.
unsigned NumExprs;
};
class GenericSelectionExprBitfields {
friend class ASTStmtReader;
friend class GenericSelectionExpr;
unsigned : NumExprBits;
/// The location of the "_Generic".
SourceLocation GenericLoc;
};
class PseudoObjectExprBitfields {
friend class ASTStmtReader; // deserialization
friend class PseudoObjectExpr;
unsigned : NumExprBits;
// These don't need to be particularly wide, because they're
// strictly limited by the forms of expressions we permit.
unsigned NumSubExprs : 8;
unsigned ResultIndex : 32 - 8 - NumExprBits;
};
//===--- C++ Expression bitfields classes ---===//
class CXXOperatorCallExprBitfields {
friend class ASTStmtReader;
friend class CXXOperatorCallExpr;
unsigned : NumCallExprBits;
/// The kind of this overloaded operator. One of the enumerator
/// value of OverloadedOperatorKind.
unsigned OperatorKind : 6;
// Only meaningful for floating point types.
unsigned FPFeatures : 3;
};
class CXXBoolLiteralExprBitfields {
friend class CXXBoolLiteralExpr;
unsigned : NumExprBits;
/// The value of the boolean literal.
unsigned Value : 1;
/// The location of the boolean literal.
SourceLocation Loc;
};
class CXXNullPtrLiteralExprBitfields {
friend class CXXNullPtrLiteralExpr;
unsigned : NumExprBits;
/// The location of the null pointer literal.
SourceLocation Loc;
};
class CXXThisExprBitfields {
friend class CXXThisExpr;
unsigned : NumExprBits;
/// Whether this is an implicit "this".
unsigned IsImplicit : 1;
/// The location of the "this".
SourceLocation Loc;
};
class CXXThrowExprBitfields {
friend class ASTStmtReader;
friend class CXXThrowExpr;
unsigned : NumExprBits;
/// Whether the thrown variable (if any) is in scope.
unsigned IsThrownVariableInScope : 1;
/// The location of the "throw".
SourceLocation ThrowLoc;
};
class CXXDefaultArgExprBitfields {
friend class ASTStmtReader;
friend class CXXDefaultArgExpr;
unsigned : NumExprBits;
/// The location where the default argument expression was used.
SourceLocation Loc;
};
class CXXDefaultInitExprBitfields {
friend class ASTStmtReader;
friend class CXXDefaultInitExpr;
unsigned : NumExprBits;
/// The location where the default initializer expression was used.
SourceLocation Loc;
};
class CXXScalarValueInitExprBitfields {
friend class ASTStmtReader;
friend class CXXScalarValueInitExpr;
unsigned : NumExprBits;
SourceLocation RParenLoc;
};
class CXXNewExprBitfields {
friend class ASTStmtReader;
friend class ASTStmtWriter;
friend class CXXNewExpr;
unsigned : NumExprBits;
/// Was the usage ::new, i.e. is the global new to be used?
unsigned IsGlobalNew : 1;
/// Do we allocate an array? If so, the first trailing "Stmt *" is the
/// size expression.
unsigned IsArray : 1;
/// Should the alignment be passed to the allocation function?
unsigned ShouldPassAlignment : 1;
/// If this is an array allocation, does the usual deallocation
/// function for the allocated type want to know the allocated size?
unsigned UsualArrayDeleteWantsSize : 1;
/// What kind of initializer do we have? Could be none, parens, or braces.
/// In storage, we distinguish between "none, and no initializer expr", and
/// "none, but an implicit initializer expr".
unsigned StoredInitializationStyle : 2;
/// True if the allocated type was expressed as a parenthesized type-id.
unsigned IsParenTypeId : 1;
/// The number of placement new arguments.
unsigned NumPlacementArgs;
};
class CXXDeleteExprBitfields {
friend class ASTStmtReader;
friend class CXXDeleteExpr;
unsigned : NumExprBits;
/// Is this a forced global delete, i.e. "::delete"?
unsigned GlobalDelete : 1;
/// Is this the array form of delete, i.e. "delete[]"?
unsigned ArrayForm : 1;
/// ArrayFormAsWritten can be different from ArrayForm if 'delete' is
/// applied to pointer-to-array type (ArrayFormAsWritten will be false
/// while ArrayForm will be true).
unsigned ArrayFormAsWritten : 1;
/// Does the usual deallocation function for the element type require
/// a size_t argument?
unsigned UsualArrayDeleteWantsSize : 1;
/// Location of the expression.
SourceLocation Loc;
};
class TypeTraitExprBitfields {
friend class ASTStmtReader;
friend class ASTStmtWriter;
friend class TypeTraitExpr;
unsigned : NumExprBits;
/// The kind of type trait, which is a value of a TypeTrait enumerator.
unsigned Kind : 8;
/// If this expression is not value-dependent, this indicates whether
/// the trait evaluated true or false.
unsigned Value : 1;
/// The number of arguments to this type trait.
unsigned NumArgs : 32 - 8 - 1 - NumExprBits;
};
class DependentScopeDeclRefExprBitfields {
friend class ASTStmtReader;
friend class ASTStmtWriter;
friend class DependentScopeDeclRefExpr;
unsigned : NumExprBits;
/// Whether the name includes info for explicit template
/// keyword and arguments.
unsigned HasTemplateKWAndArgsInfo : 1;
};
class CXXConstructExprBitfields {
friend class ASTStmtReader;
friend class CXXConstructExpr;
unsigned : NumExprBits;
unsigned Elidable : 1;
unsigned HadMultipleCandidates : 1;
unsigned ListInitialization : 1;
unsigned StdInitListInitialization : 1;
unsigned ZeroInitialization : 1;
unsigned ConstructionKind : 3;
SourceLocation Loc;
};
class ExprWithCleanupsBitfields {
friend class ASTStmtReader; // deserialization
friend class ExprWithCleanups;
unsigned : NumExprBits;
// When false, it must not have side effects.
unsigned CleanupsHaveSideEffects : 1;
unsigned NumObjects : 32 - 1 - NumExprBits;
};
class CXXUnresolvedConstructExprBitfields {
friend class ASTStmtReader;
friend class CXXUnresolvedConstructExpr;
unsigned : NumExprBits;
/// The number of arguments used to construct the type.
unsigned NumArgs;
};
class CXXDependentScopeMemberExprBitfields {
friend class ASTStmtReader;
friend class CXXDependentScopeMemberExpr;
unsigned : NumExprBits;
/// Whether this member expression used the '->' operator or
/// the '.' operator.
unsigned IsArrow : 1;
/// Whether this member expression has info for explicit template
/// keyword and arguments.
unsigned HasTemplateKWAndArgsInfo : 1;
/// See getFirstQualifierFoundInScope() and the comment listing
/// the trailing objects.
unsigned HasFirstQualifierFoundInScope : 1;
/// The location of the '->' or '.' operator.
SourceLocation OperatorLoc;
};
class OverloadExprBitfields {
friend class ASTStmtReader;
friend class OverloadExpr;
unsigned : NumExprBits;
/// Whether the name includes info for explicit template
/// keyword and arguments.
unsigned HasTemplateKWAndArgsInfo : 1;
/// Padding used by the derived classes to store various bits. If you
/// need to add some data here, shrink this padding and add your data
/// above. NumOverloadExprBits also needs to be updated.
unsigned : 32 - NumExprBits - 1;
/// The number of results.
unsigned NumResults;
};
enum { NumOverloadExprBits = NumExprBits + 1 };
class UnresolvedLookupExprBitfields {
friend class ASTStmtReader;
friend class UnresolvedLookupExpr;
unsigned : NumOverloadExprBits;
/// True if these lookup results should be extended by
/// argument-dependent lookup if this is the operand of a function call.
unsigned RequiresADL : 1;
/// True if these lookup results are overloaded. This is pretty trivially
/// rederivable if we urgently need to kill this field.
unsigned Overloaded : 1;
};
static_assert(sizeof(UnresolvedLookupExprBitfields) <= 4,
"UnresolvedLookupExprBitfields must be <= than 4 bytes to"
"avoid trashing OverloadExprBitfields::NumResults!");
class UnresolvedMemberExprBitfields {
friend class ASTStmtReader;
friend class UnresolvedMemberExpr;
unsigned : NumOverloadExprBits;
/// Whether this member expression used the '->' operator or
/// the '.' operator.
unsigned IsArrow : 1;
/// Whether the lookup results contain an unresolved using declaration.
unsigned HasUnresolvedUsing : 1;
};
static_assert(sizeof(UnresolvedMemberExprBitfields) <= 4,
"UnresolvedMemberExprBitfields must be <= than 4 bytes to"
"avoid trashing OverloadExprBitfields::NumResults!");
class CXXNoexceptExprBitfields {
friend class ASTStmtReader;
friend class CXXNoexceptExpr;
unsigned : NumExprBits;
unsigned Value : 1;
};
class SubstNonTypeTemplateParmExprBitfields {
friend class ASTStmtReader;
friend class SubstNonTypeTemplateParmExpr;
unsigned : NumExprBits;
/// The location of the non-type template parameter reference.
SourceLocation NameLoc;
};
//===--- C++ Coroutines TS bitfields classes ---===//
class CoawaitExprBitfields {
friend class CoawaitExpr;
unsigned : NumExprBits;
unsigned IsImplicit : 1;
};
//===--- Obj-C Expression bitfields classes ---===//
class ObjCIndirectCopyRestoreExprBitfields {
friend class ObjCIndirectCopyRestoreExpr;
unsigned : NumExprBits;
unsigned ShouldCopy : 1;
};
//===--- Clang Extensions bitfields classes ---===//
class OpaqueValueExprBitfields {
friend class ASTStmtReader;
friend class OpaqueValueExpr;
unsigned : NumExprBits;
/// The OVE is a unique semantic reference to its source expression if this
/// bit is set to true.
unsigned IsUnique : 1;
SourceLocation Loc;
};
union {
// Same order as in StmtNodes.td.
// Statements
StmtBitfields StmtBits;
NullStmtBitfields NullStmtBits;
CompoundStmtBitfields CompoundStmtBits;
LabelStmtBitfields LabelStmtBits;
AttributedStmtBitfields AttributedStmtBits;
IfStmtBitfields IfStmtBits;
SwitchStmtBitfields SwitchStmtBits;
WhileStmtBitfields WhileStmtBits;
DoStmtBitfields DoStmtBits;
ForStmtBitfields ForStmtBits;
GotoStmtBitfields GotoStmtBits;
ContinueStmtBitfields ContinueStmtBits;
BreakStmtBitfields BreakStmtBits;
ReturnStmtBitfields ReturnStmtBits;
SwitchCaseBitfields SwitchCaseBits;
// Expressions
ExprBitfields ExprBits;
PredefinedExprBitfields PredefinedExprBits;
DeclRefExprBitfields DeclRefExprBits;
FloatingLiteralBitfields FloatingLiteralBits;
StringLiteralBitfields StringLiteralBits;
CharacterLiteralBitfields CharacterLiteralBits;
UnaryOperatorBitfields UnaryOperatorBits;
UnaryExprOrTypeTraitExprBitfields UnaryExprOrTypeTraitExprBits;
ArraySubscriptExprBitfields ArraySubscriptExprBits;
CallExprBitfields CallExprBits;
MemberExprBitfields MemberExprBits;
CastExprBitfields CastExprBits;
BinaryOperatorBitfields BinaryOperatorBits;
InitListExprBitfields InitListExprBits;
ParenListExprBitfields ParenListExprBits;
GenericSelectionExprBitfields GenericSelectionExprBits;
PseudoObjectExprBitfields PseudoObjectExprBits;
// C++ Expressions
CXXOperatorCallExprBitfields CXXOperatorCallExprBits;
CXXBoolLiteralExprBitfields CXXBoolLiteralExprBits;
CXXNullPtrLiteralExprBitfields CXXNullPtrLiteralExprBits;
CXXThisExprBitfields CXXThisExprBits;
CXXThrowExprBitfields CXXThrowExprBits;
CXXDefaultArgExprBitfields CXXDefaultArgExprBits;
CXXDefaultInitExprBitfields CXXDefaultInitExprBits;
CXXScalarValueInitExprBitfields CXXScalarValueInitExprBits;
CXXNewExprBitfields CXXNewExprBits;
CXXDeleteExprBitfields CXXDeleteExprBits;
TypeTraitExprBitfields TypeTraitExprBits;
DependentScopeDeclRefExprBitfields DependentScopeDeclRefExprBits;
CXXConstructExprBitfields CXXConstructExprBits;
ExprWithCleanupsBitfields ExprWithCleanupsBits;
CXXUnresolvedConstructExprBitfields CXXUnresolvedConstructExprBits;
CXXDependentScopeMemberExprBitfields CXXDependentScopeMemberExprBits;
OverloadExprBitfields OverloadExprBits;
UnresolvedLookupExprBitfields UnresolvedLookupExprBits;
UnresolvedMemberExprBitfields UnresolvedMemberExprBits;
CXXNoexceptExprBitfields CXXNoexceptExprBits;
SubstNonTypeTemplateParmExprBitfields SubstNonTypeTemplateParmExprBits;
// C++ Coroutines TS expressions
CoawaitExprBitfields CoawaitBits;
// Obj-C Expressions
ObjCIndirectCopyRestoreExprBitfields ObjCIndirectCopyRestoreExprBits;
// Clang Extensions
OpaqueValueExprBitfields OpaqueValueExprBits;
};
public:
// Only allow allocation of Stmts using the allocator in ASTContext
// or by doing a placement new.
void* operator new(size_t bytes, const ASTContext& C,
unsigned alignment = 8);
void* operator new(size_t bytes, const ASTContext* C,
unsigned alignment = 8) {
return operator new(bytes, *C, alignment);
}
void *operator new(size_t bytes, void *mem) noexcept { return mem; }
void operator delete(void *, const ASTContext &, unsigned) noexcept {}
void operator delete(void *, const ASTContext *, unsigned) noexcept {}
void operator delete(void *, size_t) noexcept {}
void operator delete(void *, void *) noexcept {}
public:
/// A placeholder type used to construct an empty shell of a
/// type, that will be filled in later (e.g., by some
/// de-serialization).
struct EmptyShell {};
protected:
/// Iterator for iterating over Stmt * arrays that contain only T *.
///
/// This is needed because AST nodes use Stmt* arrays to store
/// references to children (to be compatible with StmtIterator).
template<typename T, typename TPtr = T *, typename StmtPtr = Stmt *>
struct CastIterator
: llvm::iterator_adaptor_base<CastIterator<T, TPtr, StmtPtr>, StmtPtr *,
std::random_access_iterator_tag, TPtr> {
using Base = typename CastIterator::iterator_adaptor_base;
CastIterator() : Base(nullptr) {}
CastIterator(StmtPtr *I) : Base(I) {}
typename Base::value_type operator*() const {
return cast_or_null<T>(*this->I);
}
};
/// Const iterator for iterating over Stmt * arrays that contain only T *.
template <typename T>
using ConstCastIterator = CastIterator<T, const T *const, const Stmt *const>;
using ExprIterator = CastIterator<Expr>;
using ConstExprIterator = ConstCastIterator<Expr>;
private:
/// Whether statistic collection is enabled.
static bool StatisticsEnabled;
protected:
/// Construct an empty statement.
explicit Stmt(StmtClass SC, EmptyShell) : Stmt(SC) {}
public:
Stmt(StmtClass SC) {
static_assert(sizeof(*this) <= 8,
"changing bitfields changed sizeof(Stmt)");
static_assert(sizeof(*this) % alignof(void *) == 0,
"Insufficient alignment!");
StmtBits.sClass = SC;
StmtBits.IsOMPStructuredBlock = false;
if (StatisticsEnabled) Stmt::addStmtClass(SC);
}
StmtClass getStmtClass() const {
return static_cast<StmtClass>(StmtBits.sClass);
}
Stmt(const Stmt &) = delete;
Stmt(Stmt &&) = delete;
Stmt &operator=(const Stmt &) = delete;
Stmt &operator=(Stmt &&) = delete;
const char *getStmtClassName() const;
bool isOMPStructuredBlock() const { return StmtBits.IsOMPStructuredBlock; }
void setIsOMPStructuredBlock(bool IsOMPStructuredBlock) {
StmtBits.IsOMPStructuredBlock = IsOMPStructuredBlock;
}
/// SourceLocation tokens are not useful in isolation - they are low level
/// value objects created/interpreted by SourceManager. We assume AST
/// clients will have a pointer to the respective SourceManager.
SourceRange getSourceRange() const LLVM_READONLY;
SourceLocation getBeginLoc() const LLVM_READONLY;
SourceLocation getEndLoc() const LLVM_READONLY;
// global temp stats (until we have a per-module visitor)
static void addStmtClass(const StmtClass s);
static void EnableStatistics();
static void PrintStats();
/// Dumps the specified AST fragment and all subtrees to
/// \c llvm::errs().
void dump() const;
void dump(SourceManager &SM) const;
void dump(raw_ostream &OS, SourceManager &SM) const;
void dump(raw_ostream &OS) const;
/// \return Unique reproducible object identifier
int64_t getID(const ASTContext &Context) const;
/// dumpColor - same as dump(), but forces color highlighting.
void dumpColor() const;
/// dumpPretty/printPretty - These two methods do a "pretty print" of the AST
/// back to its original source language syntax.
void dumpPretty(const ASTContext &Context) const;
void printPretty(raw_ostream &OS, PrinterHelper *Helper,
const PrintingPolicy &Policy, unsigned Indentation = 0,
StringRef NewlineSymbol = "\n",
const ASTContext *Context = nullptr) const;
/// viewAST - Visualize an AST rooted at this Stmt* using GraphViz. Only
/// works on systems with GraphViz (Mac OS X) or dot+gv installed.
void viewAST() const;
/// Skip no-op (attributed, compound) container stmts and skip captured
/// stmt at the top, if \a IgnoreCaptured is true.
Stmt *IgnoreContainers(bool IgnoreCaptured = false);
const Stmt *IgnoreContainers(bool IgnoreCaptured = false) const {
return const_cast<Stmt *>(this)->IgnoreContainers(IgnoreCaptured);
}
const Stmt *stripLabelLikeStatements() const;
Stmt *stripLabelLikeStatements() {
return const_cast<Stmt*>(
const_cast<const Stmt*>(this)->stripLabelLikeStatements());
}
/// Child Iterators: All subclasses must implement 'children'
/// to permit easy iteration over the substatements/subexpessions of an
/// AST node. This permits easy iteration over all nodes in the AST.
using child_iterator = StmtIterator;
using const_child_iterator = ConstStmtIterator;
using child_range = llvm::iterator_range<child_iterator>;
using const_child_range = llvm::iterator_range<const_child_iterator>;
child_range children();
const_child_range children() const {
auto Children = const_cast<Stmt *>(this)->children();
return const_child_range(Children.begin(), Children.end());
}
child_iterator child_begin() { return children().begin(); }
child_iterator child_end() { return children().end(); }
const_child_iterator child_begin() const { return children().begin(); }
const_child_iterator child_end() const { return children().end(); }
/// Produce a unique representation of the given statement.
///
/// \param ID once the profiling operation is complete, will contain
/// the unique representation of the given statement.
///
/// \param Context the AST context in which the statement resides
///
/// \param Canonical whether the profile should be based on the canonical
/// representation of this statement (e.g., where non-type template
/// parameters are identified by index/level rather than their
/// declaration pointers) or the exact representation of the statement as
/// written in the source.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
bool Canonical) const;
/// Calculate a unique representation for a statement that is
/// stable across compiler invocations.
///
/// \param ID profile information will be stored in ID.
///
/// \param Hash an ODRHash object which will be called where pointers would
/// have been used in the Profile function.
void ProcessODRHash(llvm::FoldingSetNodeID &ID, ODRHash& Hash) const;
};
/// DeclStmt - Adaptor class for mixing declarations with statements and
/// expressions. For example, CompoundStmt mixes statements, expressions
/// and declarations (variables, types). Another example is ForStmt, where
/// the first statement can be an expression or a declaration.
class DeclStmt : public Stmt {
DeclGroupRef DG;
SourceLocation StartLoc, EndLoc;
public:
DeclStmt(DeclGroupRef dg, SourceLocation startLoc, SourceLocation endLoc)
: Stmt(DeclStmtClass), DG(dg), StartLoc(startLoc), EndLoc(endLoc) {}
/// Build an empty declaration statement.
explicit DeclStmt(EmptyShell Empty) : Stmt(DeclStmtClass, Empty) {}
/// isSingleDecl - This method returns true if this DeclStmt refers
/// to a single Decl.
bool isSingleDecl() const { return DG.isSingleDecl(); }
const Decl *getSingleDecl() const { return DG.getSingleDecl(); }
Decl *getSingleDecl() { return DG.getSingleDecl(); }
const DeclGroupRef getDeclGroup() const { return DG; }
DeclGroupRef getDeclGroup() { return DG; }
void setDeclGroup(DeclGroupRef DGR) { DG = DGR; }
void setStartLoc(SourceLocation L) { StartLoc = L; }
SourceLocation getEndLoc() const { return EndLoc; }
void setEndLoc(SourceLocation L) { EndLoc = L; }
SourceLocation getBeginLoc() const LLVM_READONLY { return StartLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == DeclStmtClass;
}
// Iterators over subexpressions.
child_range children() {
return child_range(child_iterator(DG.begin(), DG.end()),
child_iterator(DG.end(), DG.end()));
}
const_child_range children() const {
auto Children = const_cast<DeclStmt *>(this)->children();
return const_child_range(Children);
}
using decl_iterator = DeclGroupRef::iterator;
using const_decl_iterator = DeclGroupRef::const_iterator;
using decl_range = llvm::iterator_range<decl_iterator>;
using decl_const_range = llvm::iterator_range<const_decl_iterator>;
decl_range decls() { return decl_range(decl_begin(), decl_end()); }
decl_const_range decls() const {
return decl_const_range(decl_begin(), decl_end());
}
decl_iterator decl_begin() { return DG.begin(); }
decl_iterator decl_end() { return DG.end(); }
const_decl_iterator decl_begin() const { return DG.begin(); }
const_decl_iterator decl_end() const { return DG.end(); }
using reverse_decl_iterator = std::reverse_iterator<decl_iterator>;
reverse_decl_iterator decl_rbegin() {
return reverse_decl_iterator(decl_end());
}
reverse_decl_iterator decl_rend() {
return reverse_decl_iterator(decl_begin());
}
};
/// NullStmt - This is the null statement ";": C99 6.8.3p3.
///
class NullStmt : public Stmt {
public:
NullStmt(SourceLocation L, bool hasLeadingEmptyMacro = false)
: Stmt(NullStmtClass) {
NullStmtBits.HasLeadingEmptyMacro = hasLeadingEmptyMacro;
setSemiLoc(L);
}
/// Build an empty null statement.
explicit NullStmt(EmptyShell Empty) : Stmt(NullStmtClass, Empty) {}
SourceLocation getSemiLoc() const { return NullStmtBits.SemiLoc; }
void setSemiLoc(SourceLocation L) { NullStmtBits.SemiLoc = L; }
bool hasLeadingEmptyMacro() const {
return NullStmtBits.HasLeadingEmptyMacro;
}
SourceLocation getBeginLoc() const { return getSemiLoc(); }
SourceLocation getEndLoc() const { return getSemiLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == NullStmtClass;
}
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// CompoundStmt - This represents a group of statements like { stmt stmt }.
class CompoundStmt final : public Stmt,
private llvm::TrailingObjects<CompoundStmt, Stmt *> {
friend class ASTStmtReader;
friend TrailingObjects;
/// The location of the closing "}". LBraceLoc is stored in CompoundStmtBits.
SourceLocation RBraceLoc;
CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB, SourceLocation RB);
explicit CompoundStmt(EmptyShell Empty) : Stmt(CompoundStmtClass, Empty) {}
void setStmts(ArrayRef<Stmt *> Stmts);
public:
static CompoundStmt *Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
SourceLocation LB, SourceLocation RB);
// Build an empty compound statement with a location.
explicit CompoundStmt(SourceLocation Loc)
: Stmt(CompoundStmtClass), RBraceLoc(Loc) {
CompoundStmtBits.NumStmts = 0;
CompoundStmtBits.LBraceLoc = Loc;
}
// Build an empty compound statement.
static CompoundStmt *CreateEmpty(const ASTContext &C, unsigned NumStmts);
bool body_empty() const { return CompoundStmtBits.NumStmts == 0; }
unsigned size() const { return CompoundStmtBits.NumStmts; }
using body_iterator = Stmt **;
using body_range = llvm::iterator_range<body_iterator>;
body_range body() { return body_range(body_begin(), body_end()); }
body_iterator body_begin() { return getTrailingObjects<Stmt *>(); }
body_iterator body_end() { return body_begin() + size(); }
Stmt *body_front() { return !body_empty() ? body_begin()[0] : nullptr; }
Stmt *body_back() {
return !body_empty() ? body_begin()[size() - 1] : nullptr;
}
void setLastStmt(Stmt *S) {
assert(!body_empty() && "setLastStmt");
body_begin()[size() - 1] = S;
}
using const_body_iterator = Stmt *const *;
using body_const_range = llvm::iterator_range<const_body_iterator>;
body_const_range body() const {
return body_const_range(body_begin(), body_end());
}
const_body_iterator body_begin() const {
return getTrailingObjects<Stmt *>();
}
const_body_iterator body_end() const { return body_begin() + size(); }
const Stmt *body_front() const {
return !body_empty() ? body_begin()[0] : nullptr;
}
const Stmt *body_back() const {
return !body_empty() ? body_begin()[size() - 1] : nullptr;
}
using reverse_body_iterator = std::reverse_iterator<body_iterator>;
reverse_body_iterator body_rbegin() {
return reverse_body_iterator(body_end());
}
reverse_body_iterator body_rend() {
return reverse_body_iterator(body_begin());
}
using const_reverse_body_iterator =
std::reverse_iterator<const_body_iterator>;
const_reverse_body_iterator body_rbegin() const {
return const_reverse_body_iterator(body_end());
}
const_reverse_body_iterator body_rend() const {
return const_reverse_body_iterator(body_begin());
}
SourceLocation getBeginLoc() const { return CompoundStmtBits.LBraceLoc; }
SourceLocation getEndLoc() const { return RBraceLoc; }
SourceLocation getLBracLoc() const { return CompoundStmtBits.LBraceLoc; }
SourceLocation getRBracLoc() const { return RBraceLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CompoundStmtClass;
}
// Iterators
child_range children() { return child_range(body_begin(), body_end()); }
const_child_range children() const {
return const_child_range(body_begin(), body_end());
}
};
// SwitchCase is the base class for CaseStmt and DefaultStmt,
class SwitchCase : public Stmt {
protected:
/// The location of the ":".
SourceLocation ColonLoc;
// The location of the "case" or "default" keyword. Stored in SwitchCaseBits.
// SourceLocation KeywordLoc;
/// A pointer to the following CaseStmt or DefaultStmt class,
/// used by SwitchStmt.
SwitchCase *NextSwitchCase = nullptr;
SwitchCase(StmtClass SC, SourceLocation KWLoc, SourceLocation ColonLoc)
: Stmt(SC), ColonLoc(ColonLoc) {
setKeywordLoc(KWLoc);
}
SwitchCase(StmtClass SC, EmptyShell) : Stmt(SC) {}
public:
const SwitchCase *getNextSwitchCase() const { return NextSwitchCase; }
SwitchCase *getNextSwitchCase() { return NextSwitchCase; }
void setNextSwitchCase(SwitchCase *SC) { NextSwitchCase = SC; }
SourceLocation getKeywordLoc() const { return SwitchCaseBits.KeywordLoc; }
void setKeywordLoc(SourceLocation L) { SwitchCaseBits.KeywordLoc = L; }
SourceLocation getColonLoc() const { return ColonLoc; }
void setColonLoc(SourceLocation L) { ColonLoc = L; }
inline Stmt *getSubStmt();
const Stmt *getSubStmt() const {
return const_cast<SwitchCase *>(this)->getSubStmt();
}
SourceLocation getBeginLoc() const { return getKeywordLoc(); }
inline SourceLocation getEndLoc() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CaseStmtClass ||
T->getStmtClass() == DefaultStmtClass;
}
};
/// CaseStmt - Represent a case statement. It can optionally be a GNU case
/// statement of the form LHS ... RHS representing a range of cases.
class CaseStmt final
: public SwitchCase,
private llvm::TrailingObjects<CaseStmt, Stmt *, SourceLocation> {
friend TrailingObjects;
// CaseStmt is followed by several trailing objects, some of which optional.
// Note that it would be more convenient to put the optional trailing objects
// at the end but this would impact children().
// The trailing objects are in order:
//
// * A "Stmt *" for the LHS of the case statement. Always present.
//
// * A "Stmt *" for the RHS of the case statement. This is a GNU extension
// which allow ranges in cases statement of the form LHS ... RHS.
// Present if and only if caseStmtIsGNURange() is true.
//
// * A "Stmt *" for the substatement of the case statement. Always present.
//
// * A SourceLocation for the location of the ... if this is a case statement
// with a range. Present if and only if caseStmtIsGNURange() is true.
enum { LhsOffset = 0, SubStmtOffsetFromRhs = 1 };
enum { NumMandatoryStmtPtr = 2 };
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + caseStmtIsGNURange();
}
unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
return caseStmtIsGNURange();
}
unsigned lhsOffset() const { return LhsOffset; }
unsigned rhsOffset() const { return LhsOffset + caseStmtIsGNURange(); }
unsigned subStmtOffset() const { return rhsOffset() + SubStmtOffsetFromRhs; }
/// Build a case statement assuming that the storage for the
/// trailing objects has been properly allocated.
CaseStmt(Expr *lhs, Expr *rhs, SourceLocation caseLoc,
SourceLocation ellipsisLoc, SourceLocation colonLoc)
: SwitchCase(CaseStmtClass, caseLoc, colonLoc) {
// Handle GNU case statements of the form LHS ... RHS.
bool IsGNURange = rhs != nullptr;
SwitchCaseBits.CaseStmtIsGNURange = IsGNURange;
setLHS(lhs);
setSubStmt(nullptr);
if (IsGNURange) {
setRHS(rhs);
setEllipsisLoc(ellipsisLoc);
}
}
/// Build an empty switch case statement.
explicit CaseStmt(EmptyShell Empty, bool CaseStmtIsGNURange)
: SwitchCase(CaseStmtClass, Empty) {
SwitchCaseBits.CaseStmtIsGNURange = CaseStmtIsGNURange;
}
public:
/// Build a case statement.
static CaseStmt *Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
SourceLocation caseLoc, SourceLocation ellipsisLoc,
SourceLocation colonLoc);
/// Build an empty case statement.
static CaseStmt *CreateEmpty(const ASTContext &Ctx, bool CaseStmtIsGNURange);
/// True if this case statement is of the form case LHS ... RHS, which
/// is a GNU extension. In this case the RHS can be obtained with getRHS()
/// and the location of the ellipsis can be obtained with getEllipsisLoc().
bool caseStmtIsGNURange() const { return SwitchCaseBits.CaseStmtIsGNURange; }
SourceLocation getCaseLoc() const { return getKeywordLoc(); }
void setCaseLoc(SourceLocation L) { setKeywordLoc(L); }
/// Get the location of the ... in a case statement of the form LHS ... RHS.
SourceLocation getEllipsisLoc() const {
return caseStmtIsGNURange() ? *getTrailingObjects<SourceLocation>()
: SourceLocation();
}
/// Set the location of the ... in a case statement of the form LHS ... RHS.
/// Assert that this case statement is of this form.
void setEllipsisLoc(SourceLocation L) {
assert(
caseStmtIsGNURange() &&
"setEllipsisLoc but this is not a case stmt of the form LHS ... RHS!");
*getTrailingObjects<SourceLocation>() = L;
}
Expr *getLHS() {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
}
const Expr *getLHS() const {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[lhsOffset()]);
}
void setLHS(Expr *Val) {
getTrailingObjects<Stmt *>()[lhsOffset()] = reinterpret_cast<Stmt *>(Val);
}
Expr *getRHS() {
return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
getTrailingObjects<Stmt *>()[rhsOffset()])
: nullptr;
}
const Expr *getRHS() const {
return caseStmtIsGNURange() ? reinterpret_cast<Expr *>(
getTrailingObjects<Stmt *>()[rhsOffset()])
: nullptr;
}
void setRHS(Expr *Val) {
assert(caseStmtIsGNURange() &&
"setRHS but this is not a case stmt of the form LHS ... RHS!");
getTrailingObjects<Stmt *>()[rhsOffset()] = reinterpret_cast<Stmt *>(Val);
}
Stmt *getSubStmt() { return getTrailingObjects<Stmt *>()[subStmtOffset()]; }
const Stmt *getSubStmt() const {
return getTrailingObjects<Stmt *>()[subStmtOffset()];
}
void setSubStmt(Stmt *S) {
getTrailingObjects<Stmt *>()[subStmtOffset()] = S;
}
SourceLocation getBeginLoc() const { return getKeywordLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
// Handle deeply nested case statements with iteration instead of recursion.
const CaseStmt *CS = this;
while (const auto *CS2 = dyn_cast<CaseStmt>(CS->getSubStmt()))
CS = CS2;
return CS->getSubStmt()->getEndLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CaseStmtClass;
}
// Iterators
child_range children() {
return child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
const_child_range children() const {
return const_child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
};
class DefaultStmt : public SwitchCase {
Stmt *SubStmt;
public:
DefaultStmt(SourceLocation DL, SourceLocation CL, Stmt *substmt)
: SwitchCase(DefaultStmtClass, DL, CL), SubStmt(substmt) {}
/// Build an empty default statement.
explicit DefaultStmt(EmptyShell Empty)
: SwitchCase(DefaultStmtClass, Empty) {}
Stmt *getSubStmt() { return SubStmt; }
const Stmt *getSubStmt() const { return SubStmt; }
void setSubStmt(Stmt *S) { SubStmt = S; }
SourceLocation getDefaultLoc() const { return getKeywordLoc(); }
void setDefaultLoc(SourceLocation L) { setKeywordLoc(L); }
SourceLocation getBeginLoc() const { return getKeywordLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
return SubStmt->getEndLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == DefaultStmtClass;
}
// Iterators
child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
const_child_range children() const {
return const_child_range(&SubStmt, &SubStmt + 1);
}
};
SourceLocation SwitchCase::getEndLoc() const {
if (const auto *CS = dyn_cast<CaseStmt>(this))
return CS->getEndLoc();
else if (const auto *DS = dyn_cast<DefaultStmt>(this))
return DS->getEndLoc();
llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
}
Stmt *SwitchCase::getSubStmt() {
if (auto *CS = dyn_cast<CaseStmt>(this))
return CS->getSubStmt();
else if (auto *DS = dyn_cast<DefaultStmt>(this))
return DS->getSubStmt();
llvm_unreachable("SwitchCase is neither a CaseStmt nor a DefaultStmt!");
}
/// Represents a statement that could possibly have a value and type. This
/// covers expression-statements, as well as labels and attributed statements.
///
/// Value statements have a special meaning when they are the last non-null
/// statement in a GNU statement expression, where they determine the value
/// of the statement expression.
class ValueStmt : public Stmt {
protected:
using Stmt::Stmt;
public:
const Expr *getExprStmt() const;
Expr *getExprStmt() {
const ValueStmt *ConstThis = this;
return const_cast<Expr*>(ConstThis->getExprStmt());
}
static bool classof(const Stmt *T) {
return T->getStmtClass() >= firstValueStmtConstant &&
T->getStmtClass() <= lastValueStmtConstant;
}
};
/// LabelStmt - Represents a label, which has a substatement. For example:
/// foo: return;
class LabelStmt : public ValueStmt {
LabelDecl *TheDecl;
Stmt *SubStmt;
public:
/// Build a label statement.
LabelStmt(SourceLocation IL, LabelDecl *D, Stmt *substmt)
: ValueStmt(LabelStmtClass), TheDecl(D), SubStmt(substmt) {
setIdentLoc(IL);
}
/// Build an empty label statement.
explicit LabelStmt(EmptyShell Empty) : ValueStmt(LabelStmtClass, Empty) {}
SourceLocation getIdentLoc() const { return LabelStmtBits.IdentLoc; }
void setIdentLoc(SourceLocation L) { LabelStmtBits.IdentLoc = L; }
LabelDecl *getDecl() const { return TheDecl; }
void setDecl(LabelDecl *D) { TheDecl = D; }
const char *getName() const;
Stmt *getSubStmt() { return SubStmt; }
const Stmt *getSubStmt() const { return SubStmt; }
void setSubStmt(Stmt *SS) { SubStmt = SS; }
SourceLocation getBeginLoc() const { return getIdentLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
const_child_range children() const {
return const_child_range(&SubStmt, &SubStmt + 1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == LabelStmtClass;
}
};
/// Represents an attribute applied to a statement.
///
/// Represents an attribute applied to a statement. For example:
/// [[omp::for(...)]] for (...) { ... }
class AttributedStmt final
: public ValueStmt,
private llvm::TrailingObjects<AttributedStmt, const Attr *> {
friend class ASTStmtReader;
friend TrailingObjects;
Stmt *SubStmt;
AttributedStmt(SourceLocation Loc, ArrayRef<const Attr *> Attrs,
Stmt *SubStmt)
: ValueStmt(AttributedStmtClass), SubStmt(SubStmt) {
AttributedStmtBits.NumAttrs = Attrs.size();
AttributedStmtBits.AttrLoc = Loc;
std::copy(Attrs.begin(), Attrs.end(), getAttrArrayPtr());
}
explicit AttributedStmt(EmptyShell Empty, unsigned NumAttrs)
: ValueStmt(AttributedStmtClass, Empty) {
AttributedStmtBits.NumAttrs = NumAttrs;
AttributedStmtBits.AttrLoc = SourceLocation{};
std::fill_n(getAttrArrayPtr(), NumAttrs, nullptr);
}
const Attr *const *getAttrArrayPtr() const {
return getTrailingObjects<const Attr *>();
}
const Attr **getAttrArrayPtr() { return getTrailingObjects<const Attr *>(); }
public:
static AttributedStmt *Create(const ASTContext &C, SourceLocation Loc,
ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
// Build an empty attributed statement.
static AttributedStmt *CreateEmpty(const ASTContext &C, unsigned NumAttrs);
SourceLocation getAttrLoc() const { return AttributedStmtBits.AttrLoc; }
ArrayRef<const Attr *> getAttrs() const {
return llvm::makeArrayRef(getAttrArrayPtr(), AttributedStmtBits.NumAttrs);
}
Stmt *getSubStmt() { return SubStmt; }
const Stmt *getSubStmt() const { return SubStmt; }
SourceLocation getBeginLoc() const { return getAttrLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY { return SubStmt->getEndLoc();}
child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
const_child_range children() const {
return const_child_range(&SubStmt, &SubStmt + 1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == AttributedStmtClass;
}
};
/// IfStmt - This represents an if/then/else.
class IfStmt final
: public Stmt,
private llvm::TrailingObjects<IfStmt, Stmt *, SourceLocation> {
friend TrailingObjects;
// IfStmt is followed by several trailing objects, some of which optional.
// Note that it would be more convenient to put the optional trailing
// objects at then end but this would change the order of the children.
// The trailing objects are in order:
//
// * A "Stmt *" for the init statement.
// Present if and only if hasInitStorage().
//
// * A "Stmt *" for the condition variable.
// Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
//
// * A "Stmt *" for the condition.
// Always present. This is in fact a "Expr *".
//
// * A "Stmt *" for the then statement.
// Always present.
//
// * A "Stmt *" for the else statement.
// Present if and only if hasElseStorage().
//
// * A "SourceLocation" for the location of the "else".
// Present if and only if hasElseStorage().
enum { InitOffset = 0, ThenOffsetFromCond = 1, ElseOffsetFromCond = 2 };
enum { NumMandatoryStmtPtr = 2 };
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + hasElseStorage() + hasVarStorage() +
hasInitStorage();
}
unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
return hasElseStorage();
}
unsigned initOffset() const { return InitOffset; }
unsigned varOffset() const { return InitOffset + hasInitStorage(); }
unsigned condOffset() const {
return InitOffset + hasInitStorage() + hasVarStorage();
}
unsigned thenOffset() const { return condOffset() + ThenOffsetFromCond; }
unsigned elseOffset() const { return condOffset() + ElseOffsetFromCond; }
/// Build an if/then/else statement.
IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr, Stmt *Init,
VarDecl *Var, Expr *Cond, Stmt *Then, SourceLocation EL, Stmt *Else);
/// Build an empty if/then/else statement.
explicit IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit);
public:
/// Create an IfStmt.
static IfStmt *Create(const ASTContext &Ctx, SourceLocation IL,
bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
Stmt *Then, SourceLocation EL = SourceLocation(),
Stmt *Else = nullptr);
/// Create an empty IfStmt optionally with storage for an else statement,
/// condition variable and init expression.
static IfStmt *CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
bool HasInit);
/// True if this IfStmt has the storage for an init statement.
bool hasInitStorage() const { return IfStmtBits.HasInit; }
/// True if this IfStmt has storage for a variable declaration.
bool hasVarStorage() const { return IfStmtBits.HasVar; }
/// True if this IfStmt has storage for an else statement.
bool hasElseStorage() const { return IfStmtBits.HasElse; }
Expr *getCond() {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
const Expr *getCond() const {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
void setCond(Expr *Cond) {
getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
}
Stmt *getThen() { return getTrailingObjects<Stmt *>()[thenOffset()]; }
const Stmt *getThen() const {
return getTrailingObjects<Stmt *>()[thenOffset()];
}
void setThen(Stmt *Then) {
getTrailingObjects<Stmt *>()[thenOffset()] = Then;
}
Stmt *getElse() {
return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
: nullptr;
}
const Stmt *getElse() const {
return hasElseStorage() ? getTrailingObjects<Stmt *>()[elseOffset()]
: nullptr;
}
void setElse(Stmt *Else) {
assert(hasElseStorage() &&
"This if statement has no storage for an else statement!");
getTrailingObjects<Stmt *>()[elseOffset()] = Else;
}
/// Retrieve the variable declared in this "if" statement, if any.
///
/// In the following example, "x" is the condition variable.
/// \code
/// if (int x = foo()) {
/// printf("x is %d", x);
/// }
/// \endcode
VarDecl *getConditionVariable();
const VarDecl *getConditionVariable() const {
return const_cast<IfStmt *>(this)->getConditionVariable();
}
/// Set the condition variable for this if statement.
/// The if statement must have storage for the condition variable.
void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
/// If this IfStmt has a condition variable, return the faux DeclStmt
/// associated with the creation of that condition variable.
DeclStmt *getConditionVariableDeclStmt() {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
const DeclStmt *getConditionVariableDeclStmt() const {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
Stmt *getInit() {
return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
: nullptr;
}
const Stmt *getInit() const {
return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
: nullptr;
}
void setInit(Stmt *Init) {
assert(hasInitStorage() &&
"This if statement has no storage for an init statement!");
getTrailingObjects<Stmt *>()[initOffset()] = Init;
}
SourceLocation getIfLoc() const { return IfStmtBits.IfLoc; }
void setIfLoc(SourceLocation IfLoc) { IfStmtBits.IfLoc = IfLoc; }
SourceLocation getElseLoc() const {
return hasElseStorage() ? *getTrailingObjects<SourceLocation>()
: SourceLocation();
}
void setElseLoc(SourceLocation ElseLoc) {
assert(hasElseStorage() &&
"This if statement has no storage for an else statement!");
*getTrailingObjects<SourceLocation>() = ElseLoc;
}
bool isConstexpr() const { return IfStmtBits.IsConstexpr; }
void setConstexpr(bool C) { IfStmtBits.IsConstexpr = C; }
bool isObjCAvailabilityCheck() const;
SourceLocation getBeginLoc() const { return getIfLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
if (getElse())
return getElse()->getEndLoc();
return getThen()->getEndLoc();
}
// Iterators over subexpressions. The iterators will include iterating
// over the initialization expression referenced by the condition variable.
child_range children() {
return child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
const_child_range children() const {
return const_child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == IfStmtClass;
}
};
/// SwitchStmt - This represents a 'switch' stmt.
class SwitchStmt final : public Stmt,
private llvm::TrailingObjects<SwitchStmt, Stmt *> {
friend TrailingObjects;
/// Points to a linked list of case and default statements.
SwitchCase *FirstCase;
// SwitchStmt is followed by several trailing objects,
// some of which optional. Note that it would be more convenient to
// put the optional trailing objects at the end but this would change
// the order in children().
// The trailing objects are in order:
//
// * A "Stmt *" for the init statement.
// Present if and only if hasInitStorage().
//
// * A "Stmt *" for the condition variable.
// Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
//
// * A "Stmt *" for the condition.
// Always present. This is in fact an "Expr *".
//
// * A "Stmt *" for the body.
// Always present.
enum { InitOffset = 0, BodyOffsetFromCond = 1 };
enum { NumMandatoryStmtPtr = 2 };
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + hasInitStorage() + hasVarStorage();
}
unsigned initOffset() const { return InitOffset; }
unsigned varOffset() const { return InitOffset + hasInitStorage(); }
unsigned condOffset() const {
return InitOffset + hasInitStorage() + hasVarStorage();
}
unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
/// Build a switch statement.
SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond);
/// Build a empty switch statement.
explicit SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar);
public:
/// Create a switch statement.
static SwitchStmt *Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
Expr *Cond);
/// Create an empty switch statement optionally with storage for
/// an init expression and a condition variable.
static SwitchStmt *CreateEmpty(const ASTContext &Ctx, bool HasInit,
bool HasVar);
/// True if this SwitchStmt has storage for an init statement.
bool hasInitStorage() const { return SwitchStmtBits.HasInit; }
/// True if this SwitchStmt has storage for a condition variable.
bool hasVarStorage() const { return SwitchStmtBits.HasVar; }
Expr *getCond() {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
const Expr *getCond() const {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
void setCond(Expr *Cond) {
getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
}
Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
const Stmt *getBody() const {
return getTrailingObjects<Stmt *>()[bodyOffset()];
}
void setBody(Stmt *Body) {
getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
}
Stmt *getInit() {
return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
: nullptr;
}
const Stmt *getInit() const {
return hasInitStorage() ? getTrailingObjects<Stmt *>()[initOffset()]
: nullptr;
}
void setInit(Stmt *Init) {
assert(hasInitStorage() &&
"This switch statement has no storage for an init statement!");
getTrailingObjects<Stmt *>()[initOffset()] = Init;
}
/// Retrieve the variable declared in this "switch" statement, if any.
///
/// In the following example, "x" is the condition variable.
/// \code
/// switch (int x = foo()) {
/// case 0: break;
/// // ...
/// }
/// \endcode
VarDecl *getConditionVariable();
const VarDecl *getConditionVariable() const {
return const_cast<SwitchStmt *>(this)->getConditionVariable();
}
/// Set the condition variable in this switch statement.
/// The switch statement must have storage for it.
void setConditionVariable(const ASTContext &Ctx, VarDecl *VD);
/// If this SwitchStmt has a condition variable, return the faux DeclStmt
/// associated with the creation of that condition variable.
DeclStmt *getConditionVariableDeclStmt() {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
const DeclStmt *getConditionVariableDeclStmt() const {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
SwitchCase *getSwitchCaseList() { return FirstCase; }
const SwitchCase *getSwitchCaseList() const { return FirstCase; }
void setSwitchCaseList(SwitchCase *SC) { FirstCase = SC; }
SourceLocation getSwitchLoc() const { return SwitchStmtBits.SwitchLoc; }
void setSwitchLoc(SourceLocation L) { SwitchStmtBits.SwitchLoc = L; }
void setBody(Stmt *S, SourceLocation SL) {
setBody(S);
setSwitchLoc(SL);
}
void addSwitchCase(SwitchCase *SC) {
assert(!SC->getNextSwitchCase() &&
"case/default already added to a switch");
SC->setNextSwitchCase(FirstCase);
FirstCase = SC;
}
/// Set a flag in the SwitchStmt indicating that if the 'switch (X)' is a
/// switch over an enum value then all cases have been explicitly covered.
void setAllEnumCasesCovered() { SwitchStmtBits.AllEnumCasesCovered = true; }
/// Returns true if the SwitchStmt is a switch of an enum value and all cases
/// have been explicitly covered.
bool isAllEnumCasesCovered() const {
return SwitchStmtBits.AllEnumCasesCovered;
}
SourceLocation getBeginLoc() const { return getSwitchLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
return getBody() ? getBody()->getEndLoc()
: reinterpret_cast<const Stmt *>(getCond())->getEndLoc();
}
// Iterators
child_range children() {
return child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
const_child_range children() const {
return const_child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == SwitchStmtClass;
}
};
/// WhileStmt - This represents a 'while' stmt.
class WhileStmt final : public Stmt,
private llvm::TrailingObjects<WhileStmt, Stmt *> {
friend TrailingObjects;
// WhileStmt is followed by several trailing objects,
// some of which optional. Note that it would be more
// convenient to put the optional trailing object at the end
// but this would affect children().
// The trailing objects are in order:
//
// * A "Stmt *" for the condition variable.
// Present if and only if hasVarStorage(). This is in fact a "DeclStmt *".
//
// * A "Stmt *" for the condition.
// Always present. This is in fact an "Expr *".
//
// * A "Stmt *" for the body.
// Always present.
//
enum { VarOffset = 0, BodyOffsetFromCond = 1 };
enum { NumMandatoryStmtPtr = 2 };
unsigned varOffset() const { return VarOffset; }
unsigned condOffset() const { return VarOffset + hasVarStorage(); }
unsigned bodyOffset() const { return condOffset() + BodyOffsetFromCond; }
unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
return NumMandatoryStmtPtr + hasVarStorage();
}
/// Build a while statement.
WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body,
SourceLocation WL);
/// Build an empty while statement.
explicit WhileStmt(EmptyShell Empty, bool HasVar);
public:
/// Create a while statement.
static WhileStmt *Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
Stmt *Body, SourceLocation WL);
/// Create an empty while statement optionally with storage for
/// a condition variable.
static WhileStmt *CreateEmpty(const ASTContext &Ctx, bool HasVar);
/// True if this WhileStmt has storage for a condition variable.
bool hasVarStorage() const { return WhileStmtBits.HasVar; }
Expr *getCond() {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
const Expr *getCond() const {
return reinterpret_cast<Expr *>(getTrailingObjects<Stmt *>()[condOffset()]);
}
void setCond(Expr *Cond) {
getTrailingObjects<Stmt *>()[condOffset()] = reinterpret_cast<Stmt *>(Cond);
}
Stmt *getBody() { return getTrailingObjects<Stmt *>()[bodyOffset()]; }
const Stmt *getBody() const {
return getTrailingObjects<Stmt *>()[bodyOffset()];
}
void setBody(Stmt *Body) {
getTrailingObjects<Stmt *>()[bodyOffset()] = Body;
}
/// Retrieve the variable declared in this "while" statement, if any.
///
/// In the following example, "x" is the condition variable.
/// \code
/// while (int x = random()) {
/// // ...
/// }
/// \endcode
VarDecl *getConditionVariable();
const VarDecl *getConditionVariable() const {
return const_cast<WhileStmt *>(this)->getConditionVariable();
}
/// Set the condition variable of this while statement.
/// The while statement must have storage for it.
void setConditionVariable(const ASTContext &Ctx, VarDecl *V);
/// If this WhileStmt has a condition variable, return the faux DeclStmt
/// associated with the creation of that condition variable.
DeclStmt *getConditionVariableDeclStmt() {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
const DeclStmt *getConditionVariableDeclStmt() const {
return hasVarStorage() ? static_cast<DeclStmt *>(
getTrailingObjects<Stmt *>()[varOffset()])
: nullptr;
}
SourceLocation getWhileLoc() const { return WhileStmtBits.WhileLoc; }
void setWhileLoc(SourceLocation L) { WhileStmtBits.WhileLoc = L; }
SourceLocation getBeginLoc() const { return getWhileLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
return getBody()->getEndLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == WhileStmtClass;
}
// Iterators
child_range children() {
return child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
const_child_range children() const {
return const_child_range(getTrailingObjects<Stmt *>(),
getTrailingObjects<Stmt *>() +
numTrailingObjects(OverloadToken<Stmt *>()));
}
};
/// DoStmt - This represents a 'do/while' stmt.
class DoStmt : public Stmt {
enum { BODY, COND, END_EXPR };
Stmt *SubExprs[END_EXPR];
SourceLocation WhileLoc;
SourceLocation RParenLoc; // Location of final ')' in do stmt condition.
public:
DoStmt(Stmt *Body, Expr *Cond, SourceLocation DL, SourceLocation WL,
SourceLocation RP)
: Stmt(DoStmtClass), WhileLoc(WL), RParenLoc(RP) {
setCond(Cond);
setBody(Body);
setDoLoc(DL);
}
/// Build an empty do-while statement.
explicit DoStmt(EmptyShell Empty) : Stmt(DoStmtClass, Empty) {}
Expr *getCond() { return reinterpret_cast<Expr *>(SubExprs[COND]); }
const Expr *getCond() const {
return reinterpret_cast<Expr *>(SubExprs[COND]);
}
void setCond(Expr *Cond) { SubExprs[COND] = reinterpret_cast<Stmt *>(Cond); }
Stmt *getBody() { return SubExprs[BODY]; }
const Stmt *getBody() const { return SubExprs[BODY]; }
void setBody(Stmt *Body) { SubExprs[BODY] = Body; }
SourceLocation getDoLoc() const { return DoStmtBits.DoLoc; }
void setDoLoc(SourceLocation L) { DoStmtBits.DoLoc = L; }
SourceLocation getWhileLoc() const { return WhileLoc; }
void setWhileLoc(SourceLocation L) { WhileLoc = L; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
SourceLocation getBeginLoc() const { return getDoLoc(); }
SourceLocation getEndLoc() const { return getRParenLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == DoStmtClass;
}
// Iterators
child_range children() {
return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
}
const_child_range children() const {
return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
}
};
/// ForStmt - This represents a 'for (init;cond;inc)' stmt. Note that any of
/// the init/cond/inc parts of the ForStmt will be null if they were not
/// specified in the source.
class ForStmt : public Stmt {
enum { INIT, CONDVAR, COND, INC, BODY, END_EXPR };
Stmt* SubExprs[END_EXPR]; // SubExprs[INIT] is an expression or declstmt.
SourceLocation LParenLoc, RParenLoc;
public:
ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
SourceLocation RP);
/// Build an empty for statement.
explicit ForStmt(EmptyShell Empty) : Stmt(ForStmtClass, Empty) {}
Stmt *getInit() { return SubExprs[INIT]; }
/// Retrieve the variable declared in this "for" statement, if any.
///
/// In the following example, "y" is the condition variable.
/// \code
/// for (int x = random(); int y = mangle(x); ++x) {
/// // ...
/// }
/// \endcode
VarDecl *getConditionVariable() const;
void setConditionVariable(const ASTContext &C, VarDecl *V);
/// If this ForStmt has a condition variable, return the faux DeclStmt
/// associated with the creation of that condition variable.
const DeclStmt *getConditionVariableDeclStmt() const {
return reinterpret_cast<DeclStmt*>(SubExprs[CONDVAR]);
}
Expr *getCond() { return reinterpret_cast<Expr*>(SubExprs[COND]); }
Expr *getInc() { return reinterpret_cast<Expr*>(SubExprs[INC]); }
Stmt *getBody() { return SubExprs[BODY]; }
const Stmt *getInit() const { return SubExprs[INIT]; }
const Expr *getCond() const { return reinterpret_cast<Expr*>(SubExprs[COND]);}
const Expr *getInc() const { return reinterpret_cast<Expr*>(SubExprs[INC]); }
const Stmt *getBody() const { return SubExprs[BODY]; }
void setInit(Stmt *S) { SubExprs[INIT] = S; }
void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); }
void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); }
void setBody(Stmt *S) { SubExprs[BODY] = S; }
SourceLocation getForLoc() const { return ForStmtBits.ForLoc; }
void setForLoc(SourceLocation L) { ForStmtBits.ForLoc = L; }
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
SourceLocation getBeginLoc() const { return getForLoc(); }
SourceLocation getEndLoc() const { return getBody()->getEndLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ForStmtClass;
}
// Iterators
child_range children() {
return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
}
const_child_range children() const {
return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
}
};
/// GotoStmt - This represents a direct goto.
class GotoStmt : public Stmt {
LabelDecl *Label;
SourceLocation LabelLoc;
public:
GotoStmt(LabelDecl *label, SourceLocation GL, SourceLocation LL)
: Stmt(GotoStmtClass), Label(label), LabelLoc(LL) {
setGotoLoc(GL);
}
/// Build an empty goto statement.
explicit GotoStmt(EmptyShell Empty) : Stmt(GotoStmtClass, Empty) {}
LabelDecl *getLabel() const { return Label; }
void setLabel(LabelDecl *D) { Label = D; }
SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
SourceLocation getLabelLoc() const { return LabelLoc; }
void setLabelLoc(SourceLocation L) { LabelLoc = L; }
SourceLocation getBeginLoc() const { return getGotoLoc(); }
SourceLocation getEndLoc() const { return getLabelLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == GotoStmtClass;
}
// Iterators
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// IndirectGotoStmt - This represents an indirect goto.
class IndirectGotoStmt : public Stmt {
SourceLocation StarLoc;
Stmt *Target;
public:
IndirectGotoStmt(SourceLocation gotoLoc, SourceLocation starLoc, Expr *target)
: Stmt(IndirectGotoStmtClass), StarLoc(starLoc) {
setTarget(target);
setGotoLoc(gotoLoc);
}
/// Build an empty indirect goto statement.
explicit IndirectGotoStmt(EmptyShell Empty)
: Stmt(IndirectGotoStmtClass, Empty) {}
void setGotoLoc(SourceLocation L) { GotoStmtBits.GotoLoc = L; }
SourceLocation getGotoLoc() const { return GotoStmtBits.GotoLoc; }
void setStarLoc(SourceLocation L) { StarLoc = L; }
SourceLocation getStarLoc() const { return StarLoc; }
Expr *getTarget() { return reinterpret_cast<Expr *>(Target); }
const Expr *getTarget() const {
return reinterpret_cast<const Expr *>(Target);
}
void setTarget(Expr *E) { Target = reinterpret_cast<Stmt *>(E); }
/// getConstantTarget - Returns the fixed target of this indirect
/// goto, if one exists.
LabelDecl *getConstantTarget();
const LabelDecl *getConstantTarget() const {
return const_cast<IndirectGotoStmt *>(this)->getConstantTarget();
}
SourceLocation getBeginLoc() const { return getGotoLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY { return Target->getEndLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == IndirectGotoStmtClass;
}
// Iterators
child_range children() { return child_range(&Target, &Target + 1); }
const_child_range children() const {
return const_child_range(&Target, &Target + 1);
}
};
/// ContinueStmt - This represents a continue.
class ContinueStmt : public Stmt {
public:
ContinueStmt(SourceLocation CL) : Stmt(ContinueStmtClass) {
setContinueLoc(CL);
}
/// Build an empty continue statement.
explicit ContinueStmt(EmptyShell Empty) : Stmt(ContinueStmtClass, Empty) {}
SourceLocation getContinueLoc() const { return ContinueStmtBits.ContinueLoc; }
void setContinueLoc(SourceLocation L) { ContinueStmtBits.ContinueLoc = L; }
SourceLocation getBeginLoc() const { return getContinueLoc(); }
SourceLocation getEndLoc() const { return getContinueLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ContinueStmtClass;
}
// Iterators
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// BreakStmt - This represents a break.
class BreakStmt : public Stmt {
public:
BreakStmt(SourceLocation BL) : Stmt(BreakStmtClass) {
setBreakLoc(BL);
}
/// Build an empty break statement.
explicit BreakStmt(EmptyShell Empty) : Stmt(BreakStmtClass, Empty) {}
SourceLocation getBreakLoc() const { return BreakStmtBits.BreakLoc; }
void setBreakLoc(SourceLocation L) { BreakStmtBits.BreakLoc = L; }
SourceLocation getBeginLoc() const { return getBreakLoc(); }
SourceLocation getEndLoc() const { return getBreakLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == BreakStmtClass;
}
// Iterators
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// ReturnStmt - This represents a return, optionally of an expression:
/// return;
/// return 4;
///
/// Note that GCC allows return with no argument in a function declared to
/// return a value, and it allows returning a value in functions declared to
/// return void. We explicitly model this in the AST, which means you can't
/// depend on the return type of the function and the presence of an argument.
class ReturnStmt final
: public Stmt,
private llvm::TrailingObjects<ReturnStmt, const VarDecl *> {
friend TrailingObjects;
/// The return expression.
Stmt *RetExpr;
// ReturnStmt is followed optionally by a trailing "const VarDecl *"
// for the NRVO candidate. Present if and only if hasNRVOCandidate().
/// True if this ReturnStmt has storage for an NRVO candidate.
bool hasNRVOCandidate() const { return ReturnStmtBits.HasNRVOCandidate; }
unsigned numTrailingObjects(OverloadToken<const VarDecl *>) const {
return hasNRVOCandidate();
}
/// Build a return statement.
ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate);
/// Build an empty return statement.
explicit ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate);
public:
/// Create a return statement.
static ReturnStmt *Create(const ASTContext &Ctx, SourceLocation RL, Expr *E,
const VarDecl *NRVOCandidate);
/// Create an empty return statement, optionally with
/// storage for an NRVO candidate.
static ReturnStmt *CreateEmpty(const ASTContext &Ctx, bool HasNRVOCandidate);
Expr *getRetValue() { return reinterpret_cast<Expr *>(RetExpr); }
const Expr *getRetValue() const { return reinterpret_cast<Expr *>(RetExpr); }
void setRetValue(Expr *E) { RetExpr = reinterpret_cast<Stmt *>(E); }
/// Retrieve the variable that might be used for the named return
/// value optimization.
///
/// The optimization itself can only be performed if the variable is
/// also marked as an NRVO object.
const VarDecl *getNRVOCandidate() const {
return hasNRVOCandidate() ? *getTrailingObjects<const VarDecl *>()
: nullptr;
}
/// Set the variable that might be used for the named return value
/// optimization. The return statement must have storage for it,
/// which is the case if and only if hasNRVOCandidate() is true.
void setNRVOCandidate(const VarDecl *Var) {
assert(hasNRVOCandidate() &&
"This return statement has no storage for an NRVO candidate!");
*getTrailingObjects<const VarDecl *>() = Var;
}
SourceLocation getReturnLoc() const { return ReturnStmtBits.RetLoc; }
void setReturnLoc(SourceLocation L) { ReturnStmtBits.RetLoc = L; }
SourceLocation getBeginLoc() const { return getReturnLoc(); }
SourceLocation getEndLoc() const LLVM_READONLY {
return RetExpr ? RetExpr->getEndLoc() : getReturnLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == ReturnStmtClass;
}
// Iterators
child_range children() {
if (RetExpr)
return child_range(&RetExpr, &RetExpr + 1);
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
if (RetExpr)
return const_child_range(&RetExpr, &RetExpr + 1);
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// AsmStmt is the base class for GCCAsmStmt and MSAsmStmt.
class AsmStmt : public Stmt {
protected:
friend class ASTStmtReader;
SourceLocation AsmLoc;
/// True if the assembly statement does not have any input or output
/// operands.
bool IsSimple;
/// If true, treat this inline assembly as having side effects.
/// This assembly statement should not be optimized, deleted or moved.
bool IsVolatile;
unsigned NumOutputs;
unsigned NumInputs;
unsigned NumClobbers;
Stmt **Exprs = nullptr;
AsmStmt(StmtClass SC, SourceLocation asmloc, bool issimple, bool isvolatile,
unsigned numoutputs, unsigned numinputs, unsigned numclobbers)
: Stmt (SC), AsmLoc(asmloc), IsSimple(issimple), IsVolatile(isvolatile),
NumOutputs(numoutputs), NumInputs(numinputs),
NumClobbers(numclobbers) {}
public:
/// Build an empty inline-assembly statement.
explicit AsmStmt(StmtClass SC, EmptyShell Empty) : Stmt(SC, Empty) {}
SourceLocation getAsmLoc() const { return AsmLoc; }
void setAsmLoc(SourceLocation L) { AsmLoc = L; }
bool isSimple() const { return IsSimple; }
void setSimple(bool V) { IsSimple = V; }
bool isVolatile() const { return IsVolatile; }
void setVolatile(bool V) { IsVolatile = V; }
SourceLocation getBeginLoc() const LLVM_READONLY { return {}; }
SourceLocation getEndLoc() const LLVM_READONLY { return {}; }
//===--- Asm String Analysis ---===//
/// Assemble final IR asm string.
std::string generateAsmString(const ASTContext &C) const;
//===--- Output operands ---===//
unsigned getNumOutputs() const { return NumOutputs; }
/// getOutputConstraint - Return the constraint string for the specified
/// output operand. All output constraints are known to be non-empty (either
/// '=' or '+').
StringRef getOutputConstraint(unsigned i) const;
/// isOutputPlusConstraint - Return true if the specified output constraint
/// is a "+" constraint (which is both an input and an output) or false if it
/// is an "=" constraint (just an output).
bool isOutputPlusConstraint(unsigned i) const {
return getOutputConstraint(i)[0] == '+';
}
const Expr *getOutputExpr(unsigned i) const;
/// getNumPlusOperands - Return the number of output operands that have a "+"
/// constraint.
unsigned getNumPlusOperands() const;
//===--- Input operands ---===//
unsigned getNumInputs() const { return NumInputs; }
/// getInputConstraint - Return the specified input constraint. Unlike output
/// constraints, these can be empty.
StringRef getInputConstraint(unsigned i) const;
const Expr *getInputExpr(unsigned i) const;
//===--- Other ---===//
unsigned getNumClobbers() const { return NumClobbers; }
StringRef getClobber(unsigned i) const;
static bool classof(const Stmt *T) {
return T->getStmtClass() == GCCAsmStmtClass ||
T->getStmtClass() == MSAsmStmtClass;
}
// Input expr iterators.
using inputs_iterator = ExprIterator;
using const_inputs_iterator = ConstExprIterator;
using inputs_range = llvm::iterator_range<inputs_iterator>;
using inputs_const_range = llvm::iterator_range<const_inputs_iterator>;
inputs_iterator begin_inputs() {
return &Exprs[0] + NumOutputs;
}
inputs_iterator end_inputs() {
return &Exprs[0] + NumOutputs + NumInputs;
}
inputs_range inputs() { return inputs_range(begin_inputs(), end_inputs()); }
const_inputs_iterator begin_inputs() const {
return &Exprs[0] + NumOutputs;
}
const_inputs_iterator end_inputs() const {
return &Exprs[0] + NumOutputs + NumInputs;
}
inputs_const_range inputs() const {
return inputs_const_range(begin_inputs(), end_inputs());
}
// Output expr iterators.
using outputs_iterator = ExprIterator;
using const_outputs_iterator = ConstExprIterator;
using outputs_range = llvm::iterator_range<outputs_iterator>;
using outputs_const_range = llvm::iterator_range<const_outputs_iterator>;
outputs_iterator begin_outputs() {
return &Exprs[0];
}
outputs_iterator end_outputs() {
return &Exprs[0] + NumOutputs;
}
outputs_range outputs() {
return outputs_range(begin_outputs(), end_outputs());
}
const_outputs_iterator begin_outputs() const {
return &Exprs[0];
}
const_outputs_iterator end_outputs() const {
return &Exprs[0] + NumOutputs;
}
outputs_const_range outputs() const {
return outputs_const_range(begin_outputs(), end_outputs());
}
child_range children() {
return child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
}
const_child_range children() const {
return const_child_range(&Exprs[0], &Exprs[0] + NumOutputs + NumInputs);
}
};
/// This represents a GCC inline-assembly statement extension.
class GCCAsmStmt : public AsmStmt {
friend class ASTStmtReader;
SourceLocation RParenLoc;
StringLiteral *AsmStr;
// FIXME: If we wanted to, we could allocate all of these in one big array.
StringLiteral **Constraints = nullptr;
StringLiteral **Clobbers = nullptr;
IdentifierInfo **Names = nullptr;
public:
GCCAsmStmt(const ASTContext &C, SourceLocation asmloc, bool issimple,
bool isvolatile, unsigned numoutputs, unsigned numinputs,
IdentifierInfo **names, StringLiteral **constraints, Expr **exprs,
StringLiteral *asmstr, unsigned numclobbers,
StringLiteral **clobbers, SourceLocation rparenloc);
/// Build an empty inline-assembly statement.
explicit GCCAsmStmt(EmptyShell Empty) : AsmStmt(GCCAsmStmtClass, Empty) {}
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
//===--- Asm String Analysis ---===//
const StringLiteral *getAsmString() const { return AsmStr; }
StringLiteral *getAsmString() { return AsmStr; }
void setAsmString(StringLiteral *E) { AsmStr = E; }
/// AsmStringPiece - this is part of a decomposed asm string specification
/// (for use with the AnalyzeAsmString function below). An asm string is
/// considered to be a concatenation of these parts.
class AsmStringPiece {
public:
enum Kind {
String, // String in .ll asm string form, "$" -> "$$" and "%%" -> "%".
Operand // Operand reference, with optional modifier %c4.
};
private:
Kind MyKind;
std::string Str;
unsigned OperandNo;
// Source range for operand references.
CharSourceRange Range;
public:
AsmStringPiece(const std::string &S) : MyKind(String), Str(S) {}
AsmStringPiece(unsigned OpNo, const std::string &S, SourceLocation Begin,
SourceLocation End)
: MyKind(Operand), Str(S), OperandNo(OpNo),
Range(CharSourceRange::getCharRange(Begin, End)) {}
bool isString() const { return MyKind == String; }
bool isOperand() const { return MyKind == Operand; }
const std::string &getString() const { return Str; }
unsigned getOperandNo() const {
assert(isOperand());
return OperandNo;
}
CharSourceRange getRange() const {
assert(isOperand() && "Range is currently used only for Operands.");
return Range;
}
/// getModifier - Get the modifier for this operand, if present. This
/// returns '\0' if there was no modifier.
char getModifier() const;
};
/// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
/// it into pieces. If the asm string is erroneous, emit errors and return
/// true, otherwise return false. This handles canonicalization and
/// translation of strings from GCC syntax to LLVM IR syntax, and handles
//// flattening of named references like %[foo] to Operand AsmStringPiece's.
unsigned AnalyzeAsmString(SmallVectorImpl<AsmStringPiece> &Pieces,
const ASTContext &C, unsigned &DiagOffs) const;
/// Assemble final IR asm string.
std::string generateAsmString(const ASTContext &C) const;
//===--- Output operands ---===//
IdentifierInfo *getOutputIdentifier(unsigned i) const { return Names[i]; }
StringRef getOutputName(unsigned i) const {
if (IdentifierInfo *II = getOutputIdentifier(i))
return II->getName();
return {};
}
StringRef getOutputConstraint(unsigned i) const;
const StringLiteral *getOutputConstraintLiteral(unsigned i) const {
return Constraints[i];
}
StringLiteral *getOutputConstraintLiteral(unsigned i) {
return Constraints[i];
}
Expr *getOutputExpr(unsigned i);
const Expr *getOutputExpr(unsigned i) const {
return const_cast<GCCAsmStmt*>(this)->getOutputExpr(i);
}
//===--- Input operands ---===//
IdentifierInfo *getInputIdentifier(unsigned i) const {
return Names[i + NumOutputs];
}
StringRef getInputName(unsigned i) const {
if (IdentifierInfo *II = getInputIdentifier(i))
return II->getName();
return {};
}
StringRef getInputConstraint(unsigned i) const;
const StringLiteral *getInputConstraintLiteral(unsigned i) const {
return Constraints[i + NumOutputs];
}
StringLiteral *getInputConstraintLiteral(unsigned i) {
return Constraints[i + NumOutputs];
}
Expr *getInputExpr(unsigned i);
void setInputExpr(unsigned i, Expr *E);
const Expr *getInputExpr(unsigned i) const {
return const_cast<GCCAsmStmt*>(this)->getInputExpr(i);
}
private:
void setOutputsAndInputsAndClobbers(const ASTContext &C,
IdentifierInfo **Names,
StringLiteral **Constraints,
Stmt **Exprs,
unsigned NumOutputs,
unsigned NumInputs,
StringLiteral **Clobbers,
unsigned NumClobbers);
public:
//===--- Other ---===//
/// getNamedOperand - Given a symbolic operand reference like %[foo],
/// translate this into a numeric value needed to reference the same operand.
/// This returns -1 if the operand name is invalid.
int getNamedOperand(StringRef SymbolicName) const;
StringRef getClobber(unsigned i) const;
StringLiteral *getClobberStringLiteral(unsigned i) { return Clobbers[i]; }
const StringLiteral *getClobberStringLiteral(unsigned i) const {
return Clobbers[i];
}
SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == GCCAsmStmtClass;
}
};
/// This represents a Microsoft inline-assembly statement extension.
class MSAsmStmt : public AsmStmt {
friend class ASTStmtReader;
SourceLocation LBraceLoc, EndLoc;
StringRef AsmStr;
unsigned NumAsmToks = 0;
Token *AsmToks = nullptr;
StringRef *Constraints = nullptr;
StringRef *Clobbers = nullptr;
public:
MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
SourceLocation lbraceloc, bool issimple, bool isvolatile,
ArrayRef<Token> asmtoks, unsigned numoutputs, unsigned numinputs,
ArrayRef<StringRef> constraints,
ArrayRef<Expr*> exprs, StringRef asmstr,
ArrayRef<StringRef> clobbers, SourceLocation endloc);
/// Build an empty MS-style inline-assembly statement.
explicit MSAsmStmt(EmptyShell Empty) : AsmStmt(MSAsmStmtClass, Empty) {}
SourceLocation getLBraceLoc() const { return LBraceLoc; }
void setLBraceLoc(SourceLocation L) { LBraceLoc = L; }
SourceLocation getEndLoc() const { return EndLoc; }
void setEndLoc(SourceLocation L) { EndLoc = L; }
bool hasBraces() const { return LBraceLoc.isValid(); }
unsigned getNumAsmToks() { return NumAsmToks; }
Token *getAsmToks() { return AsmToks; }
//===--- Asm String Analysis ---===//
StringRef getAsmString() const { return AsmStr; }
/// Assemble final IR asm string.
std::string generateAsmString(const ASTContext &C) const;
//===--- Output operands ---===//
StringRef getOutputConstraint(unsigned i) const {
assert(i < NumOutputs);
return Constraints[i];
}
Expr *getOutputExpr(unsigned i);
const Expr *getOutputExpr(unsigned i) const {
return const_cast<MSAsmStmt*>(this)->getOutputExpr(i);
}
//===--- Input operands ---===//
StringRef getInputConstraint(unsigned i) const {
assert(i < NumInputs);
return Constraints[i + NumOutputs];
}
Expr *getInputExpr(unsigned i);
void setInputExpr(unsigned i, Expr *E);
const Expr *getInputExpr(unsigned i) const {
return const_cast<MSAsmStmt*>(this)->getInputExpr(i);
}
//===--- Other ---===//
ArrayRef<StringRef> getAllConstraints() const {
return llvm::makeArrayRef(Constraints, NumInputs + NumOutputs);
}
ArrayRef<StringRef> getClobbers() const {
return llvm::makeArrayRef(Clobbers, NumClobbers);
}
ArrayRef<Expr*> getAllExprs() const {
return llvm::makeArrayRef(reinterpret_cast<Expr**>(Exprs),
NumInputs + NumOutputs);
}
StringRef getClobber(unsigned i) const { return getClobbers()[i]; }
private:
void initialize(const ASTContext &C, StringRef AsmString,
ArrayRef<Token> AsmToks, ArrayRef<StringRef> Constraints,
ArrayRef<Expr*> Exprs, ArrayRef<StringRef> Clobbers);
public:
SourceLocation getBeginLoc() const LLVM_READONLY { return AsmLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == MSAsmStmtClass;
}
child_range children() {
return child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
}
const_child_range children() const {
return const_child_range(&Exprs[0], &Exprs[NumInputs + NumOutputs]);
}
};
class SEHExceptStmt : public Stmt {
friend class ASTReader;
friend class ASTStmtReader;
SourceLocation Loc;
Stmt *Children[2];
enum { FILTER_EXPR, BLOCK };
SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block);
explicit SEHExceptStmt(EmptyShell E) : Stmt(SEHExceptStmtClass, E) {}
public:
static SEHExceptStmt* Create(const ASTContext &C,
SourceLocation ExceptLoc,
Expr *FilterExpr,
Stmt *Block);
SourceLocation getBeginLoc() const LLVM_READONLY { return getExceptLoc(); }
SourceLocation getExceptLoc() const { return Loc; }
SourceLocation getEndLoc() const { return getBlock()->getEndLoc(); }
Expr *getFilterExpr() const {
return reinterpret_cast<Expr*>(Children[FILTER_EXPR]);
}
CompoundStmt *getBlock() const {
return cast<CompoundStmt>(Children[BLOCK]);
}
child_range children() {
return child_range(Children, Children+2);
}
const_child_range children() const {
return const_child_range(Children, Children + 2);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == SEHExceptStmtClass;
}
};
class SEHFinallyStmt : public Stmt {
friend class ASTReader;
friend class ASTStmtReader;
SourceLocation Loc;
Stmt *Block;
SEHFinallyStmt(SourceLocation Loc, Stmt *Block);
explicit SEHFinallyStmt(EmptyShell E) : Stmt(SEHFinallyStmtClass, E) {}
public:
static SEHFinallyStmt* Create(const ASTContext &C,
SourceLocation FinallyLoc,
Stmt *Block);
SourceLocation getBeginLoc() const LLVM_READONLY { return getFinallyLoc(); }
SourceLocation getFinallyLoc() const { return Loc; }
SourceLocation getEndLoc() const { return Block->getEndLoc(); }
CompoundStmt *getBlock() const { return cast<CompoundStmt>(Block); }
child_range children() {
return child_range(&Block,&Block+1);
}
const_child_range children() const {
return const_child_range(&Block, &Block + 1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == SEHFinallyStmtClass;
}
};
class SEHTryStmt : public Stmt {
friend class ASTReader;
friend class ASTStmtReader;
bool IsCXXTry;
SourceLocation TryLoc;
Stmt *Children[2];
enum { TRY = 0, HANDLER = 1 };
SEHTryStmt(bool isCXXTry, // true if 'try' otherwise '__try'
SourceLocation TryLoc,
Stmt *TryBlock,
Stmt *Handler);
explicit SEHTryStmt(EmptyShell E) : Stmt(SEHTryStmtClass, E) {}
public:
static SEHTryStmt* Create(const ASTContext &C, bool isCXXTry,
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
SourceLocation getBeginLoc() const LLVM_READONLY { return getTryLoc(); }
SourceLocation getTryLoc() const { return TryLoc; }
SourceLocation getEndLoc() const { return Children[HANDLER]->getEndLoc(); }
bool getIsCXXTry() const { return IsCXXTry; }
CompoundStmt* getTryBlock() const {
return cast<CompoundStmt>(Children[TRY]);
}
Stmt *getHandler() const { return Children[HANDLER]; }
/// Returns 0 if not defined
SEHExceptStmt *getExceptHandler() const;
SEHFinallyStmt *getFinallyHandler() const;
child_range children() {
return child_range(Children, Children+2);
}
const_child_range children() const {
return const_child_range(Children, Children + 2);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == SEHTryStmtClass;
}
};
/// Represents a __leave statement.
class SEHLeaveStmt : public Stmt {
SourceLocation LeaveLoc;
public:
explicit SEHLeaveStmt(SourceLocation LL)
: Stmt(SEHLeaveStmtClass), LeaveLoc(LL) {}
/// Build an empty __leave statement.
explicit SEHLeaveStmt(EmptyShell Empty) : Stmt(SEHLeaveStmtClass, Empty) {}
SourceLocation getLeaveLoc() const { return LeaveLoc; }
void setLeaveLoc(SourceLocation L) { LeaveLoc = L; }
SourceLocation getBeginLoc() const LLVM_READONLY { return LeaveLoc; }
SourceLocation getEndLoc() const LLVM_READONLY { return LeaveLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == SEHLeaveStmtClass;
}
// Iterators
child_range children() {
return child_range(child_iterator(), child_iterator());
}
const_child_range children() const {
return const_child_range(const_child_iterator(), const_child_iterator());
}
};
/// This captures a statement into a function. For example, the following
/// pragma annotated compound statement can be represented as a CapturedStmt,
/// and this compound statement is the body of an anonymous outlined function.
/// @code
/// #pragma omp parallel
/// {
/// compute();
/// }
/// @endcode
class CapturedStmt : public Stmt {
public:
/// The different capture forms: by 'this', by reference, capture for
/// variable-length array type etc.
enum VariableCaptureKind {
VCK_This,
VCK_ByRef,
VCK_ByCopy,
VCK_VLAType,
};
/// Describes the capture of either a variable, or 'this', or
/// variable-length array type.
class Capture {
llvm::PointerIntPair<VarDecl *, 2, VariableCaptureKind> VarAndKind;
SourceLocation Loc;
public:
friend class ASTStmtReader;
/// Create a new capture.
///
/// \param Loc The source location associated with this capture.
///
/// \param Kind The kind of capture (this, ByRef, ...).
///
/// \param Var The variable being captured, or null if capturing this.
Capture(SourceLocation Loc, VariableCaptureKind Kind,
VarDecl *Var = nullptr);
/// Determine the kind of capture.
VariableCaptureKind getCaptureKind() const;
/// Retrieve the source location at which the variable or 'this' was
/// first used.
SourceLocation getLocation() const { return Loc; }
/// Determine whether this capture handles the C++ 'this' pointer.
bool capturesThis() const { return getCaptureKind() == VCK_This; }
/// Determine whether this capture handles a variable (by reference).
bool capturesVariable() const { return getCaptureKind() == VCK_ByRef; }
/// Determine whether this capture handles a variable by copy.
bool capturesVariableByCopy() const {
return getCaptureKind() == VCK_ByCopy;
}
/// Determine whether this capture handles a variable-length array
/// type.
bool capturesVariableArrayType() const {
return getCaptureKind() == VCK_VLAType;
}
/// Retrieve the declaration of the variable being captured.
///
/// This operation is only valid if this capture captures a variable.
VarDecl *getCapturedVar() const;
};
private:
/// The number of variable captured, including 'this'.
unsigned NumCaptures;
/// The pointer part is the implicit the outlined function and the
/// int part is the captured region kind, 'CR_Default' etc.
llvm::PointerIntPair<CapturedDecl *, 2, CapturedRegionKind> CapDeclAndKind;
/// The record for captured variables, a RecordDecl or CXXRecordDecl.
RecordDecl *TheRecordDecl = nullptr;
/// Construct a captured statement.
CapturedStmt(Stmt *S, CapturedRegionKind Kind, ArrayRef<Capture> Captures,
ArrayRef<Expr *> CaptureInits, CapturedDecl *CD, RecordDecl *RD);
/// Construct an empty captured statement.
CapturedStmt(EmptyShell Empty, unsigned NumCaptures);
Stmt **getStoredStmts() { return reinterpret_cast<Stmt **>(this + 1); }
Stmt *const *getStoredStmts() const {
return reinterpret_cast<Stmt *const *>(this + 1);
}
Capture *getStoredCaptures() const;
void setCapturedStmt(Stmt *S) { getStoredStmts()[NumCaptures] = S; }
public:
friend class ASTStmtReader;
static CapturedStmt *Create(const ASTContext &Context, Stmt *S,
CapturedRegionKind Kind,
ArrayRef<Capture> Captures,
ArrayRef<Expr *> CaptureInits,
CapturedDecl *CD, RecordDecl *RD);
static CapturedStmt *CreateDeserialized(const ASTContext &Context,
unsigned NumCaptures);
/// Retrieve the statement being captured.
Stmt *getCapturedStmt() { return getStoredStmts()[NumCaptures]; }
const Stmt *getCapturedStmt() const { return getStoredStmts()[NumCaptures]; }
/// Retrieve the outlined function declaration.
CapturedDecl *getCapturedDecl();
const CapturedDecl *getCapturedDecl() const;
/// Set the outlined function declaration.
void setCapturedDecl(CapturedDecl *D);
/// Retrieve the captured region kind.
CapturedRegionKind getCapturedRegionKind() const;
/// Set the captured region kind.
void setCapturedRegionKind(CapturedRegionKind Kind);
/// Retrieve the record declaration for captured variables.
const RecordDecl *getCapturedRecordDecl() const { return TheRecordDecl; }
/// Set the record declaration for captured variables.
void setCapturedRecordDecl(RecordDecl *D) {
assert(D && "null RecordDecl");
TheRecordDecl = D;
}
/// True if this variable has been captured.
bool capturesVariable(const VarDecl *Var) const;
/// An iterator that walks over the captures.
using capture_iterator = Capture *;
using const_capture_iterator = const Capture *;
using capture_range = llvm::iterator_range<capture_iterator>;
using capture_const_range = llvm::iterator_range<const_capture_iterator>;
capture_range captures() {
return capture_range(capture_begin(), capture_end());
}
capture_const_range captures() const {
return capture_const_range(capture_begin(), capture_end());
}
/// Retrieve an iterator pointing to the first capture.
capture_iterator capture_begin() { return getStoredCaptures(); }
const_capture_iterator capture_begin() const { return getStoredCaptures(); }
/// Retrieve an iterator pointing past the end of the sequence of
/// captures.
capture_iterator capture_end() const {
return getStoredCaptures() + NumCaptures;
}
/// Retrieve the number of captures, including 'this'.
unsigned capture_size() const { return NumCaptures; }
/// Iterator that walks over the capture initialization arguments.
using capture_init_iterator = Expr **;
using capture_init_range = llvm::iterator_range<capture_init_iterator>;
/// Const iterator that walks over the capture initialization
/// arguments.
using const_capture_init_iterator = Expr *const *;
using const_capture_init_range =
llvm::iterator_range<const_capture_init_iterator>;
capture_init_range capture_inits() {
return capture_init_range(capture_init_begin(), capture_init_end());
}
const_capture_init_range capture_inits() const {
return const_capture_init_range(capture_init_begin(), capture_init_end());
}
/// Retrieve the first initialization argument.
capture_init_iterator capture_init_begin() {
return reinterpret_cast<Expr **>(getStoredStmts());
}
const_capture_init_iterator capture_init_begin() const {
return reinterpret_cast<Expr *const *>(getStoredStmts());
}
/// Retrieve the iterator pointing one past the last initialization
/// argument.
capture_init_iterator capture_init_end() {
return capture_init_begin() + NumCaptures;
}
const_capture_init_iterator capture_init_end() const {
return capture_init_begin() + NumCaptures;
}
SourceLocation getBeginLoc() const LLVM_READONLY {
return getCapturedStmt()->getBeginLoc();
}
SourceLocation getEndLoc() const LLVM_READONLY {
return getCapturedStmt()->getEndLoc();
}
SourceRange getSourceRange() const LLVM_READONLY {
return getCapturedStmt()->getSourceRange();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CapturedStmtClass;
}
child_range children();
const_child_range children() const;
};
} // namespace clang
#endif // LLVM_CLANG_AST_STMT_H
|
milc_to_qphix_utilities.c | /******************* milc_to_qphix_utilities.c ************************/
/* For the QPhiX interface */
/* MIMD version 7 */
/* 11/28/15 Created by Dhiraj Khalamkar */
#include "../include/generic_qphix.h"
#include "../include/generic.h"
#include <lattice.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <omp.h>
#define CG_DEBUG 1
#define UNOPTIMIZED_PACK_UNPACK 0
static int is_qphix_env_setup = 0;
/* The MILC layout routines list the coordinates and assume 4D */
static int milc_node_number(const int coords[]){
return node_number(coords[0],coords[1],coords[2],coords[3]);
}
static int milc_node_index(const int coords[]){
return node_index(coords[0],coords[1],coords[2],coords[3]);
}
QPHIX_evenodd_t milc2qphix_parity(int milc_parity){
switch(milc_parity){
case(EVEN): return QPHIX_EVEN;
case(ODD ): return QPHIX_ODD;
case(EVENANDODD): return QPHIX_EVENODD;
default:
printf("milc2qphix_parity: Bad MILC parity %d\n", milc_parity);
terminate(1);
}
return (QPHIX_evenodd_t)-999;
}
int qphix2milc_parity(QPHIX_evenodd_t qphix_parity){
switch(qphix_parity){
case(QPHIX_EVEN): return EVEN;
case(QPHIX_ODD ): return ODD;
case(QPHIX_EVENODD ): return EVENANDODD;
default:
printf("qphix2milc_parity: Bad QPHIX parity %d\n", qphix_parity);
terminate(1);
}
return -999;
}
QPHIX_status_t
initialize_qphix(int precision){
/* \fixme - pass the qphix params via setup */
/* create mbench */
int minCt = 1;
int threads_per_core = 1;
int numThreads = omp_get_max_threads();
if(getenv("MINCT")) minCt = atoi(getenv("MINCT"));
if(getenv("THREADS_PER_CORE")) threads_per_core = atoi(getenv("THREADS_PER_CORE"));
int numCores = numThreads / threads_per_core;
int status = 0;
static int latsize[4];
static QPHIX_layout_t layout;
latsize[0] = nx;
latsize[1] = ny;
latsize[2] = nz;
latsize[3] = nt;
if(is_qphix_env_setup > 0){
if(is_qphix_env_setup == precision)
return status;
else
/* Finalize so we can then initialize with the new precision */
finalize_qphix();
}
layout.node_number = milc_node_number;
layout.node_index = milc_node_index;
layout.latdim = 4;
layout.latsize = latsize;
layout.machdim = 4;
layout.machsize = (int *)get_logical_dimensions();
layout.this_node = this_node;
layout.even_sites_on_node = even_sites_on_node;
layout.sites_on_node = sites_on_node;
node0_printf("Initializing QPhiX for precision %d\n", precision);
node0_printf("NumCores = %d, ThreadsPerCore = %d, minCt = %d\n", numCores, threads_per_core, minCt);
status = QPHIX_init(&layout, precision);
if(status){
node0_printf("Error initializing QPhiX\n");
fflush(stdout);
terminate(1);
}
fflush(stdout);
is_qphix_env_setup = precision;
return status;
}
void
finalize_qphix(void){
QPHIX_finalize();
}
#if 0
/*! \brief Constructor to create the single global qphix_env_t object. */
void
create_qphix_env ( int nx
, int ny
, int nz
, int nt
, int ncores
, int threads_per_core
, int min_ct
//, int soalen
//, int by
//, int bz
//, bool use_compressed12
)
{
void *gfl_e, *gfl_o, *gll_e, *gll_o;
int neigh_ranks[8];
int latt[4] = { nx, ny, nz, nt};
//int *myCoord = get_logical_coordinates();
int myCoord[4]; // = get_logical_coordinates();
int *geom = get_logical_dimensions();
int tmp = this_node;
myCoord[0] = tmp % geom[0];
tmp = tmp / geom[0];
myCoord[1] = tmp % geom[1];
tmp = tmp / geom[1];
myCoord[2] = tmp % geom[2];
tmp = tmp / geom[2];
myCoord[3] = tmp % geom[3];
if(this_node != myCoord[0] + geom[0]*( myCoord[1] + geom[1]*( myCoord[2] + geom[2]*( myCoord[3] )))) {
printf("my Coord are wrong, this_node=%d\n", this_node);
exit(1);
}
qphix_env_t *env = (qphix_env_t*)malloc(sizeof(qphix_env_t));
if(env == NULL) {
fprintf( stderr, "ERROR: Could not alloc mbench_t. Exiting." );
exit(1);
}
for(int i = 0; i < 4; i++) {
int neigh_coord[4] = {myCoord[0], myCoord[1], myCoord[2], myCoord[3]};
neigh_coord[i] = (myCoord[i] == 0 ? geom[i] - 1 : myCoord[i] - 1);
neigh_ranks[2*i] = neigh_coord[0] + geom[0]*( neigh_coord[1] + geom[1]*( neigh_coord[2] + geom[2]*( neigh_coord[3] )));;
neigh_coord[i] = (myCoord[i] == geom[i] - 1 ? 0 : myCoord[i] + 1);
neigh_ranks[2*i+1] = neigh_coord[0] + geom[0]*( neigh_coord[1] + geom[1]*( neigh_coord[2] + geom[2]*( neigh_coord[3] )));;
}
setup_mbench(latt, geom, myCoord, neigh_ranks, this_node, ncores, threads_per_core, min_ct);
/* Allocate the data structures for mbench */
gfl_e = allocGauge18();
gfl_o = allocGauge18();
gll_e = allocGauge();
gll_o = allocGauge();
env->ks_src1 = allocKS();
env->ks_dest1 = allocKS();
env->ks_src2 = allocKS();
env->ks_dest2 = allocKS();
env->gll[0] = gll_e;
env->gll[1] = gll_o;
env->gfl[0] = gfl_e;
env->gfl[1] = gfl_o;
/* Set the global values */
g_qphix_env_obj = env;
is_qphix_env_setup = true;
}
/*! \brief Destroy the global qphix_env object */
void
destroy_qphix_env (void)
{
freeKS(g_qphix_env_obj->ks_src1);
freeKS(g_qphix_env_obj->ks_dest1);
freeKS(g_qphix_env_obj->ks_src2);
freeKS(g_qphix_env_obj->ks_dest2);
freeGauge(g_qphix_env_obj->gll[0]);
freeGauge(g_qphix_env_obj->gll[1]);
freeGauge18(g_qphix_env_obj->gfl[0]);
freeGauge18(g_qphix_env_obj->gfl[1]);
free(g_qphix_env_obj);
is_qphix_env_setup = false;
}
/*!
* Copy of load_longbacklinks (fermion_links_helpers.c), without the adjoint.
* We do adjoint in the generated code for the dslash kernels for the back
* links.
*/
su3_matrix *
load_longbacklinks_without_adjoint(fn_links_t *fn)
{
su3_matrix *t_lbl = NULL;
su3_matrix *t_ll = get_lnglinks(fn);
register int i;
register site *s;
int dir;
su3_matrix *tempmat1 = NULL;
msg_tag *tag[4];
char myname[] = "load_longbacklinks";
/* Allocate space for t_lbl if NULL */
t_lbl = (su3_matrix *)malloc(sites_on_node*4*sizeof(su3_matrix));
if(t_lbl==NULL){
printf("%s(%d): no room for t_lbl\n",myname,this_node);
terminate(1);
}
tempmat1 = (su3_matrix *)malloc(sites_on_node*sizeof(su3_matrix));
if(tempmat1 == NULL){
printf("%s: Can't malloc temporary\n",myname);
terminate(1);
}
/* gather backwards longlinks */
for( dir=XUP; dir<=TUP; dir ++){
#pragma omp parallel for
for (i = 0; i < sites_on_node; i++) {
tempmat1[i] = t_ll[dir+4*i];
}
tag[dir] = start_gather_field( tempmat1
, sizeof(su3_matrix)
, OPP_3_DIR(DIR3(dir))
, EVENANDODD
, gen_pt[dir] );
wait_gather( tag[dir] );
#pragma omp parallel for
for (i = 0; i < sites_on_node; i++) {
su3_matrix * temp_ = (t_lbl + dir + 4*i);
*temp_ = *((su3_matrix *)gen_pt[dir][i]);
}
cleanup_gather( tag[dir] );
}
free(tempmat1);
tempmat1 = NULL;
return t_lbl;
}
/*!
* Copy of load_fatbacklinks (fermion_links_helpers.c), without the adjoint.
* We do adjoint in the generated code for the dslash kernels for the back
* links.
*/
su3_matrix *
load_fatbacklinks_without_adjoint(fn_links_t *fn)
{
su3_matrix *t_fbl = NULL;
su3_matrix *t_fl = get_fatlinks(fn);
register int i;
register site *s;
int dir;
su3_matrix *tempmat1 = NULL;
msg_tag *tag[4];
char myname[] = "load_fatbacklinks";
/* Allocate space for t_fbl if NULL */
t_fbl = (su3_matrix *)malloc(sites_on_node*4*sizeof(su3_matrix));
if(t_fbl==NULL){
printf("%s(%d): no room for t_fbl\n",myname,this_node);
terminate(1);
}
tempmat1 = (su3_matrix *)malloc(sites_on_node*sizeof(su3_matrix));
if(tempmat1 == NULL){
printf("%s: Can't malloc temporary\n",myname);
terminate(1);
}
/* gather backwards fatlinks */
for( dir=XUP; dir<=TUP; dir ++){
#pragma omp parallel for
for (i = 0; i < sites_on_node; i++) {
tempmat1[i] = t_fl[dir+4*i];
}
tag[dir] = start_gather_field( tempmat1
, sizeof(su3_matrix)
, OPP_DIR(dir)
, EVENANDODD
, gen_pt[dir]
);
wait_gather( tag[dir] );
#pragma omp parallel for
for (i = 0; i < sites_on_node; i++) {
su3_matrix* temp_ = (t_fbl + dir + 4*i);
*temp_ = *((su3_matrix *)gen_pt[dir][i]);
}
cleanup_gather( tag[dir] );
}
free(tempmat1);
tempmat1 = NULL;
return t_fbl;
}
/*!
* Convenience function to create and array of su3_vectors from the lattice
* site array. The argument defines if we want to copy over the source or the
* destination.
*/
/* SEE su3_vector *create_v_field_from_site_member(field_offset sv) */
void
get_links_from_lattice (void* fgauge[2], void *lgauge[2], fn_links_t *fn)
{
int i, dir, p;
site *s;
su3_matrix* t_fatlink = get_fatlinks(fn);
su3_matrix* t_lnglink = get_lnglinks(fn);
double t0 = __rdtsc();
msg_tag *ftag[4], *ltag[4], *tag;
su3_matrix *ftempmat = NULL, *ltempmat = NULL;
ind_t *arr = (ind_t *)malloc(8*sites_on_node*sizeof(ind_t));
ftempmat = (su3_matrix *)malloc(8*sites_on_node*sizeof(su3_matrix));
ltempmat = (su3_matrix *)malloc(8*sites_on_node*sizeof(su3_matrix));
/* gather backwards fatlinks */
for( dir=XUP; dir<=TUP; dir++){
ftag[dir] = start_gather_field( &t_fatlink[dir]
, 4*sizeof(su3_matrix)
, OPP_DIR(dir)
, EVENANDODD
, gen_pt[dir]
);
ltag[dir] = start_gather_field( &t_lnglink[dir]
, 4*sizeof(su3_matrix)
, OPP_3_DIR(DIR3(dir))
, EVENANDODD
, gen_pt[4+dir]
);
}
for( dir=XUP; dir<=TUP; dir++){
wait_gather( ftag[dir] );
wait_gather( ltag[dir] );
}
double t1 = __rdtsc();
node0_printf("BackLnkGather = %10.4g\n", t1-t0);
//for(p = 0; p < 2; p++)
{
// int parity = (p == 0 ? EVEN : ODD);
#pragma omp parallel for private(s) default(shared)
// FORSOMEPARITY(i,s,parity) {
for(i=0;i<sites_on_node;i++) {
site *s = &(lattice[i]);
su3_matrix *fat4, *lng4;
fat4 = &(t_fatlink[4*i]);
lng4 = &(t_lnglink[4*i]);
//int ii = (((s->t *nz+ s->z)*ny+s->y)*nx/2+s->x/2) + (parity == ODD ? even_sites_on_node : 0);
//if(ii != i) printf("YYY ii=%d not same as i=%d\n", ii, i);
/* plug the 4 su3_matrices in thee forward dirs into the qphix array */
for( int dir=XUP; dir <= TUP; dir++) {
ftempmat[8*i+MILC2MBENCH[OPP_DIR(dir)]] = *((su3_matrix*)gen_pt[dir][i]);
ftempmat[8*i+MILC2MBENCH[dir]] = fat4[dir];
ltempmat[8*i+MILC2MBENCH[OPP_DIR(dir)]] = *((su3_matrix*)gen_pt[4+dir][i]);
ltempmat[8*i+MILC2MBENCH[dir]] = lng4[dir];
}
}
}
for( dir=XUP; dir<=TUP; dir++){
cleanup_gather( ftag[dir] );
cleanup_gather( ltag[dir] );
}
double t2 = __rdtsc();
node0_printf("BackLnkCopy = %10.4g\n", t2-t1);
#if 1
setFullGauge18(fgauge[0], &ftempmat[0], even_sites_on_node*8);
setFullGauge18(fgauge[1], &ftempmat[even_sites_on_node*8], 8*even_sites_on_node);
setFullGauge (lgauge[0], <empmat[0], even_sites_on_node*8);
setFullGauge (lgauge[1], <empmat[even_sites_on_node*8], even_sites_on_node*8);
#endif
double t3 = __rdtsc();
node0_printf("BackLnkConv = %10.4g\n", t3-t2);
free(arr);
free(ftempmat);
free(ltempmat);
}
void
get_fatlinks_from_lattice (void* gauge18s, int parity, fn_links_t *fn)
{
int i;
site *s;
su3_matrix* t_fatlink = get_fatlinks(fn);
su3_matrix* t_fatback = load_fatbacklinks_without_adjoint(fn);
su3_matrix *fat4, *backfat4;
#if _OPENMP
#pragma omp parallel for private(s) default(shared)
#endif
FORSOMEPARITY(i,s,parity) {
fat4 = &(t_fatlink[4*i]);
backfat4 = &(t_fatback[4*i]);
/* plug the 4 su3_matrices in thee forward dirs into the qphix array */
for( int dir=XUP; dir <= TUP; dir++) {
setGauge18( gauge18s
, &fat4[dir]
, MILC2MBENCH[dir]
, s->x/2
, s->y
, s->z
, s->t
);
setGauge18( gauge18s
, &backfat4[dir]
, MILC2MBENCH[OPP_DIR(dir)]
, s->x/2
, s->y
, s->z
, s->t
);
}
}
free(t_fatback);
}
void
get_longlinks_from_lattice (void* gauges, int parity, fn_links_t *fn)
{
int i;
site *s;
su3_matrix* t_longlink = get_lnglinks(fn);
su3_matrix* t_longback = load_longbacklinks_without_adjoint(fn);
su3_matrix *lng4, *backlng4;
#if _OPENMP
#pragma omp parallel for private(s) default(shared)
#endif
FORSOMEPARITY(i,s,parity) {
lng4 = &(t_longlink[4*i]);
backlng4 = &(t_longback[4*i]);
for( int dir=XUP; dir <= TUP; dir++) {
setGauge( gauges
, &lng4[dir]
, MILC2MBENCH[dir]
, s->x/2
, s->y
, s->z
, s->t
);
setGauge( gauges
, &backlng4[dir]
, MILC2MBENCH[OPP_DIR(dir)]
, s->x/2
, s->y
, s->z
, s->t
);
}
}
free(t_longback);
}
/*!
* Get the su3_vectors from the site major lattice and convert them into an
* array of ks_spinors for qphix
*/
void
get_ks_spinors_from_lattice (su3_vector *ks, void* ks_spinor, int parity)
{
int i;
site *s;
#if _OPENMP
//#pragma omp parallel for private(s) default(shared)
#warning using omp
int loopend= (parity)==EVEN ? even_sites_on_node : sites_on_node ;
#pragma omp parallel for private(s) default(shared)
for( int i=((parity)==ODD ? even_sites_on_node : 0 ); i<loopend; i++){
s = &(lattice[i]);
#else
FORSOMEPARITY(i,s,parity) {
#endif
setKS( ks_spinor
, ks + i
, s->x/2, s->y, s->z, s->t
);
}
}
void
set_ks_spinors_into_lattice (su3_vector *ks, void* ks_spinor, int parity)
{
int i;
site *s;
#if 1
#if _OPENMP
#pragma omp parallel for private(s) default(shared)
#endif
FORSOMEPARITY(i,s,parity) {
// getKS(ks_spinor, (su3_vector *)F_PT(s, ks_off)
getKS(ks_spinor, ks + i
, s->x/2, s->y, s->z, s->t
);
}
#else
// Get the spinors into a separate array. We pass the whole array to mbench
// su3_vector *spinors = get_su3_vectors_from_lattice(ks_off);
su3_vector *spinors = ks;
#endif
}
#endif
|
GB_binop__bget_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_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__bget_uint8
// A.*B function (eWiseMult): GB_AemultB__bget_uint8
// A*D function (colscale): (none)
// D*A function (rowscale): (node)
// C+=B function (dense accum): GB_Cdense_accumB__bget_uint8
// C+=b function (dense accum): GB_Cdense_accumb__bget_uint8
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bget_uint8
// C=scalar+B GB_bind1st__bget_uint8
// C=scalar+B' GB_bind1st_tran__bget_uint8
// C=A+scalar GB_bind2nd__bget_uint8
// C=A'+scalar GB_bind2nd_tran__bget_uint8
// C type: uint8_t
// A type: uint8_t
// B,b type: uint8_t
// BinaryOp: cij = GB_BITGET (aij, bij, uint8_t, 8)
#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) \
uint8_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint8_t 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 = GB_BITGET (x, y, uint8_t, 8) ;
// 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_BGET || GxB_NO_UINT8 || GxB_NO_BGET_UINT8)
//------------------------------------------------------------------------------
// 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__bget_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__bget_uint8
(
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__bget_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
//------------------------------------------------------------------------------
#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
uint8_t *GB_RESTRICT Cx = (uint8_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
uint8_t *GB_RESTRICT Cx = (uint8_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__bget_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 *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__bget_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 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__bget_uint8
(
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
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 ;
uint8_t bij = Bx [p] ;
Cx [p] = GB_BITGET (x, bij, uint8_t, 8) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB_bind2nd__bget_uint8
(
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 ;
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 ;
uint8_t aij = Ax [p] ;
Cx [p] = GB_BITGET (aij, y, uint8_t, 8) ;
}
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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_BITGET (x, aij, uint8_t, 8) ; \
}
GrB_Info GB_bind1st_tran__bget_uint8
(
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 \
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
}
//------------------------------------------------------------------------------
// 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) \
{ \
uint8_t aij = Ax [pA] ; \
Cx [pC] = GB_BITGET (aij, y, uint8_t, 8) ; \
}
GrB_Info GB_bind2nd_tran__bget_uint8
(
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
uint8_t y = (*((const uint8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__identity_bool_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary 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_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_bool_fp32)
// op(A') function: GB (_unop_tran__identity_bool_fp32)
// C type: bool
// A type: float
// cast: bool cij = (aij != 0)
// unaryop: cij = aij
#define GB_ATYPE \
float
#define GB_CTYPE \
bool
// 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 ;
// casting
#define GB_CAST(z, aij) \
bool z = (aij != 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
bool z = (aij != 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_bool_fp32)
(
bool *Cx, // Cx and Ax may be aliased
const float *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++)
{
float aij = Ax [p] ;
bool z = (aij != 0) ;
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 ;
float aij = Ax [p] ;
bool z = (aij != 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_bool_fp32)
(
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
|
GB_unaryop__identity_int16_int64.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_int16_int64
// op(A') function: GB_tran__identity_int16_int64
// C type: int16_t
// A type: int64_t
// cast: int16_t cij = (int16_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int64_t
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int64_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) \
int16_t z = (int16_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_INT16 || GxB_NO_INT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_int16_int64
(
int16_t *restrict Cx,
const int64_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_int16_int64
(
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
|
test_master2.c | //===-- test_master2.cc - Test the "master" construct ------=------*- C -*-===//
//
// Part of the LOMP 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 has been modified from the file
// openmp/runtime/test/master/omp_master_3.c
// of the LLVM project (https://github.com/llvm/llvm-project)
// under the Apache License v2.0 with LLVM Exceptions.
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "tests.h"
int test_omp_master_3(void) {
int nthreads;
int executing_thread;
int tid_result = 0; /* counts up the number of wrong thread no. for
the master thread. (Must be 0) */
nthreads = 0;
executing_thread = -1;
#pragma omp parallel
{
#pragma omp master
{
int tid = omp_get_thread_num();
if (tid != 0) {
#pragma omp atomic
tid_result++;
}
#pragma omp atomic
nthreads++;
executing_thread = omp_get_thread_num();
} /* end of master*/
} /* end of parallel*/
return ((nthreads == 1) && (executing_thread == 0) && (tid_result == 0));
}
int main(void) {
int i;
int num_failed = 0;
for (i = 0; i < REPETITIONS; i++) {
if (!test_omp_master_3()) {
num_failed++;
}
}
return num_failed != 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
|
1500.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "atax.h"
/* Array initialization. */
static
void init_array (int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny))
{
int i, j;
for (i = 0; i < ny; i++)
x[i] = i * M_PI;
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
A[i][j] = ((DATA_TYPE) i*(j+1)) / nx;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int nx,
DATA_TYPE POLYBENCH_1D(y,NX,nx))
{
int i;
for (i = 0; i < nx; i++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]);
if (i % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_atax(int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny),
DATA_TYPE POLYBENCH_1D(y,NY,ny),
DATA_TYPE POLYBENCH_1D(tmp,NX,nx))
{
int i, j;
#pragma scop
{
#pragma omp parallel for simd schedule(static, 28)
for (i = 0; i < _PB_NY; i++)
{
y[i] = 0;
}
#pragma omp parallel for simd schedule(static, 28)
for (i = 0; i < _PB_NX; i++)
{
tmp[i] = 0;
for (j = 0; j < _PB_NY; j++)
tmp[i] = tmp[i] + A[i][j] * x[j];
for (j = 0; j < _PB_NY; j++)
y[j] = y[j] + A[i][j] * tmp[i];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int nx = NX;
int ny = NY;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny);
POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx);
/* Initialize array(s). */
init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_atax (nx, ny,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(x),
POLYBENCH_ARRAY(y),
POLYBENCH_ARRAY(tmp));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(nx, POLYBENCH_ARRAY(y)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(x);
POLYBENCH_FREE_ARRAY(y);
POLYBENCH_FREE_ARRAY(tmp);
return 0;
}
|
cholesky.c | /*****************************************************
* Site: https://rosettacode.org/wiki/Cholesky_decomposition
*****************************************************/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <omp.h>
#include <sys/time.h>
void cholesky(double** A, int n, int nt) {
#pragma omp parallel for num_threads(nt)
for (int i = 0; i < n; i++)
for (int j = 0; j < (i + 1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += A[i][k] * A[j][k];
A[i][j] = (i == j) ? sqrt(A[i][i] - s) : (1.0 / A[j][j] * (A[i][j] - s));
}
}
void show_matrix(double** A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i][j]);
printf("\n");
}
}
void mat_zero(double** x, int n) {
int i, j;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
x[i][j] = 0.0;
}
}
}
double** mat_new(int n) {
int i;
double** x = malloc(sizeof(double*) * n);
assert(x != NULL);
for(i = 0; i < n; i++){
x[i] = malloc(sizeof(double) * n);
assert(x[i] != NULL);
}
mat_zero(x,n);
return x;
}
void rand_fill(double** x, int n){
int i, j;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++){
x[i][j] = (i+1)*(j+1);
}
for(i = 0; i < n; i++)
x[i][i] *= 100;
}
void mat_gen(double** s, int n) {
int i,j;
for(i=0; i<n; i++) {
for(j=0; j<n; j++) {
scanf("%lf",&s[i][j]);
}
}
}
void mat_del(double** x) {
free(x[0]);
free(x);
}
double wtime()
{
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec + t.tv_usec / 1000000.0;
}
int main() {
int n;
int i, j, q_exec;
int l_threads[17] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17};
int n_threads = 17;
double matT[10], total, media, desviopadrao, somatorio, mul;
// testar com n = 5000
n = 2000;
//fscanf(stdin,"%d",&n);
printf("n_threads\tmedia\t\tdesvio\n");
for (j = 0; j < n_threads; j++){
total = 0;
somatorio = 0;
q_exec = 10;
printf("%i\t", l_threads[j]);
for (i = 0; i < q_exec; i++){
double start_time, end_time, final_time;
start_time = wtime();
double** A = mat_new(n);
rand_fill(A, n);
cholesky(A, n, l_threads[j]);
//show_matrix(A, n);
mat_del(A);
end_time = wtime();
final_time = ((double)(end_time - start_time));
matT[i] = final_time;
//printf("%i - Exec\tTime:%fs\n",i+1, matT[i]);
total += matT[i];
//printf("thread %i - exec %i - t %f\n",l_threads[j], i, matT[i]);
}
media = total/q_exec;
for (i=0; i<q_exec; i++){
mul = (matT[i] - media);
somatorio += pow(mul, 2);
}
somatorio = somatorio/q_exec;
desviopadrao = sqrt(somatorio);
printf("\t%f\t%f\n",media, desviopadrao);
}
return 0;
}
|
louvain_imm.h | //===------------------------------------------------------------*- C++ -*-===//
//
// Ripples: A C++ Library for Influence Maximization
// Marco Minutoli <marco.minutoli@pnnl.gov>
// Pacific Northwest National Laboratory
//
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2019, Battelle Memorial Institute
//
// Battelle Memorial Institute (hereinafter Battelle) hereby grants permission
// to any person or entity lawfully obtaining a copy of this software and
// associated documentation files (hereinafter “the Software”) to redistribute
// and use the Software in source and binary forms, with or without
// modification. Such person or entity may use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and may permit
// others to do so, subject to the following conditions:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// 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. Other than as used herein, neither the name Battelle Memorial Institute or
// Battelle may be used in any form whatsoever without the express written
// consent of Battelle.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL BATTELLE 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 RIPPLES_LOUVAIN_IMM_H
#define RIPPLES_LOUVAIN_IMM_H
#include <queue>
#include <string>
#include <type_traits>
#include <vector>
#include "ripples/find_most_influential.h"
#include "ripples/generate_rrr_sets.h"
#include "ripples/imm.h"
#include "ripples/imm_execution_record.h"
#include "spdlog/fmt/ostr.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
namespace ripples {
struct LouvainIMMConfiguration : public IMMConfiguration {
std::string communityList;
void addCmdOptions(CLI::App &app) {
IMMConfiguration::addCmdOptions(app);
app.add_option("--community-map", communityList,
"The filename of the community map.")
->required()
->group("Algorithm Options");
}
};
struct LouvainIMMExecutionRecord : public IMMExecutionRecord {};
namespace {
template <typename vertex_type>
struct Compare {
bool operator()(std::pair<vertex_type, size_t> &a,
std::pair<vertex_type, size_t> &b) const {
return a.second < b.second;
}
};
} // namespace
template <typename GraphTy, typename RRRset, typename execution_tag>
auto FindMostInfluentialSet(const std::vector<GraphTy> &communities, size_t k,
std::vector<std::vector<RRRset>> &RRRcollection,
execution_tag &&ex_tag) {
spdlog::get("console")->info("SeedSelect start");
using vertex_type = typename GraphTy::vertex_type;
Compare<vertex_type> cmp;
using priorityQueue =
std::priority_queue<std::pair<vertex_type, size_t>,
std::vector<std::pair<vertex_type, size_t>>,
decltype(cmp)>;
// Count occurrencies for all communities
std::vector<std::vector<uint32_t>> coverageVectors(communities.size());
std::vector<priorityQueue> queues(communities.size());
std::vector<typename std::vector<RRRset>::iterator> ends(communities.size());
double total_delta = 0;
#pragma omp parallel for reduction(+ : total_delta)
for (size_t i = 0; i < communities.size(); ++i) {
coverageVectors[i] = std::vector<uint32_t>(communities[i].num_nodes(), 0);
CountOccurrencies(RRRcollection[i].begin(), RRRcollection[i].end(),
coverageVectors[i].begin(), coverageVectors[i].end(),
std::forward<execution_tag>(ex_tag));
std::vector<std::pair<vertex_type, size_t>> queue_storage(
communities[i].num_nodes());
InitHeapStorage(coverageVectors[i].begin(), coverageVectors[i].end(),
queue_storage.begin(), queue_storage.end(),
std::forward<execution_tag>(ex_tag));
queues[i] = std::move(priorityQueue(cmp, std::move(queue_storage)));
ends[i] = RRRcollection[i].end();
total_delta += RRRcollection[i].size();
}
spdlog::get("console")->flush();
// Init on heap per community
using vertex_contribution_pair = std::pair<vertex_type, double>;
std::vector<vertex_contribution_pair> global_heap(
k + 1, vertex_contribution_pair{-1, -1.0});
std::vector<uint64_t> active_communities(communities.size(), 1);
auto heap_cmp = [](const vertex_contribution_pair &a,
const vertex_contribution_pair &b) -> bool {
return a.second > b.second;
};
std::make_heap(global_heap.begin(), global_heap.end(), heap_cmp);
// std::mutex global_heap_mutex;
// for each communities do in parallel
size_t iteration = 0;
while (!std::all_of(active_communities.begin(), active_communities.end(),
[](const uint64_t &v) -> bool { return v == 0; })) {
for (size_t i = 0; i < communities.size(); ++i) {
if (active_communities[i] == 0) continue;
if (queues[i].empty()) {
active_communities[i] = 0;
continue;
}
auto element = queues[i].top();
queues[i].pop();
while (element.second > coverageVectors[i][element.first]) {
element.second = coverageVectors[i][element.first];
queues[i].push(element);
element = queues[i].top();
queues[i].pop();
}
auto cmp = [=](const RRRset &a) -> auto {
return !std::binary_search(a.begin(), a.end(), element.first);
};
auto itr = partition(RRRcollection[i].begin(), ends[i], cmp,
std::forward<execution_tag>(ex_tag));
if (std::distance(itr, ends[i]) <
std::distance(RRRcollection[i].begin(), itr)) {
UpdateCounters(itr, ends[i], coverageVectors[i],
std::forward<execution_tag>(ex_tag));
} else {
if (std::is_same<execution_tag, omp_parallel_tag>::value) {
#pragma omp parallel for simd
for (size_t j = 0; j < coverageVectors[i].size(); ++j)
coverageVectors[i][j] = 0;
} else {
std::fill(coverageVectors[i].begin(), coverageVectors[i].end(), 0);
}
CountOccurrencies(RRRcollection[i].begin(), itr,
coverageVectors[i].begin(), coverageVectors[i].end(),
std::forward<execution_tag>(ex_tag));
}
ends[i] = itr;
double contribution = RRRcollection[i].size()
? element.second / RRRcollection[i].size()
: 0;
vertex_contribution_pair vcp{communities[i].convertID(element.first),
contribution};
// Handle the global index insertion
// std::lock_guard<std::mutex> _(global_heap_mutex);
std::pop_heap(global_heap.begin(), global_heap.end(), heap_cmp);
global_heap.back() = vcp;
std::push_heap(global_heap.begin(), global_heap.end(), heap_cmp);
if (global_heap.front() == vcp) active_communities[i] = 0;
}
}
std::pop_heap(global_heap.begin(), global_heap.end(), heap_cmp);
global_heap.pop_back();
double coverage = 0;
std::vector<typename GraphTy::vertex_type> seeds;
seeds.reserve(k);
for (auto e : global_heap) {
seeds.push_back(e.first);
coverage += e.second;
}
return seeds;
}
template <typename GraphTy, typename ConfTy, typename GeneratorTy,
typename RecordTy, typename diff_model_tag>
auto LouvainIMM(const std::vector<GraphTy> &communities, ConfTy &CFG, double l,
GeneratorTy &gen, std::vector<RecordTy> &records, diff_model_tag &&model_tag,
sequential_tag &&ex_tag) {
using vertex_type = typename GraphTy::vertex_type;
size_t k = CFG.k;
double epsilon = CFG.epsilon;
using RRRsetCollection = std::vector<RRRset<GraphTy>>;
std::vector<RRRsetCollection> R(communities.size());
// For each community do ThetaEstimation and Sampling
for (size_t i = 0; i < communities.size(); ++i) {
double l_1 = l * (1 + 1 / std::log2(communities[i].num_nodes()));
R[i] = Sampling(communities[i], CFG, l_1, gen, records[i],
std::forward<diff_model_tag>(model_tag),
std::forward<sequential_tag>(ex_tag));
}
// Global seed selection using the heap
auto S = FindMostInfluentialSet(communities, k, R,
std::forward<sequential_tag>(ex_tag));
return std::make_pair(S, records);
}
//! Influence Maximization using Community Structure.
//!
//! The algorithm uses the Louvain method for community detection and then
//! IMM to select seeds frome the communities.
//!
//! \tparam GraphTy The type of the input graph.
//! \tparam PRNG The type of the parallel random number generator.
//! \tparam diff_model_tag Type-Tag to selecte the diffusion model.
//! \tparam execution_tag Type-Tag to select the execution policy.
//!
//! \param communities The input graphs. The graphs are transoposed.
//! \param k The size of the seed set.
//! \param epsilon The parameter controlling the approximation guarantee.
//! \param l Parameter usually set to 1.
//! \param gen The parallel random number generator.
//! \param model_tag The diffusion model tag.
//! \param ex_tag The execution policy tag.
template <typename GraphTy, typename ConfTy, typename GeneratorTy,
typename diff_model_tag>
auto LouvainIMM(const std::vector<GraphTy> &communities, ConfTy &CFG, double l,
std::vector<GeneratorTy> &gen, diff_model_tag &&model_tag,
omp_parallel_tag &&ex_tag) {
using vertex_type = typename GraphTy::vertex_type;
size_t k = CFG.k;
double epsilon = CFG.epsilon;
using RRRsetCollection = std::vector<RRRset<GraphTy>>;
std::vector<RRRsetCollection> R(communities.size());
// For each community do ThetaEstimation and Sampling
for (size_t i = 0; i < communities.size(); ++i) {
double l_1 = l * (1 + 1 / std::log2(communities[i].num_nodes()));
R[i] = Sampling(communities[i], CFG, l_1, gen[i], gen[i].execution_record(),
std::forward<diff_model_tag>(model_tag),
std::forward<omp_parallel_tag>(ex_tag));
}
// Global seed selection using the heap
auto S = FindMostInfluentialSet(communities, k, R,
std::forward<omp_parallel_tag>(ex_tag));
std::vector<IMMExecutionRecord> records(communities.size());
for (auto & generator : gen) {
records.push_back(generator.execution_record());
}
return std::make_pair(S, records);
}
} // namespace ripples
#endif /* RIPPLES_LOUVAIN_IMM_H */
|
clansy.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zlansy.c, normal z -> c, Fri Sep 28 17:38:08 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
/***************************************************************************//**
*
* @ingroup plasma_lansy
*
* Returns the norm of a symmetric matrix as
*
* clansy = ( max(abs(A(i,j))), NORM = PlasmaMaxNorm
* (
* ( norm1(A), NORM = PlasmaOneNorm
* (
* ( normI(A), NORM = PlasmaInfNorm
* (
* ( normF(A), NORM = PlasmaFrobeniusNorm
*
* where norm1 denotes the one norm of a matrix (maximum column sum),
* normI denotes the infinity norm of a matrix (maximum row sum) and
* normF denotes the Frobenius norm of a matrix (square root of sum
* of squares). Note that max(abs(A(i,j))) is not a consistent matrix
* norm.
*
*******************************************************************************
*
* @param[in] norm
* - PlasmaMaxNorm: Max norm
* - PlasmaOneNorm: One norm
* - PlasmaInfNorm: Infinity norm
* - PlasmaFrobeniusNorm: Frobenius norm
*
* @param[in] uplo
* - PlasmaUpper: Upper triangle of A is stored;
* - PlasmaLower: Lower triangle of A is stored.
*
* @param[in] n
* The order of the matrix A. n >= 0.
*
* @param[in,out] A
* On entry, the symmetric matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A
* contains the upper triangular part of the matrix A, and the strictly
* lower triangular part of A is not referenced.
* If uplo = PlasmaLower, the leading N-by-N lower triangular part of A
* contains the lower triangular part of the matrix A, and the strictly
* upper triangular part of A is not referenced.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,m).
*
*******************************************************************************
*
* @retval float
* The specified norm of the symmetric matrix A.
*
*******************************************************************************
*
* @sa plasma_omp_clansy
* @sa plasma_clansy
* @sa plasma_slansy
* @sa plasma_slansy
*
******************************************************************************/
float plasma_clansy(plasma_enum_t norm, plasma_enum_t uplo,
int n,
plasma_complex32_t *pA, int lda)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) &&
(norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm) ) {
plasma_error("illegal value of norm");
return -1;
}
if ((uplo != PlasmaUpper) &&
(uplo != PlasmaLower)) {
plasma_error("illegal value of uplo");
return -2;
}
if (n < 0) {
plasma_error("illegal value of n");
return -3;
}
if (lda < imax(1, n)) {
plasma_error("illegal value of lda");
return -5;
}
// quick return
if (n == 0)
return 0.0;
// Tune parameters
if (plasma->tuning)
plasma_tune_lansy(plasma, PlasmaComplexFloat, n);
// Set tiling parameters.
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
int retval;
retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb,
n, n, 0, 0, n, n, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_desc_general_create() failed");
return retval;
}
// Allocate workspace.
float *work = NULL;
switch (norm) {
case PlasmaMaxNorm:
work = (float*)malloc((size_t)A.mt*A.nt*sizeof(float));
break;
case PlasmaOneNorm:
case PlasmaInfNorm:
work = (float*)malloc(((size_t)A.mt*A.n+A.n)*sizeof(float));
break;
case PlasmaFrobeniusNorm:
work = (float*)malloc((size_t)2*A.mt*A.nt*sizeof(float));
break;
}
if (work == NULL) {
plasma_error("malloc() failed");
return PlasmaErrorOutOfMemory;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
float value;
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_cge2desc(pA, lda, A, &sequence, &request);
// Call tile async function.
plasma_omp_clansy(norm, uplo, A, work, &value, &sequence, &request);
}
// implicit synchronization
free(work);
// Free matrix in tile layout.
plasma_desc_destroy(&A);
// Return the norm.
return value;
}
/***************************************************************************//**
*
* @ingroup plasma_lansy
*
* Calculates the max, one, infinity or Frobenius norm of a symmetric matrix.
* Non-blocking equivalent of plasma_clansy(). May return before the
* computation is finished. Operates on matrices stored by tiles. All matrices
* are passed through descriptors. All dimensions are taken from the
* descriptors. Allows for pipelining of operations at runtime.
*
*******************************************************************************
*
* @param[in] norm
* - PlasmaMaxNorm: Max norm
* - PlasmaOneNorm: One norm
* - PlasmaInfNorm: Infinity norm
* - PlasmaFrobeniusNorm: Frobenius norm
*
* @param[in] uplo
* - PlasmaUpper: Upper triangle of A is stored;
* - PlasmaLower: Lower triangle of A is stored.
*
* @param[in] A
* The descriptor of matrix A.
*
* @param[out] work
* Workspace of size:
* - PlasmaMaxNorm: A.mt*A.nt
* - PlasmaOneNorm: A.mt*A.n + A.n
* - PlasmaInfNorm: A.mt*A.n + A.n
* - PlasmaFrobeniusNorm: 2*A.mt*A.nt
*
* @param[out] value
* The calculated value of the norm requested.
*
* @param[in] sequence
* Identifies the sequence of function calls that this call belongs to
* (for completion checks and exception handling purposes).
*
* @param[out] request
* Identifies this function call (for exception handling purposes).
*
* @retval void
* Errors are returned by setting sequence->status and
* request->status to error values. The sequence->status and
* request->status should never be set to PlasmaSuccess (the
* initial values) since another async call may be setting a
* failure value at the same time.
*
*******************************************************************************
*
* @sa plasma_clansy
* @sa plasma_omp_clansy
* @sa plasma_omp_slansy
* @sa plasma_omp_slansy
*
******************************************************************************/
void plasma_omp_clansy(plasma_enum_t norm, plasma_enum_t uplo, plasma_desc_t A,
float *work, float *value,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// Check input arguments.
if ((norm != PlasmaMaxNorm) && (norm != PlasmaOneNorm) &&
(norm != PlasmaInfNorm) && (norm != PlasmaFrobeniusNorm)) {
plasma_error("illegal value of norm");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if ((uplo != PlasmaUpper) &&
(uplo != PlasmaLower)) {
plasma_error("illegal value of uplo");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid descriptor A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (A.m == 0) {
*value = 0.0;
return;
}
// Call the parallel function.
plasma_pclansy(norm, uplo, A, work, value, sequence, request);
}
|
ast-dump-openmp-target-simd.c | // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s
void test_one(int x) {
#pragma omp target simd
for (int i = 0; i < x; i++)
;
}
void test_two(int x, int y) {
#pragma omp target simd
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_three(int x, int y) {
#pragma omp target simd collapse(1)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_four(int x, int y) {
#pragma omp target simd collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
;
}
void test_five(int x, int y, int z) {
#pragma omp target simd collapse(2)
for (int i = 0; i < x; i++)
for (int i = 0; i < y; i++)
for (int i = 0; i < z; i++)
;
}
// CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc>
// CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-target-simd.c:3:1, line:7:1> line:3:6 test_one 'void (int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1>
// CHECK-NEXT: | `-OMPTargetSimdDirective {{.*}} <line:4:1, col:24>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:5:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:5:3, line:6:5>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:4:1) *const restrict'
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:4:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:5:23> col:23 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <col:3, line:6:5>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:4:1) *const restrict'
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1>
// CHECK-NEXT: | `-OMPTargetSimdDirective {{.*}} <line:10:1, col:24>
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:10:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:10:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:11:23> col:23 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:12:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:10:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1>
// CHECK-NEXT: | `-OMPTargetSimdDirective {{.*}} <line:17:1, col:36>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:25, col:35>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:34> 'int'
// CHECK-NEXT: | | |-value: Int 1
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:34> 'int' 1
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:17:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:17:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:18:23> col:23 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:19:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:17:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1>
// CHECK-NEXT: | `-OMPTargetSimdDirective {{.*}} <line:24:1, col:36>
// CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:25, col:35>
// CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:34> 'int'
// CHECK-NEXT: | | |-value: Int 2
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:34> 'int' 2
// CHECK-NEXT: | |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-CapturedStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:24:1) *const restrict'
// CHECK-NEXT: | | | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:24:1) *const restrict'
// CHECK-NEXT: | | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | | |-FieldDecl {{.*}} <line:25:23> col:23 implicit 'int'
// CHECK-NEXT: | | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | | `-FieldDecl {{.*}} <line:26:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7>
// CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19>
// CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | |-<<<NULL>>>
// CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7>
// CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:24:1) *const restrict'
// CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int'
// CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int'
// CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1>
// CHECK-NEXT: `-OMPTargetSimdDirective {{.*}} <line:31:1, col:36>
// CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:25, col:35>
// CHECK-NEXT: | `-ConstantExpr {{.*}} <col:34> 'int'
// CHECK-NEXT: | |-value: Int 2
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:34> 'int' 2
// CHECK-NEXT: |-OMPFirstprivateClause {{.*}} <<invalid sloc>> <implicit>
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-CapturedStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | | | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | | | |-<<<NULL>>>
// CHECK-NEXT: | | | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | | | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:31:1) *const restrict'
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | |-AlwaysInlineAttr {{.*}} <<invalid sloc>> Implicit __forceinline
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .part_id. 'const int *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .privates. 'void *const restrict'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .copy_fn. 'void (*const restrict)(void *const restrict, ...)'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .task_t. 'void *const'
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:31:1) *const restrict'
// CHECK-NEXT: | |-RecordDecl {{.*}} <col:1> col:1 implicit struct definition
// CHECK-NEXT: | | |-CapturedRecordAttr {{.*}} <<invalid sloc>> Implicit
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:32:23> col:23 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | |-FieldDecl {{.*}} <line:33:25> col:25 implicit 'int'
// CHECK-NEXT: | | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | | `-FieldDecl {{.*}} <line:34:27> col:27 implicit 'int'
// CHECK-NEXT: | | `-OMPCaptureKindAttr {{.*}} <<invalid sloc>> Implicit {{.*}}
// CHECK-NEXT: | `-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow
// CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9>
// CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21>
// CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: | | |-<<<NULL>>>
// CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<'
// CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue>
// CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue>
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
// CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++'
// CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int'
// CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9>
// CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (unnamed at {{.*}}ast-dump-openmp-target-simd.c:31:1) *const restrict'
// CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0
// CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit
// CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0
// CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit
// CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int'
// CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int'
// CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
|
degeneracy_approx_csr.h | #pragma once
#include "../general.h"
#include <cstdlib>
#include <omp.h>
#include <gms/third_party/fast_statistics.h>
#include <gms/third_party/fast_range.h>
#include "boundary_function.h"
namespace PpParallel
{
template <BoundaryFunction boundary, bool useRankFormat = false, class CGraph = CSRGraph, class Output = std::vector<NodeId>, class Set = RoaringSet>
void getDegeneracyOrderingApproxCGraph(const CGraph &graph, Output &res, double epsilon)
{
auto vSize = graph.num_nodes();
NodeId counter = 0;
res.resize(vSize); //Prepare Result
//Prepare Counter and Working Set
std::vector<int> degreeCounter(vSize);
NodeId *vArray = new NodeId[vSize];
#pragma omp parallel for schedule(static, 16)
for (int i = 0; i < vSize; i++) {
degreeCounter[i] = graph.out_degree(i);
vArray[i] = i;
}
NodeId *start_index = vArray;
NodeId *end_index = vArray + vSize;
while (counter < vSize) {
auto remaining = end_index - start_index;
unsigned int border = boundary(start_index, remaining, degreeCounter, epsilon);
#ifdef _OPENMP
auto middle_index = __gnu_parallel::partition(start_index, end_index,
[border, °reeCounter](const NodeId v) {
return degreeCounter[v] <= border;
});
#else
auto middle_index = std::partition(start_index, end_index,
[border, °reeCounter](const NodeId v) {
return degreeCounter[v] <= border;
});
#endif
auto mid = middle_index - start_index;
#ifdef _OPENMP
__gnu_parallel::sort(start_index, middle_index,
[°reeCounter](const NodeId v, const NodeId w) { return degreeCounter[v] < degreeCounter[w]; });
#else
std::sort(start_index, middle_index,
[°reeCounter](const NodeId v, const NodeId w) { return degreeCounter[v] < degreeCounter[w]; });
#endif
//Add to Result Set
//And reflect removing the vertices from the graph (PUSH style)
#pragma omp parallel for schedule(static, 16)
for (int i = 0; i < mid; i++) {
if constexpr (useRankFormat)
res[start_index[i]] = counter + i; //Result in Rank-Format
else
res[counter + i] = start_index[i]; //Result in Order-Format
auto v = start_index[i];
for (auto u : graph.out_neigh(v))
{
#pragma omp atomic
degreeCounter[u]--;
}
}
start_index = middle_index;
counter += mid;
}
delete[] vArray;
}
} // namespace PpParallel
|
ImageGraphUtils.h | #ifndef CAPTURE3_IMAGE_GRAPH_UTILS_H
#define CAPTURE3_IMAGE_GRAPH_UTILS_H
#include <cmath>
#include <vector>
#include <omp.h>
#include "BoundingBoxUtils.h"
#include "../engine/objects/image/ImageChannel.h"
#include "../engine/objects/image/ImageSize.h"
namespace Capture3
{
static void generateGraph(
const ImageSize &imageSize,
const ImageChannel &imageRGB,
const ImageChannel &imageHSB,
const ImageChannel &imageXYZ,
const ImageChannel &imageXYV,
const ImageChannel &imageLAB,
std::vector<float> &positionsRGB,
std::vector<float> &positionsHSB,
std::vector<float> &positionsXYZ,
std::vector<float> &positionsXYV,
std::vector<float> &positionsLAB,
std::vector<float> &colors,
unsigned int &countPoints,
unsigned int &countLines
)
{
// We want to sample a max of 250000 points
const unsigned int outputMax = 250000;
const unsigned int outputArea = imageSize.getArea();
const unsigned int outputSize = std::min(outputArea, outputMax);
const double outputScale = outputArea / (double) outputSize;
const unsigned int outputBytes = (outputSize + 24) * 3;
// Resize vectors to fit points and bounding box
positionsRGB.resize(outputBytes);
positionsHSB.resize(outputBytes);
positionsXYZ.resize(outputBytes);
positionsXYV.resize(outputBytes);
positionsLAB.resize(outputBytes);
colors.resize(outputBytes);
// Fetch data pointers
const double *dataRGB = imageRGB.getData();
const double *dataHSB = imageHSB.getData();
const double *dataXYZ = imageXYZ.getData();
const double *dataXYV = imageXYV.getData();
const double *dataLAB = imageLAB.getData();
#pragma omp parallel for schedule(static)
for (unsigned int i = 0; i < outputSize; i++) {
// Calculate indexes
const auto index = (unsigned int) lround(i * outputScale);
const unsigned int indexInput = index * 3;
const unsigned int indexOutput = i * 3;
// Colors
colors[indexOutput + 0] = (float) dataRGB[indexInput + 0];
colors[indexOutput + 1] = (float) dataRGB[indexInput + 1];
colors[indexOutput + 2] = (float) dataRGB[indexInput + 2];
// RGB
positionsRGB[indexOutput + 0] = (float) (dataRGB[indexInput + 1] - 0.5);
positionsRGB[indexOutput + 1] = (float) (dataRGB[indexInput + 2] - 0.5);
positionsRGB[indexOutput + 2] = (float) (dataRGB[indexInput + 0] - 0.5);
// HSB:
const double radians = dataHSB[indexInput + 0] * M_PI * 2.0;
const double radius = (dataHSB[indexInput + 1] * dataHSB[indexInput + 2]) / 2.0;
positionsHSB[indexOutput + 0] = (float) (radius * std::cos(radians));
positionsHSB[indexOutput + 1] = (float) (radius * std::sin(radians));
positionsHSB[indexOutput + 2] = (float) (dataHSB[indexInput + 2] - 0.5);
// XYZ:
positionsXYZ[indexOutput + 0] = (float) (dataXYZ[indexInput + 2] - 0.5);
positionsXYZ[indexOutput + 1] = (float) (dataXYZ[indexInput + 0] - 0.5);
positionsXYZ[indexOutput + 2] = (float) (dataXYZ[indexInput + 1] - 0.5);
// XYV:
positionsXYV[indexOutput + 0] = (float) (dataXYV[indexInput + 1] - 0.5);
positionsXYV[indexOutput + 1] = (float) (dataXYV[indexInput + 0] - 0.5);
positionsXYV[indexOutput + 2] = (float) (dataXYV[indexInput + 2] - 0.5);
// LAB:
positionsLAB[indexOutput + 0] = (float) (dataLAB[indexInput + 1] - 0.5);
positionsLAB[indexOutput + 1] = (float) (dataLAB[indexInput + 2] - 0.5);
positionsLAB[indexOutput + 2] = (float) (dataLAB[indexInput + 0] - 0.5);
}
// Add bounding box
boundingBox(
outputSize * 3,
positionsRGB,
positionsHSB,
positionsXYZ,
positionsXYV,
positionsLAB,
colors
);
// Store counts
countPoints = outputSize;
countLines = 24;
}
}
#endif // CAPTURE3_IMAGE_GRAPH_UTILS_H
|
parallelizer.h | // (C) Copyright Renaud Detry 2007-2015.
// Distributed under the GNU General Public License and under the
// BSD 3-Clause License (See accompanying file LICENSE.txt).
/** @file */
#ifndef NUKLEI_PARALLELIZER_H
#define NUKLEI_PARALLELIZER_H
#include <nuklei/Random.h>
#include <nuklei/Common.h>
#include <nuklei/BoostSerialization.h>
#include <nuklei/parallelizer_decl.h>
#include <cstdlib>
#include <boost/filesystem.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
namespace nuklei {
template<typename R, typename Callable, typename PrintAccessor>
std::vector<R> parallelizer::run_openmp(Callable callable,
PrintAccessor pa) const
{
std::vector<R> retv;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < n_; ++i)
{
R tmp = callable();
#ifdef _OPENMP
#pragma omp critical(nuklei_parallelizer_merge)
#endif
{
retv.push_back(tmp);
NUKLEI_INFO("Finished OpenMP thread " << i << " with value "
<< pa(tmp) << ".");
}
}
return retv;
}
template<typename R, typename Callable, typename PrintAccessor>
std::vector<R> parallelizer::run_fork(Callable callable,
PrintAccessor pa) const
{
boost::filesystem::path endpoint_name = boost::filesystem::unique_path("/tmp/nuklei-%%%%-%%%%-%%%%-%%%%");
//std::vector<pid_t> pids(n_, 0);
std::vector<R> retv;
for (int i = 0; i < n_; i++)
{
pid_t pid = fork();
NUKLEI_ASSERT(pid >= 0);
if (pid == 0)
{
Random::seed(seed_+i); // unsigned overflow wraps around.
using boost::asio::local::stream_protocol;
R tmp = callable();
{
stream_protocol::endpoint ep(endpoint_name.native());
stream_protocol::iostream stream(ep);
boost::archive::binary_oarchive oa(stream);
oa & i & BOOST_SERIALIZATION_NVP(tmp);
}
_exit(0);
}
else
{
//pids.at(i) = pid;
}
}
using boost::asio::local::stream_protocol;
stream_protocol::endpoint ep(endpoint_name.native());
boost::asio::io_service io_service;
stream_protocol::acceptor acceptor(io_service, ep);
for (int i = 0; i < n_; i++)
{
R tmp;
int fork_i = 0;
{
stream_protocol::iostream stream;
acceptor.accept(*stream.rdbuf());
boost::archive::binary_iarchive ia(stream);
ia & fork_i & BOOST_SERIALIZATION_NVP(tmp);
}
retv.push_back(tmp);
NUKLEI_INFO("Finished fork " << fork_i << " with value "
<< pa(tmp) << ".");
}
// clean up:
boost::filesystem::remove(endpoint_name);
reap();
return retv;
}
template<typename R, typename Callable, typename PrintAccessor>
std::vector<R> parallelizer::run_pthread(Callable callable,
PrintAccessor pa) const
{
std::vector<R> retv(n_);
std::vector< boost::shared_ptr<boost::thread> > threads;
for (int i = 0; i < n_; ++i)
{
// This does not work without the first boost::ref (even if bind<void>
// is used. The solution is to parametrize run_pthread_stub with
// boost::_bi::protected_bind_t<C>, and boost::protect(callable),
// but _bi is not public.
//boost::shared_ptr<boost::thread> thrd
//(new boost::thread(boost::bind(run_pthread_stub<R, Callable>,
// boost::ref(callable),
// boost::ref(retv.at(i)))));
// For future ref, here's the helper function:
//template<typename R, typename Callable>
//void run_pthread_stub(Callable callable, R& ret)
//{
// ret = callable();
//}
boost::shared_ptr<boost::thread> thread
(new boost::thread
(boost::bind<void>(pthread_wrapper<R, Callable>(callable),
boost::ref(retv.at(i)))));
threads.push_back(thread);
}
for (int i = 0; i < n_; ++i)
{
threads.at(i)->join();
NUKLEI_INFO("Finished thread " << i << " with value "
<< pa(retv.at(i)) << ".");
}
return retv;
}
template<typename R, typename Callable, typename PrintAccessor>
std::vector<R> parallelizer::run_single(Callable callable,
PrintAccessor pa) const
{
std::vector<R> retv;
for (int i = 0; i < n_; ++i)
{
R tmp = callable();
retv.push_back(tmp);
NUKLEI_INFO("Finished slice " << i << " with value "
<< pa(tmp) << ".");
}
return retv;
}
}
#endif
|
matmul_tiled.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>
#include <float.h>
#include <omp.h>
#ifdef DP
#define REAL double
#else
#define REAL float
#endif
//int NB= BSIZE;
int BSIZE;
#define HACKFOR 128
#define max(a,b)( ((a) > (b)) ? (a) : (b) )
double cclock_( void ) {
const double micro = 1.0e-06; /* Conversion constant */
static long start = 0L, startu;
struct timeval tp; /* Structure used by gettimeofday */
double wall_time; /* To hold the result */
if ( gettimeofday( &tp, NULL) == -1 )
wall_time = -1.0e0;
else if( !start ) {
start = tp.tv_sec;
startu = tp.tv_usec;
wall_time = 0.0e0;
}
else
wall_time = (double) (tp.tv_sec - start) + micro*(tp.tv_usec - startu);
return wall_time;
}
double cclock( void ) {
return cclock_();
}
void prtspeed( int m, int l, int n, int nb, double time, int ok, unsigned long nops ) {
double speed = 1.0e-9*nops/time;
printf("%dx%d,%dx%d,%.4lf,%.4lf\n",m,n,nb,nb,speed,time);
printf("Matrix size: %dx%d\n", m, n);
printf("Block size: %dx%d\n", nb, nb);
#ifdef DP
printf("Precision type: Double\n");
#else
printf("Precision type: Simple\n");
#endif
printf(" GFLOPS : %.4lf\n", speed);
printf(" computation time (in seconds): %.4lf\n", time);
if ( ok == 0 ) {
printf(" Verification: Ok\n");
} else {
printf(" Verification: Failed (%d)\n", ok);
}
}
int check( int nrep, int m, int l, int n, int mDIM, int nDIM, REAL **c/*[][nDIM*BSIZE] */) {
double eps, tvalue = (double)l;
int i, j, k, o, ok = 0;
eps = 2.0*l*l*DBL_EPSILON;
int perfectM = m / BSIZE;
int perfectN = n / BSIZE;
int leftOutM = m % BSIZE;
int leftOutN = n % BSIZE;
for(i=0;i<mDIM;i++){
for(j=0;j<nDIM;j++){
for(k=0;k<BSIZE;k++){
for(o=0;o<BSIZE;o++){
if( i == mDIM-1 && mDIM > perfectM && k >= leftOutM )
break;
else if( j == nDIM-1 && nDIM > perfectN && o >= leftOutN )
break;
else {
if ( fabs( tvalue - (c[i*nDIM+j][k*BSIZE+o]/nrep) ) > eps ) {
ok++;
//printf("Bad result at [%d][%d] : expected %f but found %f\n", i*nDIM+j, k*BSIZE+o, tvalue, c[i*nDIM+j][k*BSIZE+o]);
}
}
}
}
}
}
return( ok );
}
void gendat(int mDIM, int lDIM, int nDIM, int m, int l, int n, REAL **tileA, REAL **tileB, REAL **tileC) {
int i,j,k,y;
REAL currentValue;
int perfectM = m / BSIZE;
int perfectL = l / BSIZE;
int perfectN = n / BSIZE;
int leftOutM = m % BSIZE;
int leftOutL = l % BSIZE;
int leftOutN = n % BSIZE;
for( i = 0; i < mDIM; ++i )
for( j = 0; j < lDIM; ++j )
for( k = 0; k < BSIZE; ++k )
{
currentValue = j*BSIZE;
for( y = 0; y < BSIZE; ++y )
{
if( i == mDIM-1 && mDIM > perfectM && k >= leftOutM )
tileA[ i*lDIM + j ][ k*BSIZE+y ] = 0.0;
else if( j == lDIM-1 && lDIM > perfectL && y >= leftOutL )
tileA[ i*lDIM + j ][ k*BSIZE+y ] = 0.0;
else
tileA[ i*lDIM + j ][ k*BSIZE+y ] = ++currentValue;
}
}
for( i = 0; i < lDIM; ++i )
for( j = 0; j < nDIM; ++j )
{
currentValue = (i*BSIZE) + 1;
for( k = 0; k < BSIZE; ++k, currentValue += 1)
for( y = 0; y < BSIZE; ++y )
{
if( i == lDIM-1 && lDIM > perfectL && k >= leftOutL )
tileB[ i*nDIM + j ][ k*BSIZE+y ] = 0.0;
else if( j == nDIM-1 && nDIM > perfectN && y >= leftOutN )
tileB[ i*nDIM + j ][ k*BSIZE+y ] = 0.0;
else
tileB[ i*nDIM + j ][ k*BSIZE+y ] = 1.0 / currentValue;
}
}
for( i = 0; i < lDIM; ++i ) {
for( j = 0; j < nDIM; ++j ) {
tileC[i][j] = 0.0;
}
}
}
void matmul_tile(REAL *__restrict A, REAL *__restrict B, REAL *__restrict C, int NB) {
int nb = BSIZE;
int i, j, k;
//int asd[4];
//int numa_nodes;
int chunk = NB / omp_get_num_threads();
#pragma omp target map(tofrom: C[0:NB*NB]) map(to: A[0:NB*NB], B[0:NB*NB])
#pragma omp parallel for private(i,j,k)
for (i = 0; i < NB; i++) {
int g = chunk;
#pragma omp parallel for
for (j = 0; j < NB; j++) {
REAL sum = C[i * NB + j];
#pragma omp simd reduction(+:sum)
for (k = 0; k < NB; k++) {
sum += (A[i * NB + k] * B[k * NB + j]);
}
C[i * NB + j] = sum;
}
}
}
void matmul(int m, int l, int n, int mDIM, int lDIM, int nDIM, REAL **tileA, REAL **tileB, REAL **tileC) {
int i, j, k;
printf("==> %d %d %d \n", nDIM, mDIM, lDIM);
for (i = 0; i < mDIM; i++) {
for (j = 0; j < nDIM; j++) {
for (k = 0; k < lDIM; k++) {
matmul_tile(tileA[i * lDIM + k], tileB[k * nDIM + j], tileC[i * nDIM + j], BSIZE);
}
}
}
}
int calcdim(int x) {
int dimval;
if(x%BSIZE != 0)
dimval = x/BSIZE + 1;
else
dimval = x/BSIZE;
return dimval;
}
int main(int argc, char* argv[]) {
int lda, m, l, n;
int mDIM, lDIM, nDIM;
int ok, nrep;
unsigned long nops;
int i,k,j,o;
REAL **a, **b, **c;
double time;
FILE *inl;
if (2 > argc)
BSIZE = HACKFOR;
else
BSIZE = atoi(argv[1]);
inl = fopen( "test.in", "r" );
if (inl == 0) {
printf("No input file 'test.in' found.\n");
exit(1);
}
while( ( fscanf( inl, "%d%d%d%d\n", &m, &l, &n, &nrep ) != EOF ) ){
lda = l + 1;
mDIM = calcdim(m);
lDIM = calcdim(l);
nDIM = calcdim(n);
posix_memalign((REAL **)&a, getpagesize(), mDIM * lDIM * sizeof( REAL *));
posix_memalign((REAL **)&b, getpagesize(), lDIM * nDIM * sizeof( REAL *));
posix_memalign((REAL **)&c, getpagesize(), mDIM * nDIM * sizeof( REAL *));
for (i = 0; i < mDIM * lDIM; i++)
posix_memalign((REAL **)&a[i],getpagesize(),BSIZE * BSIZE * sizeof(REAL) );
for (i = 0; i < lDIM * nDIM; i++)
posix_memalign((REAL **)&b[i],getpagesize(),BSIZE * BSIZE * sizeof(REAL) );
for (i = 0; i < mDIM * nDIM; i++)
posix_memalign((REAL **)&c[i],getpagesize(),BSIZE * BSIZE * sizeof(REAL) );
#pragma omp register([mDIM*lDIM]a)
#pragma omp register([lDIM*nDIM]b)
#pragma omp register([mDIM*nDIM]c)
gendat( mDIM, lDIM, nDIM, m, l, n, a, b, c );
printf("multiply start\n");
time = cclock();
for( i = 0; i < nrep; i++ ){
matmul( m, l, n, mDIM, lDIM, nDIM, a, b, c );
// #pragma omp taskwait// noflush
}
#pragma omp taskwait
time = cclock() - time;
printf("multiply done\n");
ok = check( nrep, m, l, n, mDIM, nDIM, c);
time = time/nrep;
nops = (unsigned long) 2*m*l*n;
prtspeed( m, l, n, BSIZE, time, ok, nops );
for(i=0;i<mDIM*lDIM;i++)
free( a[i] );
for(i=0;i<lDIM*nDIM;i++)
free( b[i] );
for(i=0;i<mDIM*nDIM;i++)
free( c[i] );
free( a ); free( b ); free( c );
}
return 0;
}
|
stencil2d_mdev.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>
#include "homp.h"
#include "stencil2d.h"
void stencil2d_omp_mdev_launcher(omp_offloading_t * off, void *args) {
struct stencil2d_off_args * iargs = (struct stencil2d_off_args*) args;
long n = iargs->n;
long m = iargs->m;
int radius = iargs->radius;
int num_its = iargs->num_its;
long u_dimX = iargs->u_dimX;
long u_dimY = iargs->u_dimY;
int coeff_dimX = iargs->coeff_dimX;
omp_data_map_t * map_u = omp_map_get_map(off, iargs->u, -1); /* 1 is for the map u */
omp_data_map_t * map_uold = omp_map_get_map(off, iargs->uold, -1); /* 2 is for the map uld */
omp_data_map_t * map_coeff = omp_map_get_map(off, iargs->coeff, -1); /* 2 is for the map uld */
REAL * u = (REAL*) map_u->map_dev_wextra_ptr;
REAL * uold = (REAL*) map_uold->map_dev_wextra_ptr;
REAL *coeff = (REAL*) map_coeff->map_dev_wextra_ptr;
coeff = coeff + (2*radius+1) * radius + radius; /* TODO this should be a call to map a host-side address to dev-side address*/
long it; /* iteration */
#if CORRECTNESS_CHECK
printf("kernel launcher: u: %X, uold: %X\n", u, uold);
print_array("u in device: ", "udev", u, n, m);
print_array("uold in device: ", "uolddev", uold, n, m);
#endif
long offset;
long start;
long len;
offset = omp_loop_get_range(off, 0, &start, &len);
#if 0
/* col-wise dist */
omp_loop_get_range(off, 0, &start, &len);
/* row/col-wise dist */
omp_loop_get_range(off, 0, &start, &len); /* todo */
omp_loop_get_range(off, 0, &start, &len); /* todo */
#endif
omp_device_type_t devtype = off->dev->type;
//printf("dev: %d, offset: %d, length: %d, local start: %d, u: %X, uold: %X, coeff-center: %X\n", off->devseqid, offset, len, start, u, uold, coeff);
//#pragma omp parallel shared(n, m, radius, coeff, num_its, u_dimX, u_dimY, coeff_dimX) private(it) firstprivate(u, uold)
if (devtype == OMP_DEVICE_NVGPU) {
#if defined (DEVICE_NVGPU_CUDA_SUPPORT)
stencil2d_nvgpu_cuda_wrapper(off, start, len, n, m, u_dimX, u_dimY, u, uold, radius, coeff_dimX, coeff);
#endif
} else if (devtype == OMP_DEVICE_ITLMIC) {
#if defined(DEVICE_ITLMIC_SUPPORT)
stencil2d_itlmic_wrapper(off, start, len, n, m, u_dimX, u_dimY, u, uold, radius, coeff_dimX, coeff);
#endif
} else if (devtype == OMP_DEVICE_THSIM || devtype == OMP_DEVICE_HOSTCPU) {
stencil2d_cpu_omp_wrapper(off, start, len, n, m, u_dimX, u_dimY, u, uold, radius, coeff_dimX, coeff);
} else {
fprintf(stderr, "device type is not supported for this call\n");
abort();
}
/*
pthread_barrier_wait(&off->off_info->inter_dev_barrier);
omp_halo_region_pull(map_u, 0, OMP_DATA_MAP_EXCHANGE_FROM_LEFT_RIGHT);
*/
}
double stencil2d_omp_mdev(int ndevs, int *targets, long n, long m, REAL *u, int radius, REAL *coeff, int num_its) {
long u_dimX = n + 2 * radius;
long u_dimY = m + 2 * radius;
int coeff_dimX = 2*radius+1;
REAL * coeff_center = coeff + (2*radius+1) * radius + radius; /* let coeff point to the center element */
REAL *uold = (REAL *) omp_unified_malloc(sizeof(REAL) * u_dimX * u_dimY);
memcpy(uold, u, sizeof(REAL)*u_dimX * u_dimY);
//print_array("Before offloading", "u", u, u_dimX, u_dimY);
double off_init_time = read_timer_ms();
/**************************************** dist-specific *****************************************/
int __top_ndims__ = 1;
/* TODO: to use row/col-wise dist, __top_ndims__ should be set to 2 */
omp_grid_topology_t * __top__ = omp_grid_topology_init(ndevs, targets, __top_ndims__);
/* init other infos (dims, periodic, idmaps) of top if needed */
int __num_maps__ = 3; /* u, uold and the coeff */ /* XXX: need compiler output */
/* data copy offloading */
omp_offloading_info_t *__copy_data_off_info__ =
omp_offloading_init_info("data_copy", __top__, 1, OMP_OFFLOADING_DATA, __num_maps__, NULL, NULL, 0);
/* stencil kernel offloading */
struct stencil2d_off_args off_args;
off_args.n = n; off_args.m = m; off_args.u = u; off_args.radius = radius; off_args.coeff = coeff; off_args.num_its = num_its;
off_args.uold = uold; off_args.coeff_center = coeff_center; off_args.coeff_dimX = coeff_dimX; off_args.u_dimX = u_dimX; off_args.u_dimY = u_dimY;
omp_offloading_info_t * __off_info__ =
omp_offloading_init_info("stencil2d_kernel", __top__, 1, OMP_OFFLOADING_CODE, 0,
stencil2d_omp_mdev_launcher, &off_args, 1);
omp_offloading_append_profile_per_iteration(__off_info__, 13*u_dimY, 7, 1);
//printf("data copy off: %X, stencil2d off: %X\n", __copy_data_off_info__, __off_info__);
/* u map info */
omp_data_map_info_t *__u_map_info__ = &__copy_data_off_info__->data_map_info[0];
omp_data_map_init_info("u", __u_map_info__, __copy_data_off_info__, u, 2, sizeof(REAL), OMP_DATA_MAP_TOFROM, OMP_DATA_MAP_AUTO);
omp_data_map_info_set_dims_2d(__u_map_info__, u_dimX, u_dimY);
/* uold map info */
omp_data_map_info_t *__uold_map_info__ = &__copy_data_off_info__->data_map_info[1];
omp_data_map_init_info("uold", __uold_map_info__, __copy_data_off_info__, uold, 2, sizeof(REAL), OMP_DATA_MAP_TO, OMP_DATA_MAP_AUTO);
omp_data_map_info_set_dims_2d(__uold_map_info__, u_dimX, u_dimY);
/* coeff map info */
omp_data_map_info_t *__coeff_map_info__ = &__copy_data_off_info__->data_map_info[2];
omp_data_map_init_info("coeff", __coeff_map_info__, __copy_data_off_info__, coeff, 2, sizeof(REAL), OMP_DATA_MAP_TO, OMP_DATA_MAP_AUTO);
omp_data_map_info_set_dims_2d(__coeff_map_info__, coeff_dimX, coeff_dimX);
omp_data_map_dist_init_info(__coeff_map_info__, 0, OMP_DIST_POLICY_FULL, 0, coeff_dimX, 0, 0);
omp_data_map_dist_init_info(__coeff_map_info__, 1, OMP_DIST_POLICY_FULL, 0, coeff_dimX, 0, 0);
/**************************************** dist-specific *****************************************/
/* row-wise distribution */
#if 0
/* BLOCK_BLOCK */
omp_data_map_dist_init_info(__u_map_info__, 0, OMP_DIST_POLICY_BLOCK, radius, n, 0, 0);
omp_loop_dist_init_info(__off_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0);
//printf("BLOCK dist policy for arrays and loop dist\n");
/* BLOCK_ALIGN */
omp_data_map_dist_init_info(__u_map_info__, 0, OMP_DIST_POLICY_BLOCK, radius, n, 0, 0);
omp_loop_dist_align_with_data_map(__off_info__, 0, 0, __u_map_info__, 0);
//printf("BLOCK dist policy for arrays, and loop dist align with array A row dist\n");
#endif
/* AUTO_ALIGN */
omp_loop_dist_init_info(__off_info__, 0, LOOP_DIST_POLICY, 0, n, LOOP_DIST_CHUNK_SIZE, 0);
omp_data_map_dist_align_with_loop(__u_map_info__, 0, radius, __off_info__, 0);
//printf("AUTO dist policy for loop dist and array align with loops\n");
/* used by all row-wise dist */
omp_data_map_dist_init_info(__u_map_info__, 1, OMP_DIST_POLICY_FULL, 0, u_dimY, 0, 0);
omp_map_add_halo_region(__u_map_info__, 0, radius, radius, OMP_DIST_HALO_EDGING_REFLECTING);
omp_data_map_dist_align_with_data_map_with_halo(__uold_map_info__, OMP_ALL_DIMENSIONS, OMP_ALIGNEE_OFFSET, __u_map_info__, OMP_ALL_DIMENSIONS);
#if 0
/* col-wise distribution */
omp_data_map_dist_init_info(__u_map_info__, 0, OMP_DIST_POLICY_FULL, radius, n, 0, 0);
omp_data_map_dist_init_info(__u_map_info__, 1, OMP_DIST_POLICY_BLOCK, radius, n, 0, 0);
omp_map_add_halo_region(__u_map_info__, 0, radius, radius, OMP_DIST_HALO_EDGING_REFLECTING);
omp_data_map_dist_align_with_data_map_with_halo(__uold_map_info__, OMP_ALL_DIMENSIONS, 0, __u_map_info__, OMP_ALL_DIMENSIONS);
omp_loop_dist_init_info(__off_info__, 1, OMP_DIST_POLICY_BLOCK, 0, m, 0, 0);
/* row/col-wise distribution */
omp_data_map_dist_init_info(__u_map_info__, 0, OMP_DIST_POLICY_BLOCK, radius, n, 0, 0);
omp_data_map_dist_init_info(__u_map_info__, 1, OMP_DIST_POLICY_BLOCK, radius, n, 0, 1);
omp_map_add_halo_region(__u_map_info__, 0, radius, radius, OMP_DIST_HALO_EDGING_REFLECTING);
omp_map_add_halo_region(__u_map_info__, 1, radius, radius, OMP_DIST_HALO_EDGING_REFLECTING);
omp_data_map_dist_align_with_data_map_with_halo(__uold_map_info__, OMP_ALL_DIMENSIONS, 0, __u_map_info__, OMP_ALL_DIMENSIONS);
omp_loop_dist_init_info(__off_info__, 0, OMP_DIST_POLICY_BLOCK, 0, n, 0, 0);
omp_loop_dist_init_info(__off_info__, 1, OMP_DIST_POLICY_BLOCK, 0, m, 0, 1);
#endif
/* halo exchange offloading */
omp_data_map_halo_exchange_info_t x_halos[1];
x_halos[0].map_info = __u_map_info__; x_halos[0].x_direction = OMP_DATA_MAP_EXCHANGE_FROM_LEFT_RIGHT; /* u and uold*/
/* row-wise dist */
x_halos[0].x_dim = 0;
#if 0
/* col-wise dist */
x_halos[0].x_dim = 1;
/* row/col-wise dist */
x_halos[0].x_dim = -1; /* means all the dimension */
#endif
//#define STANDALONE_DATA_X 1
#if !defined (STANDALONE_DATA_X)
/* there are two approaches we handle halo exchange, appended data exchange or standalone one */
/* option 1: appended data exchange */
omp_offloading_append_data_exchange_info(__off_info__, x_halos, 1);
#else
/* option 2: standalone offloading */
omp_offloading_info_t * uuold_halo_x_off_info = omp_offloading_standalone_data_exchange_init_info("u-uold halo exchange", __top__,1, x_halos, 1);
#endif
/************************************************************************************************/
off_init_time = read_timer_ms() - off_init_time;
/*********** NOW notifying helper thread to work on this offload ******************/
#if DEBUG_MSG
printf("=========================================== offloading to %d targets ==========================================\n", __num_target_devices__);
#endif
double off_copyto_time = read_timer_ms();
double start_time = off_copyto_time;
omp_offloading_start(__copy_data_off_info__);
omp_print_map_info(__u_map_info__);
omp_print_map_info(__uold_map_info__);
omp_print_map_info(__coeff_map_info__);
off_copyto_time = read_timer_ms() - off_copyto_time;
// printf("offloading from stencil now\n");
double off_kernel_time = read_timer_ms();
int itrun;
int num_runs = 10;
for (itrun =0; itrun < num_runs; itrun++) {
int it;
for (it = 0; it < num_its; it++) {
if (it%2==0) {
x_halos[0].map_info = __u_map_info__;
off_args.u = u;
off_args.uold = uold;
} else {
x_halos[0].map_info = __uold_map_info__;
off_args.u = uold;
off_args.uold = u;
}
omp_offloading_start(__off_info__);
//omp_offloading_start(__off_info__, itrun == num_runs - 1 && it == num_its);
#if defined STANDALONE_DATA_X
omp_offloading_start(uuold_halo_x_off_info, itrun == num_runs - 1);
#endif
}
}
off_kernel_time = (read_timer_ms() - off_kernel_time)/ num_runs;
/* copy back u from each device and free others */
double off_copyfrom_time = read_timer_ms();
omp_offloading_start(__copy_data_off_info__);
off_copyfrom_time = read_timer_ms() - off_copyfrom_time;
double off_total = off_init_time + off_copyto_time + off_copyfrom_time + off_kernel_time;
printf("blackbox measurement(ms): off_init: %0.4f, off_copyto: %.4f, off_kernel: %.4f, off_copyfrom: %.4f\n",
off_init_time, off_copyto_time, off_kernel_time, off_copyfrom_time);
#if defined (OMP_BREAKDOWN_TIMING)
//omp_offloading_info_report_profile(__copy_data_off_info__, 1);
omp_offloading_info_report_profile(__off_info__, num_runs);
int num_offs = 2;
#if defined STANDALONE_DATA_X
omp_offloading_info_report_profile(uuold_halo_x_off_info);
num_offs = 3;
#endif
omp_offloading_info_t *infos[num_offs];
infos[0] = __copy_data_off_info__;
infos[1] = __off_info__;
#if defined STANDALONE_DATA_X
infos[2] = uuold_halo_x_off_info;
#endif
//omp_offloading_info_sum_profile(infos, num_offs, start_time, start_time+off_total);
//omp_offloading_info_report_profile(__copy_data_off_info__, num_runs);
#endif
omp_offloading_fini_info(__copy_data_off_info__);
omp_offloading_fini_info(__off_info__);
#if defined STANDALONE_DATA_X
omp_offloading_fini_info(uuold_halo_x_off_info);
#endif
omp_grid_topology_fini(__top__);
omp_unified_free(uold);
return off_total;
}
|
12_omp_correlate.c | // clang-format off
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -S 2>&1 | FileCheck %s --check-prefix=CHECK-opt
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -call-filter-impl=cg -call-filter-cg-file=%p/05_cg.ipcg -S 2>&1 | FileCheck %s --check-prefix=CHECK-exp-cg
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | %apply-typeart -typeart-alloca -call-filter -S | FileCheck %s --check-prefix=check-inst
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -S | FileCheck %s --check-prefix=check-inst
// RUN: %c-to-llvm -fno-discard-value-names %omp_c_flags %s | opt -O2 -S | %apply-typeart -typeart-alloca -call-filter -call-filter-impl=cg -call-filter-cg-file=%p/05_cg.ipcg -S | FileCheck %s --check-prefix=check-inst
// REQUIRES: openmp
// clang-format on
#include "omp.h"
extern void MPI_Mock(int, int, int);
extern void MPI_Send(void*, int);
void foo() {
int a = 0;
int b = 1;
int c = 2;
// check-inst: define {{.*}} @foo
// check-inst: %d = alloca
// check-inst: %0 = bitcast i32* %d to i8*
// check-inst: call void @__typeart_alloc_stack(i8* %0, i32 2, i64 1)
// check-inst-not: __typeart_alloc_stack_omp
int d = 3;
int e = 4;
#pragma omp parallel
{
// no (void*), so we assume benign (with deep analysis)
MPI_Mock(a, b, c);
// Analysis should not filter d, but e...
MPI_Send((void*)d, e);
}
}
// Standard filter
// CHECK: > Stack Memory
// CHECK-NEXT: Alloca : 12.00
// CHECK-NEXT: Stack call filtered % : 91.67
// with opt only "d" in foo is tracked
// CHECK-opt: > Stack Memory
// CHECK-opt-NEXT: Alloca : 5.00
// CHECK-opt-NEXT: Stack call filtered % : 80.00
// CG experimental filter
// CHECK-exp-cg: > Stack Memory
// CHECK-exp-cg-NEXT: Alloca : 5.00
// CHECK-exp-cg-NEXT: Stack call filtered % : 80.00 |
schur_eliminator_impl.h | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
//
// TODO(sameeragarwal): row_block_counter can perhaps be replaced by
// Chunk::start ?
#ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
#define CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
// Eigen has an internal threshold switching between different matrix
// multiplication algorithms. In particular for matrices larger than
// EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD it uses a cache friendly
// matrix matrix product algorithm that has a higher setup cost. For
// matrix sizes close to this threshold, especially when the matrices
// are thin and long, the default choice may not be optimal. This is
// the case for us, as the default choice causes a 30% performance
// regression when we moved from Eigen2 to Eigen3.
#define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10
// This include must come before any #ifndef check on Ceres compile options.
#include "ceres/internal/port.h"
#include <algorithm>
#include <map>
#include "ceres/block_random_access_matrix.h"
#include "ceres/block_sparse_matrix.h"
#include "ceres/block_structure.h"
#include "ceres/internal/eigen.h"
#include "ceres/internal/fixed_array.h"
#include "ceres/internal/scoped_ptr.h"
#include "ceres/invert_psd_matrix.h"
#include "ceres/map_util.h"
#include "ceres/schur_eliminator.h"
#include "ceres/scoped_thread_token.h"
#include "ceres/small_blas.h"
#include "ceres/stl_util.h"
#include "ceres/thread_token_provider.h"
#include "Eigen/Dense"
#include "glog/logging.h"
#if defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
#include "ceres/parallel_for.h"
#endif
namespace ceres {
namespace internal {
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::~SchurEliminator() {
STLDeleteElements(&rhs_locks_);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::Init(
int num_eliminate_blocks,
bool assume_full_rank_ete,
const CompressedRowBlockStructure* bs) {
CHECK_GT(num_eliminate_blocks, 0)
<< "SchurComplementSolver cannot be initialized with "
<< "num_eliminate_blocks = 0.";
num_eliminate_blocks_ = num_eliminate_blocks;
assume_full_rank_ete_ = assume_full_rank_ete;
const int num_col_blocks = bs->cols.size();
const int num_row_blocks = bs->rows.size();
buffer_size_ = 1;
chunks_.clear();
lhs_row_layout_.clear();
int lhs_num_rows = 0;
// Add a map object for each block in the reduced linear system
// and build the row/column block structure of the reduced linear
// system.
lhs_row_layout_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
lhs_row_layout_[i - num_eliminate_blocks_] = lhs_num_rows;
lhs_num_rows += bs->cols[i].size;
}
int r = 0;
// Iterate over the row blocks of A, and detect the chunks. The
// matrix should already have been ordered so that all rows
// containing the same y block are vertically contiguous. Along
// the way also compute the amount of space each chunk will need
// to perform the elimination.
while (r < num_row_blocks) {
const int chunk_block_id = bs->rows[r].cells.front().block_id;
if (chunk_block_id >= num_eliminate_blocks_) {
break;
}
chunks_.push_back(Chunk());
Chunk& chunk = chunks_.back();
chunk.size = 0;
chunk.start = r;
int buffer_size = 0;
const int e_block_size = bs->cols[chunk_block_id].size;
// Add to the chunk until the first block in the row is
// different than the one in the first row for the chunk.
while (r + chunk.size < num_row_blocks) {
const CompressedRow& row = bs->rows[r + chunk.size];
if (row.cells.front().block_id != chunk_block_id) {
break;
}
// Iterate over the blocks in the row, ignoring the first
// block since it is the one to be eliminated.
for (int c = 1; c < row.cells.size(); ++c) {
const Cell& cell = row.cells[c];
if (InsertIfNotPresent(
&(chunk.buffer_layout), cell.block_id, buffer_size)) {
buffer_size += e_block_size * bs->cols[cell.block_id].size;
}
}
buffer_size_ = std::max(buffer_size, buffer_size_);
++chunk.size;
}
CHECK_GT(chunk.size, 0);
r += chunk.size;
}
const Chunk& chunk = chunks_.back();
uneliminated_row_begins_ = chunk.start + chunk.size;
buffer_.reset(new double[buffer_size_ * num_threads_]);
// chunk_outer_product_buffer_ only needs to store e_block_size *
// f_block_size, which is always less than buffer_size_, so we just
// allocate buffer_size_ per thread.
chunk_outer_product_buffer_.reset(new double[buffer_size_ * num_threads_]);
STLDeleteElements(&rhs_locks_);
rhs_locks_.resize(num_col_blocks - num_eliminate_blocks_);
for (int i = 0; i < num_col_blocks - num_eliminate_blocks_; ++i) {
rhs_locks_[i] = new Mutex;
}
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
Eliminate(const BlockSparseMatrix* A,
const double* b,
const double* D,
BlockRandomAccessMatrix* lhs,
double* rhs) {
if (lhs->num_rows() > 0) {
lhs->SetZero();
VectorRef(rhs, lhs->num_rows()).setZero();
}
const CompressedRowBlockStructure* bs = A->block_structure();
const int num_col_blocks = bs->cols.size();
// Add the diagonal to the schur complement.
if (D != NULL) {
#ifdef CERES_USE_OPENMP
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
#endif // CERES_USE_OPENMP
#if !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) {
#else
ParallelFor(context_, num_eliminate_blocks_, num_col_blocks, num_threads_,
[&](int i) {
#endif // !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
const int block_id = i - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block_id, block_id,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block_size = bs->cols[i].size;
typename EigenTypes<Eigen::Dynamic>::ConstVectorRef
diag(D + bs->cols[i].position, block_size);
CeresMutexLock l(&cell_info->m);
MatrixRef m(cell_info->values, row_stride, col_stride);
m.block(r, c, block_size, block_size).diagonal()
+= diag.array().square().matrix();
}
}
#if defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
);
#endif // defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
}
#if !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
ThreadTokenProvider thread_token_provider(num_threads_);
#endif // !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
#ifdef CERES_USE_OPENMP
// Eliminate y blocks one chunk at a time. For each chunk, compute
// the entries of the normal equations and the gradient vector block
// corresponding to the y block and then apply Gaussian elimination
// to them. The matrix ete stores the normal matrix corresponding to
// the block being eliminated and array buffer_ contains the
// non-zero blocks in the row corresponding to this y block in the
// normal equations. This computation is done in
// ChunkDiagonalBlockAndGradient. UpdateRhs then applies gaussian
// elimination to the rhs of the normal equations, updating the rhs
// of the reduced linear system by modifying rhs blocks for all the
// z blocks that share a row block/residual term with the y
// block. EliminateRowOuterProduct does the corresponding operation
// for the lhs of the reduced linear system.
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
#endif // CERES_USE_OPENMP
#if !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
for (int i = 0; i < chunks_.size(); ++i) {
const ScopedThreadToken scoped_thread_token(&thread_token_provider);
const int thread_id = scoped_thread_token.token();
#else
ParallelFor(context_,
0,
int(chunks_.size()),
num_threads_,
[&](int thread_id, int i) {
#endif // !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
double* buffer = buffer_.get() + thread_id * buffer_size_;
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
VectorRef(buffer, buffer_size_).setZero();
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
FixedArray<double, 8> g(e_block_size);
typename EigenTypes<kEBlockSize>::VectorRef gref(g.get(), e_block_size);
gref.setZero();
// We are going to be computing
//
// S += F'F - F'E(E'E)^{-1}E'F
//
// for each Chunk. The computation is broken down into a number of
// function calls as below.
// Compute the outer product of the e_blocks with themselves (ete
// = E'E). Compute the product of the e_blocks with the
// corresonding f_blocks (buffer = E'F), the gradient of the terms
// in this chunk (g) and add the outer product of the f_blocks to
// Schur complement (S += F'F).
ChunkDiagonalBlockAndGradient(
chunk, A, b, chunk.start, &ete, g.get(), buffer, lhs);
// Normally one wouldn't compute the inverse explicitly, but
// e_block_size will typically be a small number like 3, in
// which case its much faster to compute the inverse once and
// use it to multiply other matrices/vectors instead of doing a
// Solve call over and over again.
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix inverse_ete =
InvertPSDMatrix<kEBlockSize>(assume_full_rank_ete_, ete);
// For the current chunk compute and update the rhs of the reduced
// linear system.
//
// rhs = F'b - F'E(E'E)^(-1) E'b
FixedArray<double, 8> inverse_ete_g(e_block_size);
MatrixVectorMultiply<kEBlockSize, kEBlockSize, 0>(
inverse_ete.data(),
e_block_size,
e_block_size,
g.get(),
inverse_ete_g.get());
UpdateRhs(chunk, A, b, chunk.start, inverse_ete_g.get(), rhs);
// S -= F'E(E'E)^{-1}E'F
ChunkOuterProduct(
thread_id, bs, inverse_ete, buffer, chunk.buffer_layout, lhs);
}
#if defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
);
#endif // defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
// For rows with no e_blocks, the schur complement update reduces to
// S += F'F.
NoEBlockRowsUpdate(A, b, uneliminated_row_begins_, lhs, rhs);
}
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
BackSubstitute(const BlockSparseMatrix* A,
const double* b,
const double* D,
const double* z,
double* y) {
const CompressedRowBlockStructure* bs = A->block_structure();
#ifdef CERES_USE_OPENMP
#pragma omp parallel for num_threads(num_threads_) schedule(dynamic)
#endif // CERES_USE_OPENMP
#if !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
for (int i = 0; i < chunks_.size(); ++i) {
#else
ParallelFor(context_, 0, int(chunks_.size()), num_threads_, [&](int i) {
#endif // !(defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS))
const Chunk& chunk = chunks_[i];
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
double* y_ptr = y + bs->cols[e_block_id].position;
typename EigenTypes<kEBlockSize>::VectorRef y_block(y_ptr, e_block_size);
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix
ete(e_block_size, e_block_size);
if (D != NULL) {
const typename EigenTypes<kEBlockSize>::ConstVectorRef
diag(D + bs->cols[e_block_id].position, e_block_size);
ete = diag.array().square().matrix().asDiagonal();
} else {
ete.setZero();
}
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[chunk.start + j];
const Cell& e_cell = row.cells.front();
DCHECK_EQ(e_block_id, e_cell.block_id);
FixedArray<double, 8> sj(row.block.size);
typename EigenTypes<kRowBlockSize>::VectorRef(sj.get(), row.block.size) =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + bs->rows[chunk.start + j].block.position, row.block.size);
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
const int r_block = f_block_id - num_eliminate_blocks_;
MatrixVectorMultiply<kRowBlockSize, kFBlockSize, -1>(
values + row.cells[c].position, row.block.size, f_block_size,
z + lhs_row_layout_[r_block],
sj.get());
}
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
sj.get(),
y_ptr);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete.data(), 0, 0, e_block_size, e_block_size);
}
y_block = InvertPSDMatrix<kEBlockSize>(assume_full_rank_ete_, ete)
* y_block;
}
#if defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
);
#endif // defined(CERES_USE_TBB) || defined(CERES_USE_CXX11_THREADS)
}
// Update the rhs of the reduced linear system. Compute
//
// F'b - F'E(E'E)^(-1) E'b
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
UpdateRhs(const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
const double* inverse_ete_g,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const int e_block_id = bs->rows[chunk.start].cells.front().block_id;
const int e_block_size = bs->cols[e_block_id].size;
int b_pos = bs->rows[row_block_counter].block.position;
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
const Cell& e_cell = row.cells.front();
typename EigenTypes<kRowBlockSize>::Vector sj =
typename EigenTypes<kRowBlockSize>::ConstVectorRef
(b + b_pos, row.block.size);
MatrixVectorMultiply<kRowBlockSize, kEBlockSize, -1>(
values + e_cell.position, row.block.size, e_block_size,
inverse_ete_g, sj.data());
for (int c = 1; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
CeresMutexLock l(rhs_locks_[block]);
MatrixTransposeVectorMultiply<kRowBlockSize, kFBlockSize, 1>(
values + row.cells[c].position,
row.block.size, block_size,
sj.data(), rhs + lhs_row_layout_[block]);
}
b_pos += row.block.size;
}
}
// Given a Chunk - set of rows with the same e_block, e.g. in the
// following Chunk with two rows.
//
// E F
// [ y11 0 0 0 | z11 0 0 0 z51]
// [ y12 0 0 0 | z12 z22 0 0 0]
//
// this function computes twp matrices. The diagonal block matrix
//
// ete = y11 * y11' + y12 * y12'
//
// and the off diagonal blocks in the Guass Newton Hessian.
//
// buffer = [y11'(z11 + z12), y12' * z22, y11' * z51]
//
// which are zero compressed versions of the block sparse matrices E'E
// and E'F.
//
// and the gradient of the e_block, E'b.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkDiagonalBlockAndGradient(
const Chunk& chunk,
const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* ete,
double* g,
double* buffer,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
int b_pos = bs->rows[row_block_counter].block.position;
const int e_block_size = ete->rows();
// Iterate over the rows in this chunk, for each row, compute the
// contribution of its F blocks to the Schur complement, the
// contribution of its E block to the matrix EE' (ete), and the
// corresponding block in the gradient vector.
const double* values = A->values();
for (int j = 0; j < chunk.size; ++j) {
const CompressedRow& row = bs->rows[row_block_counter + j];
if (row.cells.size() > 1) {
EBlockRowOuterProduct(A, row_block_counter + j, lhs);
}
// Extract the e_block, ETE += E_i' E_i
const Cell& e_cell = row.cells.front();
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + e_cell.position, row.block.size, e_block_size,
ete->data(), 0, 0, e_block_size, e_block_size);
// g += E_i' b_i
MatrixTransposeVectorMultiply<kRowBlockSize, kEBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
b + b_pos,
g);
// buffer = E'F. This computation is done by iterating over the
// f_blocks for each row in the chunk.
for (int c = 1; c < row.cells.size(); ++c) {
const int f_block_id = row.cells[c].block_id;
const int f_block_size = bs->cols[f_block_id].size;
double* buffer_ptr =
buffer + FindOrDie(chunk.buffer_layout, f_block_id);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kEBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + e_cell.position, row.block.size, e_block_size,
values + row.cells[c].position, row.block.size, f_block_size,
buffer_ptr, 0, 0, e_block_size, f_block_size);
}
b_pos += row.block.size;
}
}
// Compute the outer product F'E(E'E)^{-1}E'F and subtract it from the
// Schur complement matrix, i.e
//
// S -= F'E(E'E)^{-1}E'F.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
ChunkOuterProduct(int thread_id,
const CompressedRowBlockStructure* bs,
const Matrix& inverse_ete,
const double* buffer,
const BufferLayoutType& buffer_layout,
BlockRandomAccessMatrix* lhs) {
// This is the most computationally expensive part of this
// code. Profiling experiments reveal that the bottleneck is not the
// computation of the right-hand matrix product, but memory
// references to the left hand side.
const int e_block_size = inverse_ete.rows();
BufferLayoutType::const_iterator it1 = buffer_layout.begin();
double* b1_transpose_inverse_ete =
chunk_outer_product_buffer_.get() + thread_id * buffer_size_;
// S(i,j) -= bi' * ete^{-1} b_j
for (; it1 != buffer_layout.end(); ++it1) {
const int block1 = it1->first - num_eliminate_blocks_;
const int block1_size = bs->cols[it1->first].size;
MatrixTransposeMatrixMultiply
<kEBlockSize, kFBlockSize, kEBlockSize, kEBlockSize, 0>(
buffer + it1->second, e_block_size, block1_size,
inverse_ete.data(), e_block_size, e_block_size,
b1_transpose_inverse_ete, 0, 0, block1_size, e_block_size);
BufferLayoutType::const_iterator it2 = it1;
for (; it2 != buffer_layout.end(); ++it2) {
const int block2 = it2->first - num_eliminate_blocks_;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[it2->first].size;
CeresMutexLock l(&cell_info->m);
MatrixMatrixMultiply
<kFBlockSize, kEBlockSize, kEBlockSize, kFBlockSize, -1>(
b1_transpose_inverse_ete, block1_size, e_block_size,
buffer + it2->second, e_block_size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For rows with no e_blocks, the schur complement update reduces to S
// += F'F. This function iterates over the rows of A with no e_block,
// and calls NoEBlockRowOuterProduct on each row.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowsUpdate(const BlockSparseMatrix* A,
const double* b,
int row_block_counter,
BlockRandomAccessMatrix* lhs,
double* rhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const double* values = A->values();
for (; row_block_counter < bs->rows.size(); ++row_block_counter) {
const CompressedRow& row = bs->rows[row_block_counter];
for (int c = 0; c < row.cells.size(); ++c) {
const int block_id = row.cells[c].block_id;
const int block_size = bs->cols[block_id].size;
const int block = block_id - num_eliminate_blocks_;
MatrixTransposeVectorMultiply<Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[c].position, row.block.size, block_size,
b + row.block.position,
rhs + lhs_row_layout_[block]);
}
NoEBlockRowOuterProduct(A, row_block_counter, lhs);
}
}
// A row r of A, which has no e_blocks gets added to the Schur
// Complement as S += r r'. This function is responsible for computing
// the contribution of a single row r to the Schur complement. It is
// very similar in structure to EBlockRowOuterProduct except for
// one difference. It does not use any of the template
// parameters. This is because the algorithm used for detecting the
// static structure of the matrix A only pays attention to rows with
// e_blocks. This is becase rows without e_blocks are rare and
// typically arise from regularization terms in the original
// optimization problem, and have a very different structure than the
// rows with e_blocks. Including them in the static structure
// detection will lead to most template parameters being set to
// dynamic. Since the number of rows without e_blocks is small, the
// lack of templating is not an issue.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
NoEBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 0; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// This multiply currently ignores the fact that this is a
// symmetric outer product.
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
const int block2_size = bs->cols[row.cells[j].block_id].size;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, Eigen::Dynamic, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
// For a row with an e_block, compute the contribition S += F'F. This
// function has the same structure as NoEBlockRowOuterProduct, except
// that this function uses the template parameters.
template <int kRowBlockSize, int kEBlockSize, int kFBlockSize>
void
SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::
EBlockRowOuterProduct(const BlockSparseMatrix* A,
int row_block_index,
BlockRandomAccessMatrix* lhs) {
const CompressedRowBlockStructure* bs = A->block_structure();
const CompressedRow& row = bs->rows[row_block_index];
const double* values = A->values();
for (int i = 1; i < row.cells.size(); ++i) {
const int block1 = row.cells[i].block_id - num_eliminate_blocks_;
DCHECK_GE(block1, 0);
const int block1_size = bs->cols[row.cells[i].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block1,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
CeresMutexLock l(&cell_info->m);
// block += b1.transpose() * b1;
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[i].position, row.block.size, block1_size,
cell_info->values, r, c, row_stride, col_stride);
}
for (int j = i + 1; j < row.cells.size(); ++j) {
const int block2 = row.cells[j].block_id - num_eliminate_blocks_;
DCHECK_GE(block2, 0);
DCHECK_LT(block1, block2);
const int block2_size = bs->cols[row.cells[j].block_id].size;
int r, c, row_stride, col_stride;
CellInfo* cell_info = lhs->GetCell(block1, block2,
&r, &c,
&row_stride, &col_stride);
if (cell_info != NULL) {
// block += b1.transpose() * b2;
CeresMutexLock l(&cell_info->m);
MatrixTransposeMatrixMultiply
<kRowBlockSize, kFBlockSize, kRowBlockSize, kFBlockSize, 1>(
values + row.cells[i].position, row.block.size, block1_size,
values + row.cells[j].position, row.block.size, block2_size,
cell_info->values, r, c, row_stride, col_stride);
}
}
}
}
} // namespace internal
} // namespace ceres
#endif // CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
|
conv_im2col_layer.h | //Tencent is pleased to support the open source community by making FeatherCNN available.
//Copyright (C) 2018 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.
#pragma once
#include "../feather_simple_generated.h"
#include "conv_layer.h"
#include "blob.h"
#include "arm/generic_kernels.h"
#include "arm/sgemm.h"
#include "arm/sgemm_legacy.h"
#include "arm/helper.h"
#include <assert.h>
#include <stdio.h>
#define USE_LEGACY_SGEMM
namespace feather
{
void naive_sgemm(int M, int N, int L, float* A, float* B, float* C)
{
for (int i = 0; i < M; ++i) //loop over rows in C
{
for (int j = 0; j < N; ++j) //loop over columns in C
{
float sigma = 0;
for (int k = 0; k < L; ++k)
{
sigma += A[i * L + k] * B[k * N + j];
}
C[i * N + j] = sigma;
}
}
}
class ConvIm2colLayer : public ConvLayer
{
public:
ConvIm2colLayer(const LayerParameter *layer_param, const RuntimeParameter<float>* rt_param)
: fuse_relu(false), kc(0), nc(0), img_buffer(0), pack_array_size(0), ConvLayer(layer_param, rt_param)
{
#ifdef USE_LEGACY_SGEMM
_fusible = false;
#else
_fusible = true;
#endif
//kc = 304;
//nc = 304;
kc = 320;
nc = 160;
//kc = 400;
//nc = 400;
}
int Forward()
{
//MEMPOOL_CHECK_RETURN(common_mempool->GetPtr(&pack_array));
//img_buffer = pack_array + pack_array_size;
MEMPOOL_CHECK_RETURN(common_mempool->GetPtr(&img_buffer));
if(group <=0) group = 1;
#ifdef USE_LEGACY_SGEMM
#if 1
if (kernel_width == 1 && kernel_height == 1 && stride_height == 1 && stride_width == 1 && padding_left == 1 && padding_right == 1 && padding_top == 1 && padding_bottom == 1)
{
if (output_channels % 8 == 0)
{
block_sgemm_external_pack_threading_8x8((int)output_channels, (int)output_width * (int)output_height,
(int)input_channels * (int)kernel_width * (int)kernel_height,
packed_kernel, input, output, (int)num_threads);
}
else
{
block_sgemm_external_pack_threading((int)output_channels, (int)output_width * (int)output_height,
(int)input_channels * (int)kernel_width * (int)kernel_height,
packed_kernel, input, output, (int)num_threads);
}
}
else
{
Im2col();
//jintaomeng support the case for group != input_channels
int block = (int)input_channels / group * (int)kernel_width * (int)kernel_height;
if (output_channels % 8 == 0)
{
for (int k = 0; k < group; k++)
block_sgemm_external_pack_threading_8x8((int)output_channels, (int)output_width * (int)output_height,
(int)input_channels / group * (int)kernel_width * (int)kernel_height,
packed_kernel, img_buffer + k * block, output, (int)num_threads);
}
else
{
for (int k = 0; k < group; k++)
block_sgemm_external_pack_threading((int)output_channels, (int)output_width * (int)output_height,
(int)input_channels / group * (int)kernel_width * (int)kernel_height,
packed_kernel, img_buffer + k * block, output, (int)num_threads);
}
}
#else
Im2col();
naive_sgemm(output_channels, output_height * output_width, input_channels * kernel_width * kernel_height, kernel_data, img_buffer, output);
#endif
if (bias_term)
{
size_t out_stride = output_width * output_height;
for (int i = 0; i < output_channels; ++i)
{
float bias = bias_data[i];
for (int j = 0; j < out_stride; ++j)
{
output[out_stride * i + j] = output[out_stride * i + j] + bias;
}
}
}
#else
const int M = output_channels;
const int N = output_height * output_width;
const int K = input_channels * kernel_width * kernel_height;
if (kernel_width == 1 && kernel_height == 1 && stride_height == 1 && stride_width == 1 && padding_left == 1 && padding_right == 1 && padding_top == 1 && padding_bottom == 1)
{
packed_sgemm(M, N, K, packed_kernel, input, N, output, N, nc, kc, bias_data, num_threads, pack_array);
}
else
{
Im2col();
packed_sgemm(M, N, K, packed_kernel, img_buffer, N, output, N, nc, kc, bias_data, num_threads, pack_array);
}
#endif
return 0;
}
virtual int ForwardReshape()
{
const Blob<float> *bottom_blob = _bottom_blobs[_bottom[0]];
input_height = bottom_blob->height();
input_width = bottom_blob->width();
output_width = (input_width + padding_left + padding_right - kernel_width) / stride_width + 1;
output_height = (input_height + padding_top + padding_bottom - kernel_height) / stride_height + 1;
#ifdef USE_LEGACY_SGEMM
int M = (int)output_channels;
int eM = M + (8 - M % 8) % 8;
_top_blobs[_top[0]]->Realloc(eM * output_height * output_width);
#endif
//Global memory allocations
_top_blobs[_top[0]]->ReshapeWithRealloc(1, output_channels, output_height, output_width);
input = _bottom_blobs[_bottom[0]]->data();
output = _top_blobs[_top[0]]->data();
MEMPOOL_CHECK_RETURN(common_mempool->Alloc(sizeof(float) * (input_channels * kernel_height * kernel_width) * (output_width * output_height)))
return this->Forward();
}
int GenerateTopBlobs()
{
//Conv layer has and only has one bottom blob.
const Blob<float> *bottom_blob = _bottom_blobs[_bottom[0]];
input_width = bottom_blob->width();
input_height = bottom_blob->height();
input_channels = bottom_blob->channels();
if (stride_width == 0 || stride_height == 0)
{
stride_width = 1;
stride_height = 1;
}
output_width = (input_width + padding_left + padding_right - kernel_width) / stride_width + 1;
output_height = (input_height + padding_top + padding_bottom - kernel_height) / stride_height + 1;
#if 0
printf("input channels %d\n", input_channels);
assert(input_channels == bottom_blob->channels());
printf("input w %lu\n", input_width);
printf("padding_left %lu\n", padding_left);
printf("padding_top %lu\n", padding_top);
printf("stride_width %lu\n", stride_width);
printf("stride_height %lu\n", stride_height);
printf("output %ld %ld\n", output_width, output_height);
#endif
_top_blobs[_top[0]] = new Blob<float>(1, output_channels, output_height, output_width);
_top_blobs[_top[0]]->Alloc();
int M = output_channels;
#ifdef USE_LEGACY_SGEMM
int eM = M + (8 - M % 8) % 8;
_top_blobs[_top[0]]->Realloc(eM * output_height * output_width);
#endif
return 0;
}
int Fuse(Layer *next_layer)
{
if (next_layer->type().compare("ReLU") == 0)
{
fuse_relu = true;
return 1;
}
else
{
return 0;
}
}
bool Im2col()
{
const int stride = kernel_height * kernel_width * output_height * output_width;
if ((kernel_width == 1 && kernel_height == 1) && (stride_height == 2 && stride_width == 2))
{
float* ret = img_buffer;
#pragma omp parallel for num_threads(num_threads)
for (int k = 0; k < input_channels; k++)
{
int retID = stride * k;
{
for (int i = 0; i < output_height; i++)
{
for (int j = 0; j < output_width; j++)
{
//calculate each row
int row = 2 * i - (int)padding_top;
int col = 2 * j - (int)padding_left;
if (row < 0 || row >= input_height || col < 0 || col >= input_width)
{
ret[retID] = 0;
}
else
{
size_t index = k * input_width * input_height + row * input_width + col; //(i+u)*input_width+j+v;
ret[retID] = input[index];
}
retID++;
}
}
}
}
}
else
{
float* ret = img_buffer;
#pragma omp parallel for num_threads(num_threads)
for (int k = 0; k < input_channels; k++)
{
int retID = stride * k;
for (int u = 0; u < kernel_height; u++) for (int v = 0; v < kernel_width; v++)
{
for (int i = 0; i < output_height; i++)
{
for (int j = 0; j < output_width; j++)
{
//calculate each row
int row = u - (int)padding_top + i * (int)stride_height;
int col = v - (int)padding_left + j * (int)stride_width;
//printf("row %d, col %d\n", row, col);
if (row < 0 || row >= input_height || col < 0 || col >= input_width)
{
ret[retID] = 0;
}
else
{
size_t index = k * input_width * input_height + row * input_width + col; //(i+u)*input_width+j+v;
ret[retID] = input[index];
}
retID++;
}
}
}
}
}
return true;
}
int Init()
{
int M = (int)output_channels;
int N = output_height * output_width;
int K = (int)input_channels * (int)kernel_height * (int)kernel_width;
int eM = M + (8 - M % 8) % 8;
#ifdef USE_LEGACY_SGEMM
pack_array_size = 0;
MEMPOOL_CHECK_RETURN(private_mempool.Alloc(&packed_kernel, sizeof(float) * eM * K))
if (M % 8 == 0)
{
externalPackA8(M, K, packed_kernel, kernel_data, K);
}
else
{
externalPackA(M, K, packed_kernel, kernel_data, K);
}
#else
pack_array_size = (kc + 8) * nc * num_threads;
MEMPOOL_CHECK_RETURN(private_mempool.Alloc(&packed_kernel, sizeof(float) * (M * K)))
MEMPOOL_CHECK_RETURN(private_mempool.Alloc(&pack_array, sizeof(float) * pack_array_size))
packed_sgemm_init<4>(M, K, kc, packed_kernel, kernel_data, K);
//MEMPOOL_CHECK_RETURN(private_mempool.Alloc(&pack_array, sizeof(float) * (kc + 8) * nc) * this->num_threads);
if(bias_term && fuse_relu)
packed_sgemm = packed_sgemm_activation<true, true>;
else if(bias_term)
packed_sgemm = packed_sgemm_activation<true, false>;
else if(fuse_relu)
packed_sgemm = packed_sgemm_activation<false, true>;
else
packed_sgemm = packed_sgemm_activation<false, false>;
#endif
MEMPOOL_CHECK_RETURN(common_mempool->Request(sizeof(float) * (input_channels * kernel_height * kernel_width) * (output_width * output_height)))
//Setup input and output pointers.
input = _bottom_blobs[_bottom[0]]->data();
output = _top_blobs[_top[0]]->data();
return 0;
}
private:
float* packed_kernel;
float* img_buffer;
float* pack_array;
int pack_array_size;
float* input;
float* output;
bool fuse_relu;
int kc, nc;
void (*packed_sgemm)(int M, int N, int K, float *packA, float *b, int ldb, float *c, int ldc, int nc, int kc, float* bias, int num_threads, float* pack_array);
};
};
|
ExemplarClusteringSubmodularFunction.h | #ifndef EXEMCL_FUNCTION_CPU
#define EXEMCL_FUNCTION_CPU
#include <src/function/SubmodularFunction.h>
#include <utility>
namespace exemcl::cpu {
/**
* This class provides a CPU implementation of the submodular function of exemplar-based clustering.
*/
template<typename HostDataType = float>
class ExemplarClusteringSubmodularFunction : public SubmodularFunction {
public:
using SubmodularFunction::operator();
/**
* Constructs the exemplar clustering submodular function using a ground set V.
*
* @param V The ground set V.
*/
explicit ExemplarClusteringSubmodularFunction(const MatrixX<HostDataType>& V, int workerCount = -1) :
SubmodularFunction(workerCount), _V(std::make_unique<MatrixX<HostDataType>>(V)) {
MatrixX<HostDataType> zeroVec = VectorX<HostDataType>::Zero(_V->cols()).transpose();
_zeroVecValue = L(zeroVec);
};
/**
* Evaluates the exemplar cluster-submodular function.
*
* @param S The set to evaluate.
* @return The submodular function value.
*/
double operator()(const MatrixX<double>& S) override {
return ((const ExemplarClusteringSubmodularFunction*) (this))->operator()(S);
};
/**
* Evaluates the exemplar cluster-submodular function.
*
* @param S The set to evaluate.
* @return The submodular function value.
*/
double operator()(const MatrixX<double>& S) const override {
auto S_copy = std::make_unique<MatrixX<HostDataType>>(S.cast<HostDataType>());
// Add zero vector to data copy.
S_copy->conservativeResize(S_copy->rows() + 1, Eigen::NoChange_t());
S_copy->row(S_copy->rows() - 1).setZero();
// Make calculations.
HostDataType L_2 = L(*S_copy);
return _zeroVecValue - L_2;
};
/**
* Returns a reference to the ground set V.
* @return As stated above.
*/
const MatrixX<HostDataType>& getV() const {
return _V;
};
private:
HostDataType _zeroVecValue;
const std::unique_ptr<MatrixX<HostDataType>> _V;
/**
* Calculates the L function.
*
* @param S_inner Set of data to calculate the L function for.
* @return L function value.
*/
HostDataType L(const MatrixX<HostDataType>& S_inner) const {
auto* accuArray = new HostDataType[_V->rows()];
for (unsigned int i = 0; i < _V->rows(); i++) {
auto min_val = std::numeric_limits<HostDataType>::max();
for (unsigned int j = 0; j < S_inner.rows(); j++)
min_val = std::min((_V->row(i) - S_inner.row(j)).squaredNorm(), min_val);
accuArray[i] = min_val;
}
HostDataType accu = 0.0;
#pragma omp simd reduction(+ : accu)
for (unsigned int i = 0; i < _V->rows(); i++)
accu += accuArray[i];
delete[] accuArray;
return accu / static_cast<HostDataType>(_V->rows());
};
};
}
#endif // EXEMCL_FUNCTION_CPU
|
GB_subassign_12_and_20.c | //------------------------------------------------------------------------------
// GB_subassign_12_and_20: C(I,J)<M or !M,repl> += A ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// Method 12: C(I,J)<M,repl> += A ; using S
// Method 20: C(I,J)<!M,repl> += A ; using S
// M: present
// Mask_comp: true or false
// C_replace: true
// accum: present
// A: matrix
// S: constructed
// C: not bitmap: use GB_bitmap_assign instead
// M, A: any sparsity structure.
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_12_and_20
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t ni,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nj,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_Matrix M,
const bool Mask_struct, // if true, use the only structure of M
const bool Mask_comp, // if true, !M, else use M
const GrB_BinaryOp accum,
const GrB_Matrix A,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ;
ASSERT (!GB_aliased (C, M)) ; // NO ALIAS of C==M
ASSERT (!GB_aliased (C, A)) ; // NO ALIAS of C==A
//--------------------------------------------------------------------------
// S = C(I,J)
//--------------------------------------------------------------------------
GB_EMPTY_TASKLIST ;
GB_OK (GB_subassign_symbolic (&S, C, I, ni, J, nj, true, Context)) ;
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_MATRIX_WAIT_IF_JUMBLED (M) ;
GB_MATRIX_WAIT_IF_JUMBLED (A) ;
GB_GET_C ; // C must not be bitmap
GB_GET_MASK ;
GB_GET_A ;
GB_GET_S ;
GB_GET_ACCUM ;
//--------------------------------------------------------------------------
// Method 12: C(I,J)<M,repl> += A ; using S
// Method 20: C(I,J)<!M,repl> += A ; using S
//--------------------------------------------------------------------------
// Time: all entries in S+A must be traversed, so Omega(nnz(S)+nnz(A)) is
// required. All cases of the mask (0, 1, or not present) must be
// considered, because of the C_replace descriptor being true.
//--------------------------------------------------------------------------
// Parallel: A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20)
//--------------------------------------------------------------------------
if (A_is_bitmap)
{
// all of IxJ must be examined
GB_SUBASSIGN_IXJ_SLICE ;
}
else
{
// traverse all A+S
GB_SUBASSIGN_TWO_SLICE (A, S) ;
}
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
if (A_is_bitmap)
{
//----------------------------------------------------------------------
// phase1: A is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iA_start:iA_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
int64_t pA_start = j * Avlen ;
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j)
//--------------------------------------------------------------
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
int64_t pA = pA_start + iA ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ;
bool Afound = Ab [pA] ;
if (Sfound && !Afound)
{
// S (i,j) is present but A (i,j) is not
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (!mij)
{
// ----[C . 0] or [X . 0]---------------------------
// [X . 0]: action: ( X ): still a zombie
// [C . 0]: C_repl: action: ( delete ): now zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
else if (!Sfound && Afound)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
}
else if (Sfound && Afound)
{
// both S (i,j) and A (i,j) present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
GB_C_S_LOOKUP ;
if (mij)
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =A ): A to C no accum
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_withaccum_C_A_1_matrix ;
}
else
{
// ----[C A 0] or [X A 0]---------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): now zombie
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase1: A is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE1 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get A(:,j) and S(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
// int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iA = GBI (Ai, pA, Avlen) ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iS) ;
if (Mask_comp) mij = !mij ;
if (!mij)
{
// ----[C . 0] or [X . 0]---------------------------
// [X . 0]: action: ( X ): still a zombie
// [C . 0]: C_repl: action: ( delete ): now zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
GB_C_S_LOOKUP ;
if (mij)
{
// ----[C A 1] or [X A 1]---------------------------
// [C A 1]: action: ( =A ): A to C no accum
// [C A 1]: action: ( =C+A ): apply accum
// [X A 1]: action: ( undelete ): zombie lives
GB_withaccum_C_A_1_matrix ;
}
else
{
// ----[C A 0] or [X A 0]---------------------------
// [X A 0]: action: ( X ): still a zombie
// [C A 0]: C_repl: action: ( delete ): now zombie
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// while list S (:,j) has entries. List A (:,j) exhausted.
while (pS < pS_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iS) ;
if (Mask_comp) mij = !mij ;
if (!mij)
{
// ----[C . 0] or [X . 0]-------------------------------
// [X . 0]: action: ( X ): still a zombie
// [C . 0]: C_repl: action: ( delete ): becomes zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
// while list A (:,j) has entries. List S (:,j) exhausted.
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = GBI (Ai, pA, Avlen) ;
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
}
GB_PHASE1_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
if (A_is_bitmap)
{
//----------------------------------------------------------------------
// phase2: A is bitmap
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t j = kfirst ; j <= klast ; j++)
{
//--------------------------------------------------------------
// get S(iA_start:iA_end,j)
//--------------------------------------------------------------
GB_GET_VECTOR_FOR_IXJ (S, iA_start) ;
int64_t pA_start = j * Avlen ;
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
for (int64_t iA = iA_start ; iA < iA_end ; iA++)
{
int64_t pA = pA_start + iA ;
bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ;
bool Afound = Ab [pA] ;
if (!Sfound && Afound)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
}
}
else if (Sfound)
{
// S (i,j) present
GB_NEXT (S) ;
}
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
else
{
//----------------------------------------------------------------------
// phase2: A is hypersparse, sparse, or full
//----------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//------------------------------------------------------------------
// get the task descriptor
//------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE2 ;
//------------------------------------------------------------------
// compute all vectors in this task
//------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//--------------------------------------------------------------
// get A(:,j) and S(:,j)
//--------------------------------------------------------------
int64_t j = GBH (Zh, k) ;
GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen);
GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen);
//--------------------------------------------------------------
// get M(:,j)
//--------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
bool mjdense = (pM_end - pM_start) == Mvlen ;
//--------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//--------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = GBI (Si, pS, Svlen) ;
int64_t iA = GBI (Ai, pA, Avlen) ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]--------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// while list A (:,j) has entries. List S (:,j) exhausted.
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = GBI (Ai, pA, Avlen) ;
GB_MIJ_BINARY_SEARCH_OR_DENSE_LOOKUP (iA) ;
if (Mask_comp) mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
}
GB_NEXT (A) ;
}
}
GB_PHASE2_TASK_WRAPUP ;
}
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
mxnet_op.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) 2017 by Contributors
* \file mxnet_op.h
* \brief
* \author Junyuan Xie
*/
#ifndef MXNET_OPERATOR_MXNET_OP_H_
#define MXNET_OPERATOR_MXNET_OP_H_
#include <dmlc/omp.h>
#include <mxnet/base.h>
#include <mxnet/engine.h>
#include <mxnet/op_attr_types.h>
#include <algorithm>
#include <limits>
#include "./operator_tune.h"
#include "../engine/openmp.h"
#ifdef __CUDACC__
#include "../common/cuda/utils.h"
#endif // __CUDACC__
namespace mxnet {
namespace op {
namespace mxnet_op {
using namespace mshadow;
#ifdef __CUDA_ARCH__
__constant__ const float PI = 3.14159265358979323846;
#else
const float PI = 3.14159265358979323846;
using std::isnan;
#endif
template<typename xpu>
int get_num_threads(const int N);
#ifdef __CUDACC__
#define CUDA_KERNEL_LOOP(i, n) \
for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
i < (n); \
i += blockDim.x * gridDim.x)
inline cudaDeviceProp cuda_get_device_prop() {
int device;
CUDA_CALL(cudaGetDevice(&device));
cudaDeviceProp deviceProp;
CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device));
return deviceProp;
}
/*!
* \brief Get the number of blocks for cuda kernel given N
*/
inline int cuda_get_num_blocks(const int N) {
using namespace mshadow::cuda;
return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum);
}
template<>
inline int get_num_threads<gpu>(const int N) {
using namespace mshadow::cuda;
return kBaseThreadNum * cuda_get_num_blocks(N);
}
#endif // __CUDACC__
template<>
inline int get_num_threads<cpu>(const int N) {
return engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
}
/*! \brief operator request type switch */
#define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \
switch (req) { \
case kNullOp: \
break; \
case kWriteInplace: \
case kWriteTo: \
{ \
const OpReqType ReqType = kWriteTo; \
{__VA_ARGS__} \
} \
break; \
case kAddTo: \
{ \
const OpReqType ReqType = kAddTo; \
{__VA_ARGS__} \
} \
break; \
default: \
break; \
}
/*! \brief operator request type switch */
#define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \
switch (req) { \
case kNullOp: \
{ \
const OpReqType ReqType = kNullOp; \
{__VA_ARGS__} \
} \
break; \
case kWriteInplace: \
case kWriteTo: \
{ \
const OpReqType ReqType = kWriteTo; \
{__VA_ARGS__} \
} \
break; \
case kAddTo: \
{ \
const OpReqType ReqType = kAddTo; \
{__VA_ARGS__} \
} \
break; \
default: \
break; \
}
#define MXNET_NDIM_SWITCH(NDim, ndim, ...) \
if (NDim == 0) { \
} else if (NDim == 1) { \
const int ndim = 1; \
{__VA_ARGS__} \
} else if (NDim == 2) { \
const int ndim = 2; \
{__VA_ARGS__} \
} else if (NDim == 3) { \
const int ndim = 3; \
{__VA_ARGS__} \
} else if (NDim == 4) { \
const int ndim = 4; \
{__VA_ARGS__} \
} else if (NDim == 5) { \
const int ndim = 5; \
{__VA_ARGS__} \
} else { \
LOG(FATAL) << "ndim=" << NDim << "too large "; \
}
#define MXNET_NDIM_SWITCH_EX(NDim, ndim, ...) \
if (NDim == 0) { \
} else if (NDim == 1) { \
const int ndim = 1; \
{__VA_ARGS__} \
} else if (NDim == 2) { \
const int ndim = 2; \
{__VA_ARGS__} \
} else if (NDim == 3) { \
const int ndim = 3; \
{__VA_ARGS__} \
} else if (NDim == 4) { \
const int ndim = 4; \
{__VA_ARGS__} \
} else if (NDim == 5) { \
const int ndim = 5; \
{__VA_ARGS__} \
} else if (NDim == 6) { \
const int ndim = 6; \
{__VA_ARGS__} \
} else if (NDim == 7) { \
const int ndim = 7; \
{__VA_ARGS__} \
} else if (NDim == 8) { \
const int ndim = 8; \
{__VA_ARGS__} \
} else if (NDim == 9) { \
const int ndim = 9; \
{__VA_ARGS__} \
} else if (NDim == 10) { \
const int ndim = 10; \
{__VA_ARGS__} \
} else { \
LOG(FATAL) << "ndim=" << NDim << "too large "; \
}
#define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
case mshadow::kBfloat16: \
{ \
typedef mshadow::half::half_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kUint8: \
LOG(FATAL) << "This operation does not " \
"support int8 or uint8"; \
break; \
case mshadow::kInt8: \
LOG(FATAL) << "This operation does not " \
"support int8 or uint8"; \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_NO_BFLOAT16_TYPE_SWITCH(type, DType, ...) \
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
{ \
typedef mshadow::half::half_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kBfloat16: \
LOG(FATAL) << "This operation does not " \
"support bfloat16"; \
break; \
case mshadow::kInt8: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
LOG(FATAL) << "This operation does not " \
"support float16"; \
break; \
case mshadow::kUint8: \
{ \
typedef uint8_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt8: \
{ \
typedef int8_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
template <typename T>
struct AccType {
using type = T;
};
template <>
struct AccType<mshadow::half::half_t> {
using type = float;
};
#define MXNET_REAL_ACC_TYPE_SWITCH(type, DType, AType, ...)\
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
typedef double AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
typedef double AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
{ \
typedef mshadow::half::half_t DType; \
typedef float AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kUint8: \
{ \
LOG(FATAL) << "This operation only support " \
"floating point types not uint8"; \
} \
break; \
case mshadow::kInt8: \
{ \
LOG(FATAL) << "This operation only support " \
"floating point types not int8"; \
} \
break; \
case mshadow::kInt32: \
{ \
LOG(FATAL) << "This operation only support " \
"floating point types, not int32"; \
} \
break; \
case mshadow::kInt64: \
{ \
LOG(FATAL) << "This operation only support " \
"floating point types, not int64"; \
} \
break; \
case mshadow::kBool: \
{ \
LOG(FATAL) << "This operation only support " \
"floating point types, not bool"; \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_ACC_TYPE_SWITCH(type, DType, AType, ...)\
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
typedef double AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
typedef double AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
{ \
typedef mshadow::half::half_t DType; \
typedef float AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kUint8: \
{ \
typedef uint8_t DType; \
typedef uint32_t AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt8: \
{ \
typedef int8_t DType; \
typedef int32_t AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
typedef int64_t AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
typedef int64_t AType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kBool: \
{ \
typedef bool DType; \
typedef int64_t AType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_INT_TYPE_SWITCH(type, DType, ...)\
switch (type) { \
case mshadow::kFloat32: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float32"; \
} \
break; \
case mshadow::kFloat64: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float64"; \
} \
break; \
case mshadow::kFloat16: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float16"; \
} \
break; \
case mshadow::kUint8: \
{ \
typedef uint8_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt8: \
{ \
typedef int8_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kBool: \
{ \
typedef bool DType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_INT32_INT64_TYPE_SWITCH(type, DType, ...)\
switch (type) { \
case mshadow::kFloat32: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float32"; \
} \
break; \
case mshadow::kFloat64: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float64"; \
} \
break; \
case mshadow::kFloat16: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not float16"; \
} \
break; \
case mshadow::kUint8: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not uint8"; \
} \
break; \
case mshadow::kInt8: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not int8"; \
} \
break; \
case mshadow::kInt32: \
{ \
typedef int32_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kInt64: \
{ \
typedef int64_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kBool: \
{ \
LOG(FATAL) << "This operation only support " \
"integer types, not bool"; \
} \
break; \
default: \
LOG(FATAL) << "Unknown type enum " << type; \
}
#define MXNET_LOAD_TYPE_SWITCH(type, DType, ...) \
switch (type) { \
case mshadow::kFloat32: \
{ \
typedef float DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat64: \
{ \
typedef double DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kFloat16: \
{ \
typedef mshadow::half::half_t DType; \
{__VA_ARGS__} \
} \
break; \
case mshadow::kUint8: \
{ \
typedef uint8_t DType; \
{__VA_ARGS__} \
} \
break; \
default: \
LOG(FATAL) << "Invalid loading enum type " << type; \
}
/*!
* \brief assign the val to out according
* to request in Kernel::Launch
* \param out the data to be assigned
* \param req the assignment request
* \param val the value to be assigned to out
* \tparam OType output type
* \tparam VType value type
*/
#define KERNEL_ASSIGN(out, req, val) \
{ \
switch (req) { \
case kNullOp: \
break; \
case kWriteTo: \
case kWriteInplace: \
(out) = (val); \
break; \
case kAddTo: \
(out) += (val); \
break; \
default: \
break; \
} \
}
#define MXNET_ADD_ALL_TYPES \
.add_enum("float32", mshadow::kFloat32) \
.add_enum("float64", mshadow::kFloat64) \
.add_enum("float16", mshadow::kFloat16) \
.add_enum("bfloat16", mshadow::kBfloat16) \
.add_enum("uint8", mshadow::kUint8) \
.add_enum("int8", mshadow::kInt8) \
.add_enum("int32", mshadow::kInt32) \
.add_enum("int64", mshadow::kInt64)
#define MXNET_ADD_ALL_TYPES_WITH_BOOL \
.add_enum("float32", mshadow::kFloat32) \
.add_enum("float64", mshadow::kFloat64) \
.add_enum("float16", mshadow::kFloat16) \
.add_enum("bfloat16", mshadow::kBfloat16) \
.add_enum("uint8", mshadow::kUint8) \
.add_enum("int8", mshadow::kInt8) \
.add_enum("int32", mshadow::kInt32) \
.add_enum("int64", mshadow::kInt64) \
.add_enum("bool", mshadow::kBool)
/* \brief Compute flattened index given coordinates and shape. */
template<int ndim>
MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) {
index_t ret = 0;
#pragma unroll
for (int i = 0; i < ndim; ++i) {
ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i];
}
return ret;
}
/* Compute coordinates from flattened index given shape */
template<int ndim>
MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) {
Shape<ndim> ret;
#pragma unroll
for (index_t i = ndim-1, j = idx; i >=0; --i) {
auto tmp = j / shape[i];
ret[i] = j - tmp*shape[i];
j = tmp;
}
return ret;
}
/* Compute dot product of two vector */
template<int ndim>
MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) {
index_t ret = 0;
#pragma unroll
for (int i = 0; i < ndim; ++i) {
ret += coord[i] * stride[i];
}
return ret;
}
/* Combining unravel and dot */
template<int ndim>
MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape,
const Shape<ndim>& stride) {
index_t ret = 0;
#pragma unroll
for (index_t i = ndim-1, j = idx; i >=0; --i) {
auto tmp = j / shape[i];
ret += (j - tmp*shape[i])*stride[i];
j = tmp;
}
return ret;
}
/* Calculate stride of each dim from shape */
template<int ndim>
MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) {
Shape<ndim> stride;
index_t cumprod = 1;
#pragma unroll
for (int i = ndim - 1; i >= 0; --i) {
stride[i] = (shape[i] > 1) ? cumprod : 0;
cumprod *= shape[i];
}
return stride;
}
/* Increment coordinates */
template<int ndim>
MSHADOW_XINLINE bool inc(Shape<ndim>* coord, const Shape<ndim>& shape) {
++(*coord)[ndim-1];
#pragma unroll
for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) {
(*coord)[i] -= shape[i];
++(*coord)[i-1];
}
return (*coord)[0] < shape[0];
}
/* Increment coordinates and modify index */
template<int ndim>
MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape,
index_t* idx, const Shape<ndim>& stride) {
++(*coord)[ndim-1];
*idx += stride[ndim-1];
#pragma unroll
for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) {
(*coord)[i] -= shape[i];
++(*coord)[i-1];
*idx = *idx + stride[i-1] - shape[i] * stride[i];
}
}
/* Increment coordinates and modify index */
template<int ndim>
MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape,
index_t* idx1, const Shape<ndim>& stride1,
index_t* idx2, const Shape<ndim>& stride2) {
++(*coord)[ndim-1];
*idx1 += stride1[ndim-1];
*idx2 += stride2[ndim-1];
#pragma unroll
for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) {
(*coord)[i] -= shape[i];
++(*coord)[i-1];
*idx1 = *idx1 + stride1[i-1] - shape[i] * stride1[i];
*idx2 = *idx2 + stride2[i-1] - shape[i] * stride2[i];
}
}
/*!
* \brief Simple copy data from one blob to another
* \param to Destination blob
* \param from Source blob
*/
template <typename xpu>
MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) {
CHECK_EQ(from.Size(), to.Size());
CHECK_EQ(from.dev_mask(), to.dev_mask());
MSHADOW_TYPE_SWITCH_WITH_BOOL(to.type_flag_, DType, {
if (to.type_flag_ == from.type_flag_) {
mshadow::Copy(to.FlatTo1D<xpu, DType>(s), from.FlatTo1D<xpu, DType>(s), s);
} else {
MSHADOW_TYPE_SWITCH_WITH_BOOL(from.type_flag_, SrcDType, {
to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s));
})
}
})
}
/*! \brief Binary op backward gradient OP wrapper */
template<typename GRAD_OP>
struct backward_grad {
/* \brief Backward calc with grad
* \param a - output grad
* \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies)
* \return input grad
*/
template<typename DType, typename ...Args>
MSHADOW_XINLINE static DType Map(DType a, Args... args) {
return DType(a * GRAD_OP::Map(args...));
}
};
template<typename OP, int req>
struct mixed_type_unary_op {
typedef OP Operation;
/*! \brief input is one tensor */
template<typename OType, typename IType>
MSHADOW_XINLINE static void Map(index_t i, OType *out, const IType *in) {
KERNEL_ASSIGN(out[i], req, OP::Map(OType(in[i])));
}
};
/*! \brief Binary op backward gradient OP wrapper (tuned) */
template<typename GRAD_OP>
struct backward_grad_tuned : public backward_grad<GRAD_OP>, public tunable {
using backward_grad<GRAD_OP>::Map;
};
/*! \brief Select assignment operation based upon the req value
* Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch
*/
template<typename OP, int req>
struct op_with_req {
typedef OP Operation;
/*! \brief input is one tensor */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i]));
}
/*! \brief inputs are two tensors */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *lhs, const DType *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief input is tensor and a scalar value */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value));
}
/*! \brief input is tensor and two scalar value */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in,
const DType value_1, const DType value_2) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value_1, value_2));
}
/*! \brief No inputs (ie fill to constant value) */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out) {
KERNEL_ASSIGN(out[i], req, OP::Map());
}
/*! \brief input is single scalar value */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType value) {
KERNEL_ASSIGN(out[i], req, OP::Map(value));
}
/*! \brief inputs are two tensors and a scalar value */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out,
const DType *input_1, const DType *input_2, const DType value) {
KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value));
}
/*! \brief inputs are three tensors (ie backward grad with binary grad function) */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out,
const DType *input_1,
const DType *input_2,
const DType *input_3) {
KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i]));
}
/*! \brief input is a tensor and the output is a boolean tensor */
template<typename DType,
typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *in) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i]));
}
/*! \brief inputs are two tensors with a boolean output tensor */
template<typename DType,
typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *lhs, const DType *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief input is tensor and two scalar value with a boolean output tensor */
template<typename DType,
typename std::enable_if<!std::is_same<DType, bool>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, bool *out, const DType *in, const DType value) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value));
}
/*! \brief input is two tensors with different type and with a boolean output tensor */
template<typename LType, typename RType,
typename std::enable_if<!std::is_same<LType, RType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, bool *out, const LType *lhs, const RType *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief inputs are two tensors with a half_t output tensor */
template<typename DType,
typename std::enable_if<std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i,
mshadow::half::half_t *out,
const DType *lhs,
const mshadow::half::half_t *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief inputs are two tensors with a float output tensor */
template<typename DType,
typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value ||
std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const float *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief inputs are two tensors with a double output tensor */
template<typename DType,
typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value ||
std::is_same<DType, float>::value ||
std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, double *out, const DType *lhs, const double *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief inputs are two tensors with a half_t output tensor */
template<typename DType,
typename std::enable_if<std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i,
mshadow::half::half_t *out,
const DType *lhs,
const mshadow::half::half_t value) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value));
}
/*! \brief inputs are two tensors with a float output tensor */
template<typename DType,
typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value ||
std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const float value) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value));
}
/*! \brief inputs are two tensors with a double output tensor */
template<typename DType,
typename std::enable_if<std::is_same<DType, mshadow::half::half_t>::value ||
std::is_same<DType, float>::value ||
std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, double *out, const DType *lhs, const double value) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], value));
}
/*! \brief inputs are two tensors with a float output tensor */
template<typename DType,
typename std::enable_if<std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *lhs, const DType *rhs) {
KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
}
/*! \brief input is a tensor and a scalar value with a float output tensor */
template<typename DType,
typename std::enable_if<std::is_integral<DType>::value, int>::type = 0>
MSHADOW_XINLINE static void Map(index_t i, float *out, const DType *in, const DType value) {
KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value));
}
};
template<typename OP, typename xpu>
struct Kernel;
/*!
* \brief CPU Kernel launcher
* \tparam OP Operator to launch
*/
template<typename OP>
struct Kernel<OP, cpu> {
/*!
* \brief Launch a generic CPU kernel.
* When using this for a new kernel op, add declaration and tuning objects to
* operator_tune.cc
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param N Number of iterations
* \param args Varargs to eventually pass to the OP::Map() function
*/
template<typename ...Args>
inline static bool Launch(mshadow::Stream<cpu> *, const size_t N, Args... args) {
#ifdef _OPENMP
const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
if (omp_threads < 2) {
for (size_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
} else {
#pragma omp parallel for num_threads(omp_threads)
for (index_t i = 0; i < static_cast<index_t>(N); ++i) {
OP::Map(i, args...);
}
}
#else
for (size_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
#endif
return true;
}
/*!
* \brief Launch a generic CPU kernel with dynamic schedule. This is recommended
* for irregular workloads such as spmv.
* When using this for a new kernel op, add declaration and tuning objects to
* operator_tune.cc
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param N Number of iterations
* \param args Varargs to eventually pass to the OP::Map() function
*/
template<typename ...Args>
inline static bool LaunchDynamic(mshadow::Stream<cpu> *, const int64_t N, Args... args) {
#ifdef _OPENMP
const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(false);
if (omp_threads < 2) {
for (int64_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
} else {
#pragma omp parallel for num_threads(omp_threads) schedule(dynamic)
for (int64_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
}
#else
for (int64_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
#endif
return true;
}
/*!
* \brief Launch CPU kernel which has OMP tuning data available.
* When using this for a new kernel op, add declaration and tuning objects to
* operator_tune.cc
* \tparam PRIMITIVE_OP The primitive operation to use for tuning
* \tparam DType Data type
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param N Number of iterations
* \param dest Destination pointer (used to infer DType)
* \param args Varargs to eventually pass to the OP::Map() function
*/
template<typename PRIMITIVE_OP, typename DType, typename ...Args>
static void LaunchTuned(mshadow::Stream<cpu> *, const size_t N, Args... args) {
#ifdef _OPENMP
const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP(
N, static_cast<size_t>(omp_threads))) {
for (size_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
} else {
#pragma omp parallel for num_threads(omp_threads)
for (index_t i = 0; i < static_cast<index_t>(N); ++i) {
OP::Map(i, args...);
}
}
#else
for (size_t i = 0; i < N; ++i) {
OP::Map(i, args...);
}
#endif
}
/*!
* \brief Launch custom-tuned kernel where each thread is set to
* operate on a contiguous partition
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param N Number of iterations
* \param args Varargs to eventually pass to the UseOMP() and OP::Map() functions
*/
template<typename ...Args>
inline static void LaunchEx(mshadow::Stream<cpu> *s, const size_t N, Args... args) {
#ifdef _OPENMP
const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
if (omp_threads < 2) {
OP::Map(0, N, args...);
} else {
const auto length = (N + omp_threads - 1) / omp_threads;
#pragma omp parallel for num_threads(omp_threads)
for (index_t i = 0; i < static_cast<index_t>(N); i += length) {
OP::Map(i, i + length > N ? N - i : length, args...);
}
}
#else
OP::Map(0, N, args...);
#endif
}
/*!
* \brief Launch a tunable OP with implicitly-supplied data type
* \tparam DType Data type
* \tparam T OP type
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param s Stream (usually null for CPU)
* \param N Number of iterations
* \param args Varargs to eventually pass to the OP::Map() function
* \return Always true
*/
template<typename DType, typename T = OP, typename ...Args>
static MSHADOW_CINLINE
typename std::enable_if<std::is_base_of<tunable, T>::value, bool>::type
Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) {
LaunchTuned<T, DType>(s, N, dest, args...);
return true;
}
/*!
* \brief Launch a tunable OP wrapper with explicitly-supplied data type (ie op_with_req)
* \tparam DType Data type
* \tparam T Wrapper type
* \tparam Args Varargs type to eventually pass to the OP::Map() function
* \param s Stream (usually null for CPU)
* \param N Number of iterations
* \param args Varargs to eventually pass to the OP::Map() function
* \return Always true
*/
template<typename DType, typename T = OP, typename ...Args>
static MSHADOW_CINLINE
typename std::enable_if<std::is_base_of<tunable, typename T::Operation>::value, bool>::type
Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) {
LaunchTuned<typename T::Operation, DType>(s, N, dest, args...);
return true;
}
};
#ifdef __CUDACC__
template<typename OP, typename ...Args>
__global__ void mxnet_generic_kernel(int N, Args... args) {
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) {
OP::Map(i, args...);
}
}
template<typename OP, typename ...Args>
__global__ void mxnet_generic_kernel_ex(int N, Args... args) {
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) {
OP::Map(i, 1, args...);
}
}
template<typename OP>
struct Kernel<OP, gpu> {
/*! \brief Launch GPU kernel */
template<typename ...Args>
inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) {
if (0 == N) return;
using namespace mshadow::cuda;
int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum);
mxnet_generic_kernel<OP, Args...>
<<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
N, args...);
MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel);
}
template<typename ...Args>
inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) {
if (0 == N) return;
using namespace mshadow::cuda;
int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum);
mxnet_generic_kernel_ex<OP, Args...>
<<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
N, args...);
MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex);
}
};
#endif // __CUDACC__
/*!
* \brief Set to immediate scalar value kernel
* \tparam val Scalar immediate
*/
template<int val>
struct set_to_int : public tunable {
// mxnet_op version (when used directly with Kernel<>::Launch()) */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out) {
out[i] = DType(val);
}
// mshadow_op version (when used with op_with_req<>)
MSHADOW_XINLINE static int Map() {
return val;
}
};
/*!
* \brief Special-case kernel shortcut for setting to zero and one
*/
using set_zero = set_to_int<0>;
using set_one = set_to_int<1>;
/*!
* \brief Set to immediate scalar value kernel
* \tparam val Scalar immediate
*/
template<bool val>
struct set_to_bool : public tunable {
// mxnet_op version (when used directly with Kernel<>::Launch()) */
template<typename DType>
MSHADOW_XINLINE static void Map(index_t i, DType *out) {
out[i] = DType(val);
}
// mshadow_op version (when used with op_with_req<>)
MSHADOW_XINLINE static int Map() {
return val;
}
};
/*!
* \brief Special-case kernel shortcut for setting to true and false
*/
using set_true = set_to_bool<true>;
using set_false = set_to_bool<false>;
} // namespace mxnet_op
} // namespace op
} // namespace mxnet
#endif // MXNET_OPERATOR_MXNET_OP_H_
|
HannWindow.h | #ifndef _H_HANN_WINDOW_
#define _H_HANN_WINDOW_
#include <cmath>
#include <cstdio>
class HannWindow {
int cnt = 0;
private:
// c standard defind
//#define M_PI (3.14159265358979323846)::
// MATLAB 'pi'
const double MATLAB_pi= 3.141592653589793;
double *hann;
int shift_size;
int frame_size;
public:
inline HannWindow(int _frame_size, int _shift_size);
inline ~HannWindow();
// 2D
inline void Process(double ** buf, int channels);
// 1D - multi channel
inline void Process(double * buf, int channels);
// 1D - single channel
inline void Process(double * buf);
// 2D
inline void WindowWithScaling(double ** buf, int channels);
// 1D - multi channel
inline void WindowWithScaling(double * buf, int channels);
// 1D - single channel
inline void WindowWithScaling(double * buf);
};
inline HannWindow::HannWindow(int _frame_size, int _shift_size) {
int i;
double tmp = 0;
shift_size = _shift_size;
frame_size = _frame_size;
hann = new double[frame_size];
/* Ver 1 */
/*
switch (frame_size / shift_size) {
case 4:
hann[0] = 0.0;
for (i = 1; i < frame_size; ++i)
hann[i] = 0.5 * (1.0 - cos(2.0 * M_PI * (double)i / (double)frame_size));
tmp = sqrt((double)2 / 3);
for (i = 1; i < frame_size; i++)
hann[i] *= tmp;
break;
case 2:
for (i = 0; i < frame_size; i++)
hann[i] = sin(M_PI * (i + 0.5) / frame_size);
break;
}
*/
/* Ver 2 */
// win = hanning(frame_size,'periodic');
for (i = 0; i < frame_size; i++)
hann[i] = 0.5 * (1.0 - cos(2.0 * MATLAB_pi* (i / (double)frame_size)));
// win = win./sqrt(sum(win.^2)/shift_size);
for (i = 0; i < frame_size; i++)
tmp += hann[i] * hann[i];
tmp /= shift_size;
tmp = std::sqrt(tmp);
for (i = 0; i < frame_size; i++)
hann[i] /= tmp;
}
inline HannWindow::~HannWindow() { delete[] hann; }
inline void HannWindow::Process(double **buffer,
int channels) {
cnt++;
int i, j;
for (i = 0; i < channels; i++) {
#pragma omp parallel for
for (j = 0; j < frame_size; j++) {
buffer[i][j] *= hann[j];
}
}
}
inline void HannWindow::Process(double *buffer,
int channels) {
int i, j;
for (i = 0; i < channels; i++) {
#pragma omp parallel for
for (j = 0; j < frame_size; j++) {
buffer[i*(frame_size+2) + j] *= hann[j];
}
}
}
inline void HannWindow::Process(double *buffer){
int j;
for (j = 0; j < frame_size; j++) {
buffer[j] *= hann[j];
}
}
inline void HannWindow::WindowWithScaling(double **buffer,
int channels) {
int i, j;
for (i = 0; i < channels; i++) {
#pragma omp parallel for
for (j = 0; j < frame_size; j++) {
buffer[i][j] *= hann[j];
buffer[i][j] /= 32767.0;
}
}
}
inline void HannWindow::WindowWithScaling(double *buffer){
int j;
for (j = 0; j < frame_size; j++) {
buffer[j] *= hann[j];
buffer[j] /= 32767.0;
}
}
inline void HannWindow::WindowWithScaling(double *buffer,
int channels) {
int i, j;
for (i = 0; i < channels; i++) {
#pragma omp parallel for
for (j = 0; j < frame_size; j++) {
buffer[ i*(frame_size+2) + j] *= hann[j];
buffer[ i*(frame_size+2) + j] /= 32767.0;
}
}
}
#endif
|
vect-aggressive-1.c | /* { dg-require-effective-target vect_condition } */
/* { dg-require-effective-target vect_simd_clones } */
/* { dg-additional-options "-fopenmp-simd" } */
#include "tree-vect.h"
#define N 64
int a[N];
int c[N];
__attribute__ ((noinline)) int
foo (void)
{
int i, res = 0;
#pragma omp simd safelen(8)
for (i = 0; i < N; i++)
{
int t = a[i];
if (c[i] != 0)
if (t != 100 & t > 5)
res += 1;
}
return res;
}
__attribute__ ((noinline)) int
hundred (void)
{
return 100;
}
int main (void)
{
int i;
check_vect ();
for (i = 0; i < N; i++)
{
c[i] = i & 1;
switch (i & 3)
{
case 0:
a[i] = hundred ();
break;
case 1:
a[i] = 1;
break;
default:
a[i] = i + 6;
break;
}
}
if (foo () != 16)
abort ();
return 0;
}
/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
|
tree-vect-data-refs.c | /* Data References Analysis and Manipulation Utilities for Vectorization.
Copyright (C) 2003-2015 Free Software Foundation, Inc.
Contributed by Dorit Naishlos <dorit@il.ibm.com>
and Ira Rosen <irar@il.ibm.com>
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 3, 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 COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "dumpfile.h"
#include "tm.h"
#include "hash-set.h"
#include "machmode.h"
#include "vec.h"
#include "double-int.h"
#include "input.h"
#include "alias.h"
#include "symtab.h"
#include "wide-int.h"
#include "inchash.h"
#include "tree.h"
#include "fold-const.h"
#include "stor-layout.h"
#include "tm_p.h"
#include "target.h"
#include "predict.h"
#include "hard-reg-set.h"
#include "function.h"
#include "dominance.h"
#include "cfg.h"
#include "basic-block.h"
#include "gimple-pretty-print.h"
#include "tree-ssa-alias.h"
#include "internal-fn.h"
#include "tree-eh.h"
#include "gimple-expr.h"
#include "is-a.h"
#include "gimple.h"
#include "gimplify.h"
#include "gimple-iterator.h"
#include "gimplify-me.h"
#include "gimple-ssa.h"
#include "tree-phinodes.h"
#include "ssa-iterators.h"
#include "stringpool.h"
#include "tree-ssanames.h"
#include "tree-ssa-loop-ivopts.h"
#include "tree-ssa-loop-manip.h"
#include "tree-ssa-loop.h"
#include "cfgloop.h"
#include "tree-chrec.h"
#include "tree-scalar-evolution.h"
#include "tree-vectorizer.h"
#include "diagnostic-core.h"
#include "hash-map.h"
#include "plugin-api.h"
#include "ipa-ref.h"
#include "cgraph.h"
/* Need to include rtl.h, expr.h, etc. for optabs. */
#include "hashtab.h"
#include "rtl.h"
#include "flags.h"
#include "statistics.h"
#include "real.h"
#include "fixed-value.h"
#include "insn-config.h"
#include "expmed.h"
#include "dojump.h"
#include "explow.h"
#include "calls.h"
#include "emit-rtl.h"
#include "varasm.h"
#include "stmt.h"
#include "expr.h"
#include "insn-codes.h"
#include "optabs.h"
#include "builtins.h"
/* Return true if load- or store-lanes optab OPTAB is implemented for
COUNT vectors of type VECTYPE. NAME is the name of OPTAB. */
static bool
vect_lanes_optab_supported_p (const char *name, convert_optab optab,
tree vectype, unsigned HOST_WIDE_INT count)
{
machine_mode mode, array_mode;
bool limit_p;
mode = TYPE_MODE (vectype);
limit_p = !targetm.array_mode_supported_p (mode, count);
array_mode = mode_for_size (count * GET_MODE_BITSIZE (mode),
MODE_INT, limit_p);
if (array_mode == BLKmode)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"no array mode for %s[" HOST_WIDE_INT_PRINT_DEC "]\n",
GET_MODE_NAME (mode), count);
return false;
}
if (convert_optab_handler (optab, array_mode, mode) == CODE_FOR_nothing)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"cannot use %s<%s><%s>\n", name,
GET_MODE_NAME (array_mode), GET_MODE_NAME (mode));
return false;
}
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"can use %s<%s><%s>\n", name, GET_MODE_NAME (array_mode),
GET_MODE_NAME (mode));
return true;
}
/* Return the smallest scalar part of STMT.
This is used to determine the vectype of the stmt. We generally set the
vectype according to the type of the result (lhs). For stmts whose
result-type is different than the type of the arguments (e.g., demotion,
promotion), vectype will be reset appropriately (later). Note that we have
to visit the smallest datatype in this function, because that determines the
VF. If the smallest datatype in the loop is present only as the rhs of a
promotion operation - we'd miss it.
Such a case, where a variable of this datatype does not appear in the lhs
anywhere in the loop, can only occur if it's an invariant: e.g.:
'int_x = (int) short_inv', which we'd expect to have been optimized away by
invariant motion. However, we cannot rely on invariant motion to always
take invariants out of the loop, and so in the case of promotion we also
have to check the rhs.
LHS_SIZE_UNIT and RHS_SIZE_UNIT contain the sizes of the corresponding
types. */
tree
vect_get_smallest_scalar_type (gimple stmt, HOST_WIDE_INT *lhs_size_unit,
HOST_WIDE_INT *rhs_size_unit)
{
tree scalar_type = gimple_expr_type (stmt);
HOST_WIDE_INT lhs, rhs;
lhs = rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (scalar_type));
if (is_gimple_assign (stmt)
&& (gimple_assign_cast_p (stmt)
|| gimple_assign_rhs_code (stmt) == WIDEN_MULT_EXPR
|| gimple_assign_rhs_code (stmt) == WIDEN_LSHIFT_EXPR
|| gimple_assign_rhs_code (stmt) == FLOAT_EXPR))
{
tree rhs_type = TREE_TYPE (gimple_assign_rhs1 (stmt));
rhs = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (rhs_type));
if (rhs < lhs)
scalar_type = rhs_type;
}
*lhs_size_unit = lhs;
*rhs_size_unit = rhs;
return scalar_type;
}
/* Insert DDR into LOOP_VINFO list of ddrs that may alias and need to be
tested at run-time. Return TRUE if DDR was successfully inserted.
Return false if versioning is not supported. */
static bool
vect_mark_for_runtime_alias_test (ddr_p ddr, loop_vec_info loop_vinfo)
{
struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
if ((unsigned) PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS) == 0)
return false;
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"mark for run-time aliasing test between ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (DDR_A (ddr)));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (DDR_B (ddr)));
dump_printf (MSG_NOTE, "\n");
}
if (optimize_loop_nest_for_size_p (loop))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning not supported when optimizing"
" for size.\n");
return false;
}
/* FORNOW: We don't support versioning with outer-loop vectorization. */
if (loop->inner)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning not yet supported for outer-loops.\n");
return false;
}
/* FORNOW: We don't support creating runtime alias tests for non-constant
step. */
if (TREE_CODE (DR_STEP (DDR_A (ddr))) != INTEGER_CST
|| TREE_CODE (DR_STEP (DDR_B (ddr))) != INTEGER_CST)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning not yet supported for non-constant "
"step\n");
return false;
}
LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo).safe_push (ddr);
return true;
}
/* Function vect_analyze_data_ref_dependence.
Return TRUE if there (might) exist a dependence between a memory-reference
DRA and a memory-reference DRB. When versioning for alias may check a
dependence at run-time, return FALSE. Adjust *MAX_VF according to
the data dependence. */
static bool
vect_analyze_data_ref_dependence (struct data_dependence_relation *ddr,
loop_vec_info loop_vinfo, int *max_vf)
{
unsigned int i;
struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
struct data_reference *dra = DDR_A (ddr);
struct data_reference *drb = DDR_B (ddr);
stmt_vec_info stmtinfo_a = vinfo_for_stmt (DR_STMT (dra));
stmt_vec_info stmtinfo_b = vinfo_for_stmt (DR_STMT (drb));
lambda_vector dist_v;
unsigned int loop_depth;
/* In loop analysis all data references should be vectorizable. */
if (!STMT_VINFO_VECTORIZABLE (stmtinfo_a)
|| !STMT_VINFO_VECTORIZABLE (stmtinfo_b))
gcc_unreachable ();
/* Independent data accesses. */
if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
return false;
if (dra == drb
|| (DR_IS_READ (dra) && DR_IS_READ (drb)))
return false;
/* Even if we have an anti-dependence then, as the vectorized loop covers at
least two scalar iterations, there is always also a true dependence.
As the vectorizer does not re-order loads and stores we can ignore
the anti-dependence if TBAA can disambiguate both DRs similar to the
case with known negative distance anti-dependences (positive
distance anti-dependences would violate TBAA constraints). */
if (((DR_IS_READ (dra) && DR_IS_WRITE (drb))
|| (DR_IS_WRITE (dra) && DR_IS_READ (drb)))
&& !alias_sets_conflict_p (get_alias_set (DR_REF (dra)),
get_alias_set (DR_REF (drb))))
return false;
/* Unknown data dependence. */
if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
{
/* If user asserted safelen consecutive iterations can be
executed concurrently, assume independence. */
if (loop->safelen >= 2)
{
if (loop->safelen < *max_vf)
*max_vf = loop->safelen;
LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = false;
return false;
}
if (STMT_VINFO_GATHER_P (stmtinfo_a)
|| STMT_VINFO_GATHER_P (stmtinfo_b))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning for alias not supported for: "
"can't determine dependence between ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (dra));
dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return true;
}
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning for alias required: "
"can't determine dependence between ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (dra));
dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
/* Add to list of ddrs that need to be tested at run-time. */
return !vect_mark_for_runtime_alias_test (ddr, loop_vinfo);
}
/* Known data dependence. */
if (DDR_NUM_DIST_VECTS (ddr) == 0)
{
/* If user asserted safelen consecutive iterations can be
executed concurrently, assume independence. */
if (loop->safelen >= 2)
{
if (loop->safelen < *max_vf)
*max_vf = loop->safelen;
LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = false;
return false;
}
if (STMT_VINFO_GATHER_P (stmtinfo_a)
|| STMT_VINFO_GATHER_P (stmtinfo_b))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning for alias not supported for: "
"bad dist vector for ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (dra));
dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return true;
}
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"versioning for alias required: "
"bad dist vector for ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
/* Add to list of ddrs that need to be tested at run-time. */
return !vect_mark_for_runtime_alias_test (ddr, loop_vinfo);
}
loop_depth = index_in_loop_nest (loop->num, DDR_LOOP_NEST (ddr));
FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
{
int dist = dist_v[loop_depth];
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"dependence distance = %d.\n", dist);
if (dist == 0)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"dependence distance == 0 between ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
/* When we perform grouped accesses and perform implicit CSE
by detecting equal accesses and doing disambiguation with
runtime alias tests like for
.. = a[i];
.. = a[i+1];
a[i] = ..;
a[i+1] = ..;
*p = ..;
.. = a[i];
.. = a[i+1];
where we will end up loading { a[i], a[i+1] } once, make
sure that inserting group loads before the first load and
stores after the last store will do the right thing.
Similar for groups like
a[i] = ...;
... = a[i];
a[i+1] = ...;
where loads from the group interleave with the store. */
if (STMT_VINFO_GROUPED_ACCESS (stmtinfo_a)
|| STMT_VINFO_GROUPED_ACCESS (stmtinfo_b))
{
gimple earlier_stmt;
earlier_stmt = get_earlier_stmt (DR_STMT (dra), DR_STMT (drb));
if (DR_IS_WRITE
(STMT_VINFO_DATA_REF (vinfo_for_stmt (earlier_stmt))))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"READ_WRITE dependence in interleaving."
"\n");
return true;
}
}
continue;
}
if (dist > 0 && DDR_REVERSED_P (ddr))
{
/* If DDR_REVERSED_P the order of the data-refs in DDR was
reversed (to make distance vector positive), and the actual
distance is negative. */
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"dependence distance negative.\n");
/* Record a negative dependence distance to later limit the
amount of stmt copying / unrolling we can perform.
Only need to handle read-after-write dependence. */
if (DR_IS_READ (drb)
&& (STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) == 0
|| STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) > (unsigned)dist))
STMT_VINFO_MIN_NEG_DIST (stmtinfo_b) = dist;
continue;
}
if (abs (dist) >= 2
&& abs (dist) < *max_vf)
{
/* The dependence distance requires reduction of the maximal
vectorization factor. */
*max_vf = abs (dist);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"adjusting maximal vectorization factor to %i\n",
*max_vf);
}
if (abs (dist) >= *max_vf)
{
/* Dependence distance does not create dependence, as far as
vectorization is concerned, in this case. */
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"dependence distance >= VF.\n");
continue;
}
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized, possible dependence "
"between data-refs ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_NOTE, "\n");
}
return true;
}
return false;
}
/* Function vect_analyze_data_ref_dependences.
Examine all the data references in the loop, and make sure there do not
exist any data dependences between them. Set *MAX_VF according to
the maximum vectorization factor the data dependences allow. */
bool
vect_analyze_data_ref_dependences (loop_vec_info loop_vinfo, int *max_vf)
{
unsigned int i;
struct data_dependence_relation *ddr;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_analyze_data_ref_dependences ===\n");
LOOP_VINFO_NO_DATA_DEPENDENCIES (loop_vinfo) = true;
if (!compute_all_dependences (LOOP_VINFO_DATAREFS (loop_vinfo),
&LOOP_VINFO_DDRS (loop_vinfo),
LOOP_VINFO_LOOP_NEST (loop_vinfo), true))
return false;
FOR_EACH_VEC_ELT (LOOP_VINFO_DDRS (loop_vinfo), i, ddr)
if (vect_analyze_data_ref_dependence (ddr, loop_vinfo, max_vf))
return false;
return true;
}
/* Function vect_slp_analyze_data_ref_dependence.
Return TRUE if there (might) exist a dependence between a memory-reference
DRA and a memory-reference DRB. When versioning for alias may check a
dependence at run-time, return FALSE. Adjust *MAX_VF according to
the data dependence. */
static bool
vect_slp_analyze_data_ref_dependence (struct data_dependence_relation *ddr)
{
struct data_reference *dra = DDR_A (ddr);
struct data_reference *drb = DDR_B (ddr);
/* We need to check dependences of statements marked as unvectorizable
as well, they still can prohibit vectorization. */
/* Independent data accesses. */
if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
return false;
if (dra == drb)
return false;
/* Read-read is OK. */
if (DR_IS_READ (dra) && DR_IS_READ (drb))
return false;
/* If dra and drb are part of the same interleaving chain consider
them independent. */
if (STMT_VINFO_GROUPED_ACCESS (vinfo_for_stmt (DR_STMT (dra)))
&& (GROUP_FIRST_ELEMENT (vinfo_for_stmt (DR_STMT (dra)))
== GROUP_FIRST_ELEMENT (vinfo_for_stmt (DR_STMT (drb)))))
return false;
/* Unknown data dependence. */
if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"can't determine dependence between ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_MISSED_OPTIMIZATION, " and ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
}
else if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"determined dependence between ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_NOTE, "\n");
}
/* We do not vectorize basic blocks with write-write dependencies. */
if (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))
return true;
/* If we have a read-write dependence check that the load is before the store.
When we vectorize basic blocks, vector load can be only before
corresponding scalar load, and vector store can be only after its
corresponding scalar store. So the order of the acceses is preserved in
case the load is before the store. */
gimple earlier_stmt = get_earlier_stmt (DR_STMT (dra), DR_STMT (drb));
if (DR_IS_READ (STMT_VINFO_DATA_REF (vinfo_for_stmt (earlier_stmt))))
{
/* That only holds for load-store pairs taking part in vectorization. */
if (STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dra)))
&& STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (drb))))
return false;
}
return true;
}
/* Function vect_analyze_data_ref_dependences.
Examine all the data references in the basic-block, and make sure there
do not exist any data dependences between them. Set *MAX_VF according to
the maximum vectorization factor the data dependences allow. */
bool
vect_slp_analyze_data_ref_dependences (bb_vec_info bb_vinfo)
{
struct data_dependence_relation *ddr;
unsigned int i;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_slp_analyze_data_ref_dependences ===\n");
if (!compute_all_dependences (BB_VINFO_DATAREFS (bb_vinfo),
&BB_VINFO_DDRS (bb_vinfo),
vNULL, true))
return false;
FOR_EACH_VEC_ELT (BB_VINFO_DDRS (bb_vinfo), i, ddr)
if (vect_slp_analyze_data_ref_dependence (ddr))
return false;
return true;
}
/* Function vect_compute_data_ref_alignment
Compute the misalignment of the data reference DR.
Output:
1. If during the misalignment computation it is found that the data reference
cannot be vectorized then false is returned.
2. DR_MISALIGNMENT (DR) is defined.
FOR NOW: No analysis is actually performed. Misalignment is calculated
only for trivial cases. TODO. */
static bool
vect_compute_data_ref_alignment (struct data_reference *dr)
{
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
struct loop *loop = NULL;
tree ref = DR_REF (dr);
tree vectype;
tree base, base_addr;
bool base_aligned;
tree misalign;
tree aligned_to;
unsigned HOST_WIDE_INT alignment;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_compute_data_ref_alignment:\n");
if (loop_vinfo)
loop = LOOP_VINFO_LOOP (loop_vinfo);
/* Initialize misalignment to unknown. */
SET_DR_MISALIGNMENT (dr, -1);
/* Strided loads perform only component accesses, misalignment information
is irrelevant for them. */
if (STMT_VINFO_STRIDE_LOAD_P (stmt_info))
return true;
misalign = DR_INIT (dr);
aligned_to = DR_ALIGNED_TO (dr);
base_addr = DR_BASE_ADDRESS (dr);
vectype = STMT_VINFO_VECTYPE (stmt_info);
/* In case the dataref is in an inner-loop of the loop that is being
vectorized (LOOP), we use the base and misalignment information
relative to the outer-loop (LOOP). This is ok only if the misalignment
stays the same throughout the execution of the inner-loop, which is why
we have to check that the stride of the dataref in the inner-loop evenly
divides by the vector size. */
if (loop && nested_in_vect_loop_p (loop, stmt))
{
tree step = DR_STEP (dr);
HOST_WIDE_INT dr_step = TREE_INT_CST_LOW (step);
if (dr_step % GET_MODE_SIZE (TYPE_MODE (vectype)) == 0)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"inner step divides the vector-size.\n");
misalign = STMT_VINFO_DR_INIT (stmt_info);
aligned_to = STMT_VINFO_DR_ALIGNED_TO (stmt_info);
base_addr = STMT_VINFO_DR_BASE_ADDRESS (stmt_info);
}
else
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"inner step doesn't divide the vector-size.\n");
misalign = NULL_TREE;
}
}
/* Similarly, if we're doing basic-block vectorization, we can only use
base and misalignment information relative to an innermost loop if the
misalignment stays the same throughout the execution of the loop.
As above, this is the case if the stride of the dataref evenly divides
by the vector size. */
if (!loop)
{
tree step = DR_STEP (dr);
HOST_WIDE_INT dr_step = TREE_INT_CST_LOW (step);
if (dr_step % GET_MODE_SIZE (TYPE_MODE (vectype)) != 0)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"SLP: step doesn't divide the vector-size.\n");
misalign = NULL_TREE;
}
}
alignment = TYPE_ALIGN_UNIT (vectype);
if ((compare_tree_int (aligned_to, alignment) < 0)
|| !misalign)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Unknown alignment for access: ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, ref);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return true;
}
/* To look at alignment of the base we have to preserve an inner MEM_REF
as that carries alignment information of the actual access. */
base = ref;
while (handled_component_p (base))
base = TREE_OPERAND (base, 0);
if (TREE_CODE (base) == MEM_REF)
base = build2 (MEM_REF, TREE_TYPE (base), base_addr,
build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)), 0));
if (get_object_alignment (base) >= TYPE_ALIGN (vectype))
base_aligned = true;
else
base_aligned = false;
if (!base_aligned)
{
/* Strip an inner MEM_REF to a bare decl if possible. */
if (TREE_CODE (base) == MEM_REF
&& integer_zerop (TREE_OPERAND (base, 1))
&& TREE_CODE (TREE_OPERAND (base, 0)) == ADDR_EXPR)
base = TREE_OPERAND (TREE_OPERAND (base, 0), 0);
if (!vect_can_force_dr_alignment_p (base, TYPE_ALIGN (vectype)))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"can't force alignment of ref: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
dump_printf (MSG_NOTE, "\n");
}
return true;
}
/* Force the alignment of the decl.
NOTE: This is the only change to the code we make during
the analysis phase, before deciding to vectorize the loop. */
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location, "force alignment of ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
dump_printf (MSG_NOTE, "\n");
}
((dataref_aux *)dr->aux)->base_decl = base;
((dataref_aux *)dr->aux)->base_misaligned = true;
}
/* If this is a backward running DR then first access in the larger
vectype actually is N-1 elements before the address in the DR.
Adjust misalign accordingly. */
if (tree_int_cst_sgn (DR_STEP (dr)) < 0)
{
tree offset = ssize_int (TYPE_VECTOR_SUBPARTS (vectype) - 1);
/* DR_STEP(dr) is the same as -TYPE_SIZE of the scalar type,
otherwise we wouldn't be here. */
offset = fold_build2 (MULT_EXPR, ssizetype, offset, DR_STEP (dr));
/* PLUS because DR_STEP was negative. */
misalign = size_binop (PLUS_EXPR, misalign, offset);
}
SET_DR_MISALIGNMENT (dr,
wi::mod_floor (misalign, alignment, SIGNED).to_uhwi ());
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"misalign = %d bytes of ref ", DR_MISALIGNMENT (dr));
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, ref);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return true;
}
/* Function vect_compute_data_refs_alignment
Compute the misalignment of data references in the loop.
Return FALSE if a data reference is found that cannot be vectorized. */
static bool
vect_compute_data_refs_alignment (loop_vec_info loop_vinfo,
bb_vec_info bb_vinfo)
{
vec<data_reference_p> datarefs;
struct data_reference *dr;
unsigned int i;
if (loop_vinfo)
datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
else
datarefs = BB_VINFO_DATAREFS (bb_vinfo);
FOR_EACH_VEC_ELT (datarefs, i, dr)
if (STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr)))
&& !vect_compute_data_ref_alignment (dr))
{
if (bb_vinfo)
{
/* Mark unsupported statement as unvectorizable. */
STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr))) = false;
continue;
}
else
return false;
}
return true;
}
/* Function vect_update_misalignment_for_peel
DR - the data reference whose misalignment is to be adjusted.
DR_PEEL - the data reference whose misalignment is being made
zero in the vector loop by the peel.
NPEEL - the number of iterations in the peel loop if the misalignment
of DR_PEEL is known at compile time. */
static void
vect_update_misalignment_for_peel (struct data_reference *dr,
struct data_reference *dr_peel, int npeel)
{
unsigned int i;
vec<dr_p> same_align_drs;
struct data_reference *current_dr;
int dr_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (DR_REF (dr))));
int dr_peel_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (DR_REF (dr_peel))));
stmt_vec_info stmt_info = vinfo_for_stmt (DR_STMT (dr));
stmt_vec_info peel_stmt_info = vinfo_for_stmt (DR_STMT (dr_peel));
/* For interleaved data accesses the step in the loop must be multiplied by
the size of the interleaving group. */
if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
dr_size *= GROUP_SIZE (vinfo_for_stmt (GROUP_FIRST_ELEMENT (stmt_info)));
if (STMT_VINFO_GROUPED_ACCESS (peel_stmt_info))
dr_peel_size *= GROUP_SIZE (peel_stmt_info);
/* It can be assumed that the data refs with the same alignment as dr_peel
are aligned in the vector loop. */
same_align_drs
= STMT_VINFO_SAME_ALIGN_REFS (vinfo_for_stmt (DR_STMT (dr_peel)));
FOR_EACH_VEC_ELT (same_align_drs, i, current_dr)
{
if (current_dr != dr)
continue;
gcc_assert (DR_MISALIGNMENT (dr) / dr_size ==
DR_MISALIGNMENT (dr_peel) / dr_peel_size);
SET_DR_MISALIGNMENT (dr, 0);
return;
}
if (known_alignment_for_access_p (dr)
&& known_alignment_for_access_p (dr_peel))
{
bool negative = tree_int_cst_compare (DR_STEP (dr), size_zero_node) < 0;
int misal = DR_MISALIGNMENT (dr);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
misal += negative ? -npeel * dr_size : npeel * dr_size;
misal &= (TYPE_ALIGN (vectype) / BITS_PER_UNIT) - 1;
SET_DR_MISALIGNMENT (dr, misal);
return;
}
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location, "Setting misalignment to -1.\n");
SET_DR_MISALIGNMENT (dr, -1);
}
/* Function vect_verify_datarefs_alignment
Return TRUE if all data references in the loop can be
handled with respect to alignment. */
bool
vect_verify_datarefs_alignment (loop_vec_info loop_vinfo, bb_vec_info bb_vinfo)
{
vec<data_reference_p> datarefs;
struct data_reference *dr;
enum dr_alignment_support supportable_dr_alignment;
unsigned int i;
if (loop_vinfo)
datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
else
datarefs = BB_VINFO_DATAREFS (bb_vinfo);
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
if (!STMT_VINFO_RELEVANT_P (stmt_info))
continue;
/* For interleaving, only the alignment of the first access matters.
Skip statements marked as not vectorizable. */
if ((STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& GROUP_FIRST_ELEMENT (stmt_info) != stmt)
|| !STMT_VINFO_VECTORIZABLE (stmt_info))
continue;
/* Strided loads perform only component accesses, alignment is
irrelevant for them. */
if (STMT_VINFO_STRIDE_LOAD_P (stmt_info))
continue;
supportable_dr_alignment = vect_supportable_dr_alignment (dr, false);
if (!supportable_dr_alignment)
{
if (dump_enabled_p ())
{
if (DR_IS_READ (dr))
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: unsupported unaligned load.");
else
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: unsupported unaligned "
"store.");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (dr));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return false;
}
if (supportable_dr_alignment != dr_aligned && dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Vectorizing an unaligned access.\n");
}
return true;
}
/* Given an memory reference EXP return whether its alignment is less
than its size. */
static bool
not_size_aligned (tree exp)
{
if (!tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (exp))))
return true;
return (tree_to_uhwi (TYPE_SIZE (TREE_TYPE (exp)))
> get_object_alignment (exp));
}
/* Function vector_alignment_reachable_p
Return true if vector alignment for DR is reachable by peeling
a few loop iterations. Return false otherwise. */
static bool
vector_alignment_reachable_p (struct data_reference *dr)
{
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
{
/* For interleaved access we peel only if number of iterations in
the prolog loop ({VF - misalignment}), is a multiple of the
number of the interleaved accesses. */
int elem_size, mis_in_elements;
int nelements = TYPE_VECTOR_SUBPARTS (vectype);
/* FORNOW: handle only known alignment. */
if (!known_alignment_for_access_p (dr))
return false;
elem_size = GET_MODE_SIZE (TYPE_MODE (vectype)) / nelements;
mis_in_elements = DR_MISALIGNMENT (dr) / elem_size;
if ((nelements - mis_in_elements) % GROUP_SIZE (stmt_info))
return false;
}
/* If misalignment is known at the compile time then allow peeling
only if natural alignment is reachable through peeling. */
if (known_alignment_for_access_p (dr) && !aligned_access_p (dr))
{
HOST_WIDE_INT elmsize =
int_cst_value (TYPE_SIZE_UNIT (TREE_TYPE (vectype)));
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"data size =" HOST_WIDE_INT_PRINT_DEC, elmsize);
dump_printf (MSG_NOTE,
". misalignment = %d.\n", DR_MISALIGNMENT (dr));
}
if (DR_MISALIGNMENT (dr) % elmsize)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"data size does not divide the misalignment.\n");
return false;
}
}
if (!known_alignment_for_access_p (dr))
{
tree type = TREE_TYPE (DR_REF (dr));
bool is_packed = not_size_aligned (DR_REF (dr));
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Unknown misalignment, is_packed = %d\n",is_packed);
if ((TYPE_USER_ALIGN (type) && !is_packed)
|| targetm.vectorize.vector_alignment_reachable (type, is_packed))
return true;
else
return false;
}
return true;
}
/* Calculate the cost of the memory access represented by DR. */
static void
vect_get_data_access_cost (struct data_reference *dr,
unsigned int *inside_cost,
unsigned int *outside_cost,
stmt_vector_for_cost *body_cost_vec)
{
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
int nunits = TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
int ncopies = vf / nunits;
if (DR_IS_READ (dr))
vect_get_load_cost (dr, ncopies, true, inside_cost, outside_cost,
NULL, body_cost_vec, false);
else
vect_get_store_cost (dr, ncopies, inside_cost, body_cost_vec);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"vect_get_data_access_cost: inside_cost = %d, "
"outside_cost = %d.\n", *inside_cost, *outside_cost);
}
/* Insert DR into peeling hash table with NPEEL as key. */
static void
vect_peeling_hash_insert (loop_vec_info loop_vinfo, struct data_reference *dr,
int npeel)
{
struct _vect_peel_info elem, *slot;
_vect_peel_info **new_slot;
bool supportable_dr_alignment = vect_supportable_dr_alignment (dr, true);
elem.npeel = npeel;
slot = LOOP_VINFO_PEELING_HTAB (loop_vinfo)->find (&elem);
if (slot)
slot->count++;
else
{
slot = XNEW (struct _vect_peel_info);
slot->npeel = npeel;
slot->dr = dr;
slot->count = 1;
new_slot
= LOOP_VINFO_PEELING_HTAB (loop_vinfo)->find_slot (slot, INSERT);
*new_slot = slot;
}
if (!supportable_dr_alignment
&& unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
slot->count += VECT_MAX_COST;
}
/* Traverse peeling hash table to find peeling option that aligns maximum
number of data accesses. */
int
vect_peeling_hash_get_most_frequent (_vect_peel_info **slot,
_vect_peel_extended_info *max)
{
vect_peel_info elem = *slot;
if (elem->count > max->peel_info.count
|| (elem->count == max->peel_info.count
&& max->peel_info.npeel > elem->npeel))
{
max->peel_info.npeel = elem->npeel;
max->peel_info.count = elem->count;
max->peel_info.dr = elem->dr;
}
return 1;
}
/* Traverse peeling hash table and calculate cost for each peeling option.
Find the one with the lowest cost. */
int
vect_peeling_hash_get_lowest_cost (_vect_peel_info **slot,
_vect_peel_extended_info *min)
{
vect_peel_info elem = *slot;
int save_misalignment, dummy;
unsigned int inside_cost = 0, outside_cost = 0, i;
gimple stmt = DR_STMT (elem->dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
struct data_reference *dr;
stmt_vector_for_cost prologue_cost_vec, body_cost_vec, epilogue_cost_vec;
int single_iter_cost;
prologue_cost_vec.create (2);
body_cost_vec.create (2);
epilogue_cost_vec.create (2);
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
stmt = DR_STMT (dr);
stmt_info = vinfo_for_stmt (stmt);
/* For interleaving, only the alignment of the first access
matters. */
if (STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& GROUP_FIRST_ELEMENT (stmt_info) != stmt)
continue;
save_misalignment = DR_MISALIGNMENT (dr);
vect_update_misalignment_for_peel (dr, elem->dr, elem->npeel);
vect_get_data_access_cost (dr, &inside_cost, &outside_cost,
&body_cost_vec);
SET_DR_MISALIGNMENT (dr, save_misalignment);
}
single_iter_cost = vect_get_single_scalar_iteration_cost (loop_vinfo);
outside_cost += vect_get_known_peeling_cost
(loop_vinfo, elem->npeel, &dummy,
/* ??? We use this cost as number of stmts with scalar_stmt cost,
thus divide by that. This introduces rounding errors, thus better
introduce a new cost kind (raw_cost? scalar_iter_cost?). */
single_iter_cost / vect_get_stmt_cost (scalar_stmt),
&prologue_cost_vec, &epilogue_cost_vec);
/* Prologue and epilogue costs are added to the target model later.
These costs depend only on the scalar iteration cost, the
number of peeling iterations finally chosen, and the number of
misaligned statements. So discard the information found here. */
prologue_cost_vec.release ();
epilogue_cost_vec.release ();
if (inside_cost < min->inside_cost
|| (inside_cost == min->inside_cost && outside_cost < min->outside_cost))
{
min->inside_cost = inside_cost;
min->outside_cost = outside_cost;
min->body_cost_vec.release ();
min->body_cost_vec = body_cost_vec;
min->peel_info.dr = elem->dr;
min->peel_info.npeel = elem->npeel;
}
else
body_cost_vec.release ();
return 1;
}
/* Choose best peeling option by traversing peeling hash table and either
choosing an option with the lowest cost (if cost model is enabled) or the
option that aligns as many accesses as possible. */
static struct data_reference *
vect_peeling_hash_choose_best_peeling (loop_vec_info loop_vinfo,
unsigned int *npeel,
stmt_vector_for_cost *body_cost_vec)
{
struct _vect_peel_extended_info res;
res.peel_info.dr = NULL;
res.body_cost_vec = stmt_vector_for_cost ();
if (!unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
{
res.inside_cost = INT_MAX;
res.outside_cost = INT_MAX;
LOOP_VINFO_PEELING_HTAB (loop_vinfo)
->traverse <_vect_peel_extended_info *,
vect_peeling_hash_get_lowest_cost> (&res);
}
else
{
res.peel_info.count = 0;
LOOP_VINFO_PEELING_HTAB (loop_vinfo)
->traverse <_vect_peel_extended_info *,
vect_peeling_hash_get_most_frequent> (&res);
}
*npeel = res.peel_info.npeel;
*body_cost_vec = res.body_cost_vec;
return res.peel_info.dr;
}
/* Function vect_enhance_data_refs_alignment
This pass will use loop versioning and loop peeling in order to enhance
the alignment of data references in the loop.
FOR NOW: we assume that whatever versioning/peeling takes place, only the
original loop is to be vectorized. Any other loops that are created by
the transformations performed in this pass - are not supposed to be
vectorized. This restriction will be relaxed.
This pass will require a cost model to guide it whether to apply peeling
or versioning or a combination of the two. For example, the scheme that
intel uses when given a loop with several memory accesses, is as follows:
choose one memory access ('p') which alignment you want to force by doing
peeling. Then, either (1) generate a loop in which 'p' is aligned and all
other accesses are not necessarily aligned, or (2) use loop versioning to
generate one loop in which all accesses are aligned, and another loop in
which only 'p' is necessarily aligned.
("Automatic Intra-Register Vectorization for the Intel Architecture",
Aart J.C. Bik, Milind Girkar, Paul M. Grey and Ximmin Tian, International
Journal of Parallel Programming, Vol. 30, No. 2, April 2002.)
Devising a cost model is the most critical aspect of this work. It will
guide us on which access to peel for, whether to use loop versioning, how
many versions to create, etc. The cost model will probably consist of
generic considerations as well as target specific considerations (on
powerpc for example, misaligned stores are more painful than misaligned
loads).
Here are the general steps involved in alignment enhancements:
-- original loop, before alignment analysis:
for (i=0; i<N; i++){
x = q[i]; # DR_MISALIGNMENT(q) = unknown
p[i] = y; # DR_MISALIGNMENT(p) = unknown
}
-- After vect_compute_data_refs_alignment:
for (i=0; i<N; i++){
x = q[i]; # DR_MISALIGNMENT(q) = 3
p[i] = y; # DR_MISALIGNMENT(p) = unknown
}
-- Possibility 1: we do loop versioning:
if (p is aligned) {
for (i=0; i<N; i++){ # loop 1A
x = q[i]; # DR_MISALIGNMENT(q) = 3
p[i] = y; # DR_MISALIGNMENT(p) = 0
}
}
else {
for (i=0; i<N; i++){ # loop 1B
x = q[i]; # DR_MISALIGNMENT(q) = 3
p[i] = y; # DR_MISALIGNMENT(p) = unaligned
}
}
-- Possibility 2: we do loop peeling:
for (i = 0; i < 3; i++){ # (scalar loop, not to be vectorized).
x = q[i];
p[i] = y;
}
for (i = 3; i < N; i++){ # loop 2A
x = q[i]; # DR_MISALIGNMENT(q) = 0
p[i] = y; # DR_MISALIGNMENT(p) = unknown
}
-- Possibility 3: combination of loop peeling and versioning:
for (i = 0; i < 3; i++){ # (scalar loop, not to be vectorized).
x = q[i];
p[i] = y;
}
if (p is aligned) {
for (i = 3; i<N; i++){ # loop 3A
x = q[i]; # DR_MISALIGNMENT(q) = 0
p[i] = y; # DR_MISALIGNMENT(p) = 0
}
}
else {
for (i = 3; i<N; i++){ # loop 3B
x = q[i]; # DR_MISALIGNMENT(q) = 0
p[i] = y; # DR_MISALIGNMENT(p) = unaligned
}
}
These loops are later passed to loop_transform to be vectorized. The
vectorizer will use the alignment information to guide the transformation
(whether to generate regular loads/stores, or with special handling for
misalignment). */
bool
vect_enhance_data_refs_alignment (loop_vec_info loop_vinfo)
{
vec<data_reference_p> datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
enum dr_alignment_support supportable_dr_alignment;
struct data_reference *dr0 = NULL, *first_store = NULL;
struct data_reference *dr;
unsigned int i, j;
bool do_peeling = false;
bool do_versioning = false;
bool stat;
gimple stmt;
stmt_vec_info stmt_info;
unsigned int npeel = 0;
bool all_misalignments_unknown = true;
unsigned int vf = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
unsigned possible_npeel_number = 1;
tree vectype;
unsigned int nelements, mis, same_align_drs_max = 0;
stmt_vector_for_cost body_cost_vec = stmt_vector_for_cost ();
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_enhance_data_refs_alignment ===\n");
/* While cost model enhancements are expected in the future, the high level
view of the code at this time is as follows:
A) If there is a misaligned access then see if peeling to align
this access can make all data references satisfy
vect_supportable_dr_alignment. If so, update data structures
as needed and return true.
B) If peeling wasn't possible and there is a data reference with an
unknown misalignment that does not satisfy vect_supportable_dr_alignment
then see if loop versioning checks can be used to make all data
references satisfy vect_supportable_dr_alignment. If so, update
data structures as needed and return true.
C) If neither peeling nor versioning were successful then return false if
any data reference does not satisfy vect_supportable_dr_alignment.
D) Return true (all data references satisfy vect_supportable_dr_alignment).
Note, Possibility 3 above (which is peeling and versioning together) is not
being done at this time. */
/* (1) Peeling to force alignment. */
/* (1.1) Decide whether to perform peeling, and how many iterations to peel:
Considerations:
+ How many accesses will become aligned due to the peeling
- How many accesses will become unaligned due to the peeling,
and the cost of misaligned accesses.
- The cost of peeling (the extra runtime checks, the increase
in code size). */
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
stmt = DR_STMT (dr);
stmt_info = vinfo_for_stmt (stmt);
if (!STMT_VINFO_RELEVANT_P (stmt_info))
continue;
/* For interleaving, only the alignment of the first access
matters. */
if (STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& GROUP_FIRST_ELEMENT (stmt_info) != stmt)
continue;
/* For invariant accesses there is nothing to enhance. */
if (integer_zerop (DR_STEP (dr)))
continue;
/* Strided loads perform only component accesses, alignment is
irrelevant for them. */
if (STMT_VINFO_STRIDE_LOAD_P (stmt_info))
continue;
supportable_dr_alignment = vect_supportable_dr_alignment (dr, true);
do_peeling = vector_alignment_reachable_p (dr);
if (do_peeling)
{
if (known_alignment_for_access_p (dr))
{
unsigned int npeel_tmp;
bool negative = tree_int_cst_compare (DR_STEP (dr),
size_zero_node) < 0;
/* Save info about DR in the hash table. */
if (!LOOP_VINFO_PEELING_HTAB (loop_vinfo))
LOOP_VINFO_PEELING_HTAB (loop_vinfo)
= new hash_table<peel_info_hasher> (1);
vectype = STMT_VINFO_VECTYPE (stmt_info);
nelements = TYPE_VECTOR_SUBPARTS (vectype);
mis = DR_MISALIGNMENT (dr) / GET_MODE_SIZE (TYPE_MODE (
TREE_TYPE (DR_REF (dr))));
npeel_tmp = (negative
? (mis - nelements) : (nelements - mis))
& (nelements - 1);
/* For multiple types, it is possible that the bigger type access
will have more than one peeling option. E.g., a loop with two
types: one of size (vector size / 4), and the other one of
size (vector size / 8). Vectorization factor will 8. If both
access are misaligned by 3, the first one needs one scalar
iteration to be aligned, and the second one needs 5. But the
the first one will be aligned also by peeling 5 scalar
iterations, and in that case both accesses will be aligned.
Hence, except for the immediate peeling amount, we also want
to try to add full vector size, while we don't exceed
vectorization factor.
We do this automtically for cost model, since we calculate cost
for every peeling option. */
if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
possible_npeel_number = vf /nelements;
/* Handle the aligned case. We may decide to align some other
access, making DR unaligned. */
if (DR_MISALIGNMENT (dr) == 0)
{
npeel_tmp = 0;
if (unlimited_cost_model (LOOP_VINFO_LOOP (loop_vinfo)))
possible_npeel_number++;
}
for (j = 0; j < possible_npeel_number; j++)
{
gcc_assert (npeel_tmp <= vf);
vect_peeling_hash_insert (loop_vinfo, dr, npeel_tmp);
npeel_tmp += nelements;
}
all_misalignments_unknown = false;
/* Data-ref that was chosen for the case that all the
misalignments are unknown is not relevant anymore, since we
have a data-ref with known alignment. */
dr0 = NULL;
}
else
{
/* If we don't know any misalignment values, we prefer
peeling for data-ref that has the maximum number of data-refs
with the same alignment, unless the target prefers to align
stores over load. */
if (all_misalignments_unknown)
{
unsigned same_align_drs
= STMT_VINFO_SAME_ALIGN_REFS (stmt_info).length ();
if (!dr0
|| same_align_drs_max < same_align_drs)
{
same_align_drs_max = same_align_drs;
dr0 = dr;
}
/* For data-refs with the same number of related
accesses prefer the one where the misalign
computation will be invariant in the outermost loop. */
else if (same_align_drs_max == same_align_drs)
{
struct loop *ivloop0, *ivloop;
ivloop0 = outermost_invariant_loop_for_expr
(loop, DR_BASE_ADDRESS (dr0));
ivloop = outermost_invariant_loop_for_expr
(loop, DR_BASE_ADDRESS (dr));
if ((ivloop && !ivloop0)
|| (ivloop && ivloop0
&& flow_loop_nested_p (ivloop, ivloop0)))
dr0 = dr;
}
if (!first_store && DR_IS_WRITE (dr))
first_store = dr;
}
/* If there are both known and unknown misaligned accesses in the
loop, we choose peeling amount according to the known
accesses. */
if (!supportable_dr_alignment)
{
dr0 = dr;
if (!first_store && DR_IS_WRITE (dr))
first_store = dr;
}
}
}
else
{
if (!aligned_access_p (dr))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"vector alignment may not be reachable\n");
break;
}
}
}
/* Check if we can possibly peel the loop. */
if (!vect_can_advance_ivs_p (loop_vinfo)
|| !slpeel_can_duplicate_loop_p (loop, single_exit (loop)))
do_peeling = false;
/* If we don't know how many times the peeling loop will run
assume it will run VF-1 times and disable peeling if the remaining
iters are less than the vectorization factor. */
if (do_peeling
&& all_misalignments_unknown
&& LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
&& (LOOP_VINFO_INT_NITERS (loop_vinfo)
< 2 * (unsigned) LOOP_VINFO_VECT_FACTOR (loop_vinfo) - 1))
do_peeling = false;
if (do_peeling
&& all_misalignments_unknown
&& vect_supportable_dr_alignment (dr0, false))
{
/* Check if the target requires to prefer stores over loads, i.e., if
misaligned stores are more expensive than misaligned loads (taking
drs with same alignment into account). */
if (first_store && DR_IS_READ (dr0))
{
unsigned int load_inside_cost = 0, load_outside_cost = 0;
unsigned int store_inside_cost = 0, store_outside_cost = 0;
unsigned int load_inside_penalty = 0, load_outside_penalty = 0;
unsigned int store_inside_penalty = 0, store_outside_penalty = 0;
stmt_vector_for_cost dummy;
dummy.create (2);
vect_get_data_access_cost (dr0, &load_inside_cost, &load_outside_cost,
&dummy);
vect_get_data_access_cost (first_store, &store_inside_cost,
&store_outside_cost, &dummy);
dummy.release ();
/* Calculate the penalty for leaving FIRST_STORE unaligned (by
aligning the load DR0). */
load_inside_penalty = store_inside_cost;
load_outside_penalty = store_outside_cost;
for (i = 0;
STMT_VINFO_SAME_ALIGN_REFS (vinfo_for_stmt (
DR_STMT (first_store))).iterate (i, &dr);
i++)
if (DR_IS_READ (dr))
{
load_inside_penalty += load_inside_cost;
load_outside_penalty += load_outside_cost;
}
else
{
load_inside_penalty += store_inside_cost;
load_outside_penalty += store_outside_cost;
}
/* Calculate the penalty for leaving DR0 unaligned (by
aligning the FIRST_STORE). */
store_inside_penalty = load_inside_cost;
store_outside_penalty = load_outside_cost;
for (i = 0;
STMT_VINFO_SAME_ALIGN_REFS (vinfo_for_stmt (
DR_STMT (dr0))).iterate (i, &dr);
i++)
if (DR_IS_READ (dr))
{
store_inside_penalty += load_inside_cost;
store_outside_penalty += load_outside_cost;
}
else
{
store_inside_penalty += store_inside_cost;
store_outside_penalty += store_outside_cost;
}
if (load_inside_penalty > store_inside_penalty
|| (load_inside_penalty == store_inside_penalty
&& load_outside_penalty > store_outside_penalty))
dr0 = first_store;
}
/* In case there are only loads with different unknown misalignments, use
peeling only if it may help to align other accesses in the loop. */
if (!first_store
&& !STMT_VINFO_SAME_ALIGN_REFS (
vinfo_for_stmt (DR_STMT (dr0))).length ()
&& vect_supportable_dr_alignment (dr0, false)
!= dr_unaligned_supported)
do_peeling = false;
}
if (do_peeling && !dr0)
{
/* Peeling is possible, but there is no data access that is not supported
unless aligned. So we try to choose the best possible peeling. */
/* We should get here only if there are drs with known misalignment. */
gcc_assert (!all_misalignments_unknown);
/* Choose the best peeling from the hash table. */
dr0 = vect_peeling_hash_choose_best_peeling (loop_vinfo, &npeel,
&body_cost_vec);
if (!dr0 || !npeel)
do_peeling = false;
/* If peeling by npeel will result in a remaining loop not iterating
enough to be vectorized then do not peel. */
if (do_peeling
&& LOOP_VINFO_NITERS_KNOWN_P (loop_vinfo)
&& (LOOP_VINFO_INT_NITERS (loop_vinfo)
< LOOP_VINFO_VECT_FACTOR (loop_vinfo) + npeel))
do_peeling = false;
}
if (do_peeling)
{
stmt = DR_STMT (dr0);
stmt_info = vinfo_for_stmt (stmt);
vectype = STMT_VINFO_VECTYPE (stmt_info);
nelements = TYPE_VECTOR_SUBPARTS (vectype);
if (known_alignment_for_access_p (dr0))
{
bool negative = tree_int_cst_compare (DR_STEP (dr0),
size_zero_node) < 0;
if (!npeel)
{
/* Since it's known at compile time, compute the number of
iterations in the peeled loop (the peeling factor) for use in
updating DR_MISALIGNMENT values. The peeling factor is the
vectorization factor minus the misalignment as an element
count. */
mis = DR_MISALIGNMENT (dr0);
mis /= GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (DR_REF (dr0))));
npeel = ((negative ? mis - nelements : nelements - mis)
& (nelements - 1));
}
/* For interleaved data access every iteration accesses all the
members of the group, therefore we divide the number of iterations
by the group size. */
stmt_info = vinfo_for_stmt (DR_STMT (dr0));
if (STMT_VINFO_GROUPED_ACCESS (stmt_info))
npeel /= GROUP_SIZE (stmt_info);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Try peeling by %d\n", npeel);
}
/* Ensure that all data refs can be vectorized after the peel. */
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
int save_misalignment;
if (dr == dr0)
continue;
stmt = DR_STMT (dr);
stmt_info = vinfo_for_stmt (stmt);
/* For interleaving, only the alignment of the first access
matters. */
if (STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& GROUP_FIRST_ELEMENT (stmt_info) != stmt)
continue;
/* Strided loads perform only component accesses, alignment is
irrelevant for them. */
if (STMT_VINFO_STRIDE_LOAD_P (stmt_info))
continue;
save_misalignment = DR_MISALIGNMENT (dr);
vect_update_misalignment_for_peel (dr, dr0, npeel);
supportable_dr_alignment = vect_supportable_dr_alignment (dr, false);
SET_DR_MISALIGNMENT (dr, save_misalignment);
if (!supportable_dr_alignment)
{
do_peeling = false;
break;
}
}
if (do_peeling && known_alignment_for_access_p (dr0) && npeel == 0)
{
stat = vect_verify_datarefs_alignment (loop_vinfo, NULL);
if (!stat)
do_peeling = false;
else
{
body_cost_vec.release ();
return stat;
}
}
if (do_peeling)
{
unsigned max_allowed_peel
= PARAM_VALUE (PARAM_VECT_MAX_PEELING_FOR_ALIGNMENT);
if (max_allowed_peel != (unsigned)-1)
{
unsigned max_peel = npeel;
if (max_peel == 0)
{
gimple dr_stmt = DR_STMT (dr0);
stmt_vec_info vinfo = vinfo_for_stmt (dr_stmt);
tree vtype = STMT_VINFO_VECTYPE (vinfo);
max_peel = TYPE_VECTOR_SUBPARTS (vtype) - 1;
}
if (max_peel > max_allowed_peel)
{
do_peeling = false;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Disable peeling, max peels reached: %d\n", max_peel);
}
}
}
if (do_peeling)
{
/* (1.2) Update the DR_MISALIGNMENT of each data reference DR_i.
If the misalignment of DR_i is identical to that of dr0 then set
DR_MISALIGNMENT (DR_i) to zero. If the misalignment of DR_i and
dr0 are known at compile time then increment DR_MISALIGNMENT (DR_i)
by the peeling factor times the element size of DR_i (MOD the
vectorization factor times the size). Otherwise, the
misalignment of DR_i must be set to unknown. */
FOR_EACH_VEC_ELT (datarefs, i, dr)
if (dr != dr0)
vect_update_misalignment_for_peel (dr, dr0, npeel);
LOOP_VINFO_UNALIGNED_DR (loop_vinfo) = dr0;
if (npeel)
LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo) = npeel;
else
LOOP_VINFO_PEELING_FOR_ALIGNMENT (loop_vinfo)
= DR_MISALIGNMENT (dr0);
SET_DR_MISALIGNMENT (dr0, 0);
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"Alignment of access forced using peeling.\n");
dump_printf_loc (MSG_NOTE, vect_location,
"Peeling for alignment will be applied.\n");
}
/* The inside-loop cost will be accounted for in vectorizable_load
and vectorizable_store correctly with adjusted alignments.
Drop the body_cst_vec on the floor here. */
body_cost_vec.release ();
stat = vect_verify_datarefs_alignment (loop_vinfo, NULL);
gcc_assert (stat);
return stat;
}
}
body_cost_vec.release ();
/* (2) Versioning to force alignment. */
/* Try versioning if:
1) optimize loop for speed
2) there is at least one unsupported misaligned data ref with an unknown
misalignment, and
3) all misaligned data refs with a known misalignment are supported, and
4) the number of runtime alignment checks is within reason. */
do_versioning =
optimize_loop_nest_for_speed_p (loop)
&& (!loop->inner); /* FORNOW */
if (do_versioning)
{
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
stmt = DR_STMT (dr);
stmt_info = vinfo_for_stmt (stmt);
/* For interleaving, only the alignment of the first access
matters. */
if (aligned_access_p (dr)
|| (STMT_VINFO_GROUPED_ACCESS (stmt_info)
&& GROUP_FIRST_ELEMENT (stmt_info) != stmt))
continue;
/* Strided loads perform only component accesses, alignment is
irrelevant for them. */
if (STMT_VINFO_STRIDE_LOAD_P (stmt_info))
continue;
supportable_dr_alignment = vect_supportable_dr_alignment (dr, false);
if (!supportable_dr_alignment)
{
gimple stmt;
int mask;
tree vectype;
if (known_alignment_for_access_p (dr)
|| LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).length ()
>= (unsigned) PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIGNMENT_CHECKS))
{
do_versioning = false;
break;
}
stmt = DR_STMT (dr);
vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (stmt));
gcc_assert (vectype);
/* The rightmost bits of an aligned address must be zeros.
Construct the mask needed for this test. For example,
GET_MODE_SIZE for the vector mode V4SI is 16 bytes so the
mask must be 15 = 0xf. */
mask = GET_MODE_SIZE (TYPE_MODE (vectype)) - 1;
/* FORNOW: use the same mask to test all potentially unaligned
references in the loop. The vectorizer currently supports
a single vector size, see the reference to
GET_MODE_NUNITS (TYPE_MODE (vectype)) where the
vectorization factor is computed. */
gcc_assert (!LOOP_VINFO_PTR_MASK (loop_vinfo)
|| LOOP_VINFO_PTR_MASK (loop_vinfo) == mask);
LOOP_VINFO_PTR_MASK (loop_vinfo) = mask;
LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).safe_push (
DR_STMT (dr));
}
}
/* Versioning requires at least one misaligned data reference. */
if (!LOOP_REQUIRES_VERSIONING_FOR_ALIGNMENT (loop_vinfo))
do_versioning = false;
else if (!do_versioning)
LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo).truncate (0);
}
if (do_versioning)
{
vec<gimple> may_misalign_stmts
= LOOP_VINFO_MAY_MISALIGN_STMTS (loop_vinfo);
gimple stmt;
/* It can now be assumed that the data references in the statements
in LOOP_VINFO_MAY_MISALIGN_STMTS will be aligned in the version
of the loop being vectorized. */
FOR_EACH_VEC_ELT (may_misalign_stmts, i, stmt)
{
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
dr = STMT_VINFO_DATA_REF (stmt_info);
SET_DR_MISALIGNMENT (dr, 0);
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Alignment of access forced using versioning.\n");
}
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Versioning for alignment will be applied.\n");
/* Peeling and versioning can't be done together at this time. */
gcc_assert (! (do_peeling && do_versioning));
stat = vect_verify_datarefs_alignment (loop_vinfo, NULL);
gcc_assert (stat);
return stat;
}
/* This point is reached if neither peeling nor versioning is being done. */
gcc_assert (! (do_peeling || do_versioning));
stat = vect_verify_datarefs_alignment (loop_vinfo, NULL);
return stat;
}
/* Function vect_find_same_alignment_drs.
Update group and alignment relations according to the chosen
vectorization factor. */
static void
vect_find_same_alignment_drs (struct data_dependence_relation *ddr,
loop_vec_info loop_vinfo)
{
unsigned int i;
struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
int vectorization_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
struct data_reference *dra = DDR_A (ddr);
struct data_reference *drb = DDR_B (ddr);
stmt_vec_info stmtinfo_a = vinfo_for_stmt (DR_STMT (dra));
stmt_vec_info stmtinfo_b = vinfo_for_stmt (DR_STMT (drb));
int dra_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (DR_REF (dra))));
int drb_size = GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (DR_REF (drb))));
lambda_vector dist_v;
unsigned int loop_depth;
if (DDR_ARE_DEPENDENT (ddr) == chrec_known)
return;
if (dra == drb)
return;
if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
return;
/* Loop-based vectorization and known data dependence. */
if (DDR_NUM_DIST_VECTS (ddr) == 0)
return;
/* Data-dependence analysis reports a distance vector of zero
for data-references that overlap only in the first iteration
but have different sign step (see PR45764).
So as a sanity check require equal DR_STEP. */
if (!operand_equal_p (DR_STEP (dra), DR_STEP (drb), 0))
return;
loop_depth = index_in_loop_nest (loop->num, DDR_LOOP_NEST (ddr));
FOR_EACH_VEC_ELT (DDR_DIST_VECTS (ddr), i, dist_v)
{
int dist = dist_v[loop_depth];
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"dependence distance = %d.\n", dist);
/* Same loop iteration. */
if (dist == 0
|| (dist % vectorization_factor == 0 && dra_size == drb_size))
{
/* Two references with distance zero have the same alignment. */
STMT_VINFO_SAME_ALIGN_REFS (stmtinfo_a).safe_push (drb);
STMT_VINFO_SAME_ALIGN_REFS (stmtinfo_b).safe_push (dra);
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"accesses have the same alignment.\n");
dump_printf (MSG_NOTE,
"dependence distance modulo vf == 0 between ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_NOTE, "\n");
}
}
}
}
/* Function vect_analyze_data_refs_alignment
Analyze the alignment of the data-references in the loop.
Return FALSE if a data reference is found that cannot be vectorized. */
bool
vect_analyze_data_refs_alignment (loop_vec_info loop_vinfo,
bb_vec_info bb_vinfo)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_analyze_data_refs_alignment ===\n");
/* Mark groups of data references with same alignment using
data dependence information. */
if (loop_vinfo)
{
vec<ddr_p> ddrs = LOOP_VINFO_DDRS (loop_vinfo);
struct data_dependence_relation *ddr;
unsigned int i;
FOR_EACH_VEC_ELT (ddrs, i, ddr)
vect_find_same_alignment_drs (ddr, loop_vinfo);
}
if (!vect_compute_data_refs_alignment (loop_vinfo, bb_vinfo))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: can't calculate alignment "
"for data ref.\n");
return false;
}
return true;
}
/* Analyze groups of accesses: check that DR belongs to a group of
accesses of legal size, step, etc. Detect gaps, single element
interleaving, and other special cases. Set grouped access info.
Collect groups of strided stores for further use in SLP analysis. */
static bool
vect_analyze_group_access (struct data_reference *dr)
{
tree step = DR_STEP (dr);
tree scalar_type = TREE_TYPE (DR_REF (dr));
HOST_WIDE_INT type_size = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (scalar_type));
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
HOST_WIDE_INT dr_step = TREE_INT_CST_LOW (step);
HOST_WIDE_INT groupsize, last_accessed_element = 1;
bool slp_impossible = false;
struct loop *loop = NULL;
if (loop_vinfo)
loop = LOOP_VINFO_LOOP (loop_vinfo);
/* For interleaving, GROUPSIZE is STEP counted in elements, i.e., the
size of the interleaving group (including gaps). */
groupsize = absu_hwi (dr_step) / type_size;
/* Not consecutive access is possible only if it is a part of interleaving. */
if (!GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)))
{
/* Check if it this DR is a part of interleaving, and is a single
element of the group that is accessed in the loop. */
/* Gaps are supported only for loads. STEP must be a multiple of the type
size. The size of the group must be a power of 2. */
if (DR_IS_READ (dr)
&& (dr_step % type_size) == 0
&& groupsize > 0
&& exact_log2 (groupsize) != -1)
{
GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)) = stmt;
GROUP_SIZE (vinfo_for_stmt (stmt)) = groupsize;
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"Detected single element interleaving ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dr));
dump_printf (MSG_NOTE, " step ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, step);
dump_printf (MSG_NOTE, "\n");
}
if (loop_vinfo)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Data access with gaps requires scalar "
"epilogue loop\n");
if (loop->inner)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Peeling for outer loop is not"
" supported\n");
return false;
}
LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = true;
}
return true;
}
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not consecutive access ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
{
/* Mark the statement as unvectorizable. */
STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr))) = false;
return true;
}
return false;
}
if (GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)) == stmt)
{
/* First stmt in the interleaving chain. Check the chain. */
gimple next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (stmt));
struct data_reference *data_ref = dr;
unsigned int count = 1;
tree prev_init = DR_INIT (data_ref);
gimple prev = stmt;
HOST_WIDE_INT diff, gaps = 0;
unsigned HOST_WIDE_INT count_in_bytes;
while (next)
{
/* Skip same data-refs. In case that two or more stmts share
data-ref (supported only for loads), we vectorize only the first
stmt, and the rest get their vectorized loads from the first
one. */
if (!tree_int_cst_compare (DR_INIT (data_ref),
DR_INIT (STMT_VINFO_DATA_REF (
vinfo_for_stmt (next)))))
{
if (DR_IS_WRITE (data_ref))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Two store stmts share the same dr.\n");
return false;
}
/* For load use the same data-ref load. */
GROUP_SAME_DR_STMT (vinfo_for_stmt (next)) = prev;
prev = next;
next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
continue;
}
prev = next;
data_ref = STMT_VINFO_DATA_REF (vinfo_for_stmt (next));
/* All group members have the same STEP by construction. */
gcc_checking_assert (operand_equal_p (DR_STEP (data_ref), step, 0));
/* Check that the distance between two accesses is equal to the type
size. Otherwise, we have gaps. */
diff = (TREE_INT_CST_LOW (DR_INIT (data_ref))
- TREE_INT_CST_LOW (prev_init)) / type_size;
if (diff != 1)
{
/* FORNOW: SLP of accesses with gaps is not supported. */
slp_impossible = true;
if (DR_IS_WRITE (data_ref))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"interleaved store with gaps\n");
return false;
}
gaps += diff - 1;
}
last_accessed_element += diff;
/* Store the gap from the previous member of the group. If there is no
gap in the access, GROUP_GAP is always 1. */
GROUP_GAP (vinfo_for_stmt (next)) = diff;
prev_init = DR_INIT (data_ref);
next = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next));
/* Count the number of data-refs in the chain. */
count++;
}
/* COUNT is the number of accesses found, we multiply it by the size of
the type to get COUNT_IN_BYTES. */
count_in_bytes = type_size * count;
/* Check that the size of the interleaving (including gaps) is not
greater than STEP. */
if (dr_step != 0
&& absu_hwi (dr_step) < count_in_bytes + gaps * type_size)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"interleaving size is greater than step for ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
DR_REF (dr));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return false;
}
/* Check that the size of the interleaving is equal to STEP for stores,
i.e., that there are no gaps. */
if (dr_step != 0
&& absu_hwi (dr_step) != count_in_bytes)
{
if (DR_IS_READ (dr))
{
slp_impossible = true;
/* There is a gap after the last load in the group. This gap is a
difference between the groupsize and the number of elements.
When there is no gap, this difference should be 0. */
GROUP_GAP (vinfo_for_stmt (stmt)) = groupsize - count;
}
else
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"interleaved store with gaps\n");
return false;
}
}
/* Check that STEP is a multiple of type size. */
if (dr_step != 0
&& (dr_step % type_size) != 0)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"step is not a multiple of type size: step ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM, step);
dump_printf (MSG_MISSED_OPTIMIZATION, " size ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_SLIM,
TYPE_SIZE_UNIT (scalar_type));
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return false;
}
if (groupsize == 0)
groupsize = count;
GROUP_SIZE (vinfo_for_stmt (stmt)) = groupsize;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"Detected interleaving of size %d\n", (int)groupsize);
/* SLP: create an SLP data structure for every interleaving group of
stores for further analysis in vect_analyse_slp. */
if (DR_IS_WRITE (dr) && !slp_impossible)
{
if (loop_vinfo)
LOOP_VINFO_GROUPED_STORES (loop_vinfo).safe_push (stmt);
if (bb_vinfo)
BB_VINFO_GROUPED_STORES (bb_vinfo).safe_push (stmt);
}
/* There is a gap in the end of the group. */
if (groupsize - last_accessed_element > 0 && loop_vinfo)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Data access with gaps requires scalar "
"epilogue loop\n");
if (loop->inner)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"Peeling for outer loop is not supported\n");
return false;
}
LOOP_VINFO_PEELING_FOR_GAPS (loop_vinfo) = true;
}
}
return true;
}
/* Analyze the access pattern of the data-reference DR.
In case of non-consecutive accesses call vect_analyze_group_access() to
analyze groups of accesses. */
static bool
vect_analyze_data_ref_access (struct data_reference *dr)
{
tree step = DR_STEP (dr);
tree scalar_type = TREE_TYPE (DR_REF (dr));
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
struct loop *loop = NULL;
if (loop_vinfo)
loop = LOOP_VINFO_LOOP (loop_vinfo);
if (loop_vinfo && !step)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"bad data-ref access in loop\n");
return false;
}
/* Allow invariant loads in not nested loops. */
if (loop_vinfo && integer_zerop (step))
{
GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)) = NULL;
if (nested_in_vect_loop_p (loop, stmt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"zero step in inner loop of nest\n");
return false;
}
return DR_IS_READ (dr);
}
if (loop && nested_in_vect_loop_p (loop, stmt))
{
/* Interleaved accesses are not yet supported within outer-loop
vectorization for references in the inner-loop. */
GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)) = NULL;
/* For the rest of the analysis we use the outer-loop step. */
step = STMT_VINFO_DR_STEP (stmt_info);
if (integer_zerop (step))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"zero step in outer loop.\n");
if (DR_IS_READ (dr))
return true;
else
return false;
}
}
/* Consecutive? */
if (TREE_CODE (step) == INTEGER_CST)
{
HOST_WIDE_INT dr_step = TREE_INT_CST_LOW (step);
if (!tree_int_cst_compare (step, TYPE_SIZE_UNIT (scalar_type))
|| (dr_step < 0
&& !compare_tree_int (TYPE_SIZE_UNIT (scalar_type), -dr_step)))
{
/* Mark that it is not interleaving. */
GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt)) = NULL;
return true;
}
}
if (loop && nested_in_vect_loop_p (loop, stmt))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"grouped access in outer loop.\n");
return false;
}
/* Assume this is a DR handled by non-constant strided load case. */
if (TREE_CODE (step) != INTEGER_CST)
return STMT_VINFO_STRIDE_LOAD_P (stmt_info);
/* Not consecutive access - check if it's a part of interleaving group. */
return vect_analyze_group_access (dr);
}
/* A helper function used in the comparator function to sort data
references. T1 and T2 are two data references to be compared.
The function returns -1, 0, or 1. */
static int
compare_tree (tree t1, tree t2)
{
int i, cmp;
enum tree_code code;
char tclass;
if (t1 == t2)
return 0;
if (t1 == NULL)
return -1;
if (t2 == NULL)
return 1;
if (TREE_CODE (t1) != TREE_CODE (t2))
return TREE_CODE (t1) < TREE_CODE (t2) ? -1 : 1;
code = TREE_CODE (t1);
switch (code)
{
/* For const values, we can just use hash values for comparisons. */
case INTEGER_CST:
case REAL_CST:
case FIXED_CST:
case STRING_CST:
case COMPLEX_CST:
case VECTOR_CST:
{
hashval_t h1 = iterative_hash_expr (t1, 0);
hashval_t h2 = iterative_hash_expr (t2, 0);
if (h1 != h2)
return h1 < h2 ? -1 : 1;
break;
}
case SSA_NAME:
cmp = compare_tree (SSA_NAME_VAR (t1), SSA_NAME_VAR (t2));
if (cmp != 0)
return cmp;
if (SSA_NAME_VERSION (t1) != SSA_NAME_VERSION (t2))
return SSA_NAME_VERSION (t1) < SSA_NAME_VERSION (t2) ? -1 : 1;
break;
default:
tclass = TREE_CODE_CLASS (code);
/* For var-decl, we could compare their UIDs. */
if (tclass == tcc_declaration)
{
if (DECL_UID (t1) != DECL_UID (t2))
return DECL_UID (t1) < DECL_UID (t2) ? -1 : 1;
break;
}
/* For expressions with operands, compare their operands recursively. */
for (i = TREE_OPERAND_LENGTH (t1) - 1; i >= 0; --i)
{
cmp = compare_tree (TREE_OPERAND (t1, i), TREE_OPERAND (t2, i));
if (cmp != 0)
return cmp;
}
}
return 0;
}
/* Compare two data-references DRA and DRB to group them into chunks
suitable for grouping. */
static int
dr_group_sort_cmp (const void *dra_, const void *drb_)
{
data_reference_p dra = *(data_reference_p *)const_cast<void *>(dra_);
data_reference_p drb = *(data_reference_p *)const_cast<void *>(drb_);
int cmp;
/* Stabilize sort. */
if (dra == drb)
return 0;
/* Ordering of DRs according to base. */
if (!operand_equal_p (DR_BASE_ADDRESS (dra), DR_BASE_ADDRESS (drb), 0))
{
cmp = compare_tree (DR_BASE_ADDRESS (dra), DR_BASE_ADDRESS (drb));
if (cmp != 0)
return cmp;
}
/* And according to DR_OFFSET. */
if (!dr_equal_offsets_p (dra, drb))
{
cmp = compare_tree (DR_OFFSET (dra), DR_OFFSET (drb));
if (cmp != 0)
return cmp;
}
/* Put reads before writes. */
if (DR_IS_READ (dra) != DR_IS_READ (drb))
return DR_IS_READ (dra) ? -1 : 1;
/* Then sort after access size. */
if (!operand_equal_p (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dra))),
TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (drb))), 0))
{
cmp = compare_tree (TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dra))),
TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (drb))));
if (cmp != 0)
return cmp;
}
/* And after step. */
if (!operand_equal_p (DR_STEP (dra), DR_STEP (drb), 0))
{
cmp = compare_tree (DR_STEP (dra), DR_STEP (drb));
if (cmp != 0)
return cmp;
}
/* Then sort after DR_INIT. In case of identical DRs sort after stmt UID. */
cmp = tree_int_cst_compare (DR_INIT (dra), DR_INIT (drb));
if (cmp == 0)
return gimple_uid (DR_STMT (dra)) < gimple_uid (DR_STMT (drb)) ? -1 : 1;
return cmp;
}
/* Function vect_analyze_data_ref_accesses.
Analyze the access pattern of all the data references in the loop.
FORNOW: the only access pattern that is considered vectorizable is a
simple step 1 (consecutive) access.
FORNOW: handle only arrays and pointer accesses. */
bool
vect_analyze_data_ref_accesses (loop_vec_info loop_vinfo, bb_vec_info bb_vinfo)
{
unsigned int i;
vec<data_reference_p> datarefs;
struct data_reference *dr;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_analyze_data_ref_accesses ===\n");
if (loop_vinfo)
datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
else
datarefs = BB_VINFO_DATAREFS (bb_vinfo);
if (datarefs.is_empty ())
return true;
/* Sort the array of datarefs to make building the interleaving chains
linear. Don't modify the original vector's order, it is needed for
determining what dependencies are reversed. */
vec<data_reference_p> datarefs_copy = datarefs.copy ();
datarefs_copy.qsort (dr_group_sort_cmp);
/* Build the interleaving chains. */
for (i = 0; i < datarefs_copy.length () - 1;)
{
data_reference_p dra = datarefs_copy[i];
stmt_vec_info stmtinfo_a = vinfo_for_stmt (DR_STMT (dra));
stmt_vec_info lastinfo = NULL;
for (i = i + 1; i < datarefs_copy.length (); ++i)
{
data_reference_p drb = datarefs_copy[i];
stmt_vec_info stmtinfo_b = vinfo_for_stmt (DR_STMT (drb));
/* ??? Imperfect sorting (non-compatible types, non-modulo
accesses, same accesses) can lead to a group to be artificially
split here as we don't just skip over those. If it really
matters we can push those to a worklist and re-iterate
over them. The we can just skip ahead to the next DR here. */
/* Check that the data-refs have same first location (except init)
and they are both either store or load (not load and store,
not masked loads or stores). */
if (DR_IS_READ (dra) != DR_IS_READ (drb)
|| !operand_equal_p (DR_BASE_ADDRESS (dra),
DR_BASE_ADDRESS (drb), 0)
|| !dr_equal_offsets_p (dra, drb)
|| !gimple_assign_single_p (DR_STMT (dra))
|| !gimple_assign_single_p (DR_STMT (drb)))
break;
/* Check that the data-refs have the same constant size and step. */
tree sza = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dra)));
tree szb = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (drb)));
if (!tree_fits_uhwi_p (sza)
|| !tree_fits_uhwi_p (szb)
|| !tree_int_cst_equal (sza, szb)
|| !tree_fits_shwi_p (DR_STEP (dra))
|| !tree_fits_shwi_p (DR_STEP (drb))
|| !tree_int_cst_equal (DR_STEP (dra), DR_STEP (drb)))
break;
/* Do not place the same access in the interleaving chain twice. */
if (tree_int_cst_compare (DR_INIT (dra), DR_INIT (drb)) == 0)
break;
/* Check the types are compatible.
??? We don't distinguish this during sorting. */
if (!types_compatible_p (TREE_TYPE (DR_REF (dra)),
TREE_TYPE (DR_REF (drb))))
break;
/* Sorting has ensured that DR_INIT (dra) <= DR_INIT (drb). */
HOST_WIDE_INT init_a = TREE_INT_CST_LOW (DR_INIT (dra));
HOST_WIDE_INT init_b = TREE_INT_CST_LOW (DR_INIT (drb));
gcc_assert (init_a < init_b);
/* If init_b == init_a + the size of the type * k, we have an
interleaving, and DRA is accessed before DRB. */
HOST_WIDE_INT type_size_a = tree_to_uhwi (sza);
if ((init_b - init_a) % type_size_a != 0)
break;
/* The step (if not zero) is greater than the difference between
data-refs' inits. This splits groups into suitable sizes. */
HOST_WIDE_INT step = tree_to_shwi (DR_STEP (dra));
if (step != 0 && step <= (init_b - init_a))
break;
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"Detected interleaving ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (dra));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_REF (drb));
dump_printf (MSG_NOTE, "\n");
}
/* Link the found element into the group list. */
if (!GROUP_FIRST_ELEMENT (stmtinfo_a))
{
GROUP_FIRST_ELEMENT (stmtinfo_a) = DR_STMT (dra);
lastinfo = stmtinfo_a;
}
GROUP_FIRST_ELEMENT (stmtinfo_b) = DR_STMT (dra);
GROUP_NEXT_ELEMENT (lastinfo) = DR_STMT (drb);
lastinfo = stmtinfo_b;
}
}
FOR_EACH_VEC_ELT (datarefs_copy, i, dr)
if (STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr)))
&& !vect_analyze_data_ref_access (dr))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: complicated access pattern.\n");
if (bb_vinfo)
{
/* Mark the statement as not vectorizable. */
STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr))) = false;
continue;
}
else
{
datarefs_copy.release ();
return false;
}
}
datarefs_copy.release ();
return true;
}
/* Operator == between two dr_with_seg_len objects.
This equality operator is used to make sure two data refs
are the same one so that we will consider to combine the
aliasing checks of those two pairs of data dependent data
refs. */
static bool
operator == (const dr_with_seg_len& d1,
const dr_with_seg_len& d2)
{
return operand_equal_p (DR_BASE_ADDRESS (d1.dr),
DR_BASE_ADDRESS (d2.dr), 0)
&& compare_tree (d1.offset, d2.offset) == 0
&& compare_tree (d1.seg_len, d2.seg_len) == 0;
}
/* Function comp_dr_with_seg_len_pair.
Comparison function for sorting objects of dr_with_seg_len_pair_t
so that we can combine aliasing checks in one scan. */
static int
comp_dr_with_seg_len_pair (const void *p1_, const void *p2_)
{
const dr_with_seg_len_pair_t* p1 = (const dr_with_seg_len_pair_t *) p1_;
const dr_with_seg_len_pair_t* p2 = (const dr_with_seg_len_pair_t *) p2_;
const dr_with_seg_len &p11 = p1->first,
&p12 = p1->second,
&p21 = p2->first,
&p22 = p2->second;
/* For DR pairs (a, b) and (c, d), we only consider to merge the alias checks
if a and c have the same basic address snd step, and b and d have the same
address and step. Therefore, if any a&c or b&d don't have the same address
and step, we don't care the order of those two pairs after sorting. */
int comp_res;
if ((comp_res = compare_tree (DR_BASE_ADDRESS (p11.dr),
DR_BASE_ADDRESS (p21.dr))) != 0)
return comp_res;
if ((comp_res = compare_tree (DR_BASE_ADDRESS (p12.dr),
DR_BASE_ADDRESS (p22.dr))) != 0)
return comp_res;
if ((comp_res = compare_tree (DR_STEP (p11.dr), DR_STEP (p21.dr))) != 0)
return comp_res;
if ((comp_res = compare_tree (DR_STEP (p12.dr), DR_STEP (p22.dr))) != 0)
return comp_res;
if ((comp_res = compare_tree (p11.offset, p21.offset)) != 0)
return comp_res;
if ((comp_res = compare_tree (p12.offset, p22.offset)) != 0)
return comp_res;
return 0;
}
/* Function vect_vfa_segment_size.
Create an expression that computes the size of segment
that will be accessed for a data reference. The functions takes into
account that realignment loads may access one more vector.
Input:
DR: The data reference.
LENGTH_FACTOR: segment length to consider.
Return an expression whose value is the size of segment which will be
accessed by DR. */
static tree
vect_vfa_segment_size (struct data_reference *dr, tree length_factor)
{
tree segment_length;
if (integer_zerop (DR_STEP (dr)))
segment_length = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
else
segment_length = size_binop (MULT_EXPR,
fold_convert (sizetype, DR_STEP (dr)),
fold_convert (sizetype, length_factor));
if (vect_supportable_dr_alignment (dr, false)
== dr_explicit_realign_optimized)
{
tree vector_size = TYPE_SIZE_UNIT
(STMT_VINFO_VECTYPE (vinfo_for_stmt (DR_STMT (dr))));
segment_length = size_binop (PLUS_EXPR, segment_length, vector_size);
}
return segment_length;
}
/* Function vect_prune_runtime_alias_test_list.
Prune a list of ddrs to be tested at run-time by versioning for alias.
Merge several alias checks into one if possible.
Return FALSE if resulting list of ddrs is longer then allowed by
PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS, otherwise return TRUE. */
bool
vect_prune_runtime_alias_test_list (loop_vec_info loop_vinfo)
{
vec<ddr_p> may_alias_ddrs =
LOOP_VINFO_MAY_ALIAS_DDRS (loop_vinfo);
vec<dr_with_seg_len_pair_t>& comp_alias_ddrs =
LOOP_VINFO_COMP_ALIAS_DDRS (loop_vinfo);
int vect_factor = LOOP_VINFO_VECT_FACTOR (loop_vinfo);
tree scalar_loop_iters = LOOP_VINFO_NITERS (loop_vinfo);
ddr_p ddr;
unsigned int i;
tree length_factor;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_prune_runtime_alias_test_list ===\n");
if (may_alias_ddrs.is_empty ())
return true;
/* Basically, for each pair of dependent data refs store_ptr_0
and load_ptr_0, we create an expression:
((store_ptr_0 + store_segment_length_0) <= load_ptr_0)
|| (load_ptr_0 + load_segment_length_0) <= store_ptr_0))
for aliasing checks. However, in some cases we can decrease
the number of checks by combining two checks into one. For
example, suppose we have another pair of data refs store_ptr_0
and load_ptr_1, and if the following condition is satisfied:
load_ptr_0 < load_ptr_1 &&
load_ptr_1 - load_ptr_0 - load_segment_length_0 < store_segment_length_0
(this condition means, in each iteration of vectorized loop,
the accessed memory of store_ptr_0 cannot be between the memory
of load_ptr_0 and load_ptr_1.)
we then can use only the following expression to finish the
alising checks between store_ptr_0 & load_ptr_0 and
store_ptr_0 & load_ptr_1:
((store_ptr_0 + store_segment_length_0) <= load_ptr_0)
|| (load_ptr_1 + load_segment_length_1 <= store_ptr_0))
Note that we only consider that load_ptr_0 and load_ptr_1 have the
same basic address. */
comp_alias_ddrs.create (may_alias_ddrs.length ());
/* First, we collect all data ref pairs for aliasing checks. */
FOR_EACH_VEC_ELT (may_alias_ddrs, i, ddr)
{
struct data_reference *dr_a, *dr_b;
gimple dr_group_first_a, dr_group_first_b;
tree segment_length_a, segment_length_b;
gimple stmt_a, stmt_b;
dr_a = DDR_A (ddr);
stmt_a = DR_STMT (DDR_A (ddr));
dr_group_first_a = GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt_a));
if (dr_group_first_a)
{
stmt_a = dr_group_first_a;
dr_a = STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt_a));
}
dr_b = DDR_B (ddr);
stmt_b = DR_STMT (DDR_B (ddr));
dr_group_first_b = GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt_b));
if (dr_group_first_b)
{
stmt_b = dr_group_first_b;
dr_b = STMT_VINFO_DATA_REF (vinfo_for_stmt (stmt_b));
}
if (!operand_equal_p (DR_STEP (dr_a), DR_STEP (dr_b), 0))
length_factor = scalar_loop_iters;
else
length_factor = size_int (vect_factor);
segment_length_a = vect_vfa_segment_size (dr_a, length_factor);
segment_length_b = vect_vfa_segment_size (dr_b, length_factor);
dr_with_seg_len_pair_t dr_with_seg_len_pair
(dr_with_seg_len (dr_a, segment_length_a),
dr_with_seg_len (dr_b, segment_length_b));
if (compare_tree (DR_BASE_ADDRESS (dr_a), DR_BASE_ADDRESS (dr_b)) > 0)
std::swap (dr_with_seg_len_pair.first, dr_with_seg_len_pair.second);
comp_alias_ddrs.safe_push (dr_with_seg_len_pair);
}
/* Second, we sort the collected data ref pairs so that we can scan
them once to combine all possible aliasing checks. */
comp_alias_ddrs.qsort (comp_dr_with_seg_len_pair);
/* Third, we scan the sorted dr pairs and check if we can combine
alias checks of two neighbouring dr pairs. */
for (size_t i = 1; i < comp_alias_ddrs.length (); ++i)
{
/* Deal with two ddrs (dr_a1, dr_b1) and (dr_a2, dr_b2). */
dr_with_seg_len *dr_a1 = &comp_alias_ddrs[i-1].first,
*dr_b1 = &comp_alias_ddrs[i-1].second,
*dr_a2 = &comp_alias_ddrs[i].first,
*dr_b2 = &comp_alias_ddrs[i].second;
/* Remove duplicate data ref pairs. */
if (*dr_a1 == *dr_a2 && *dr_b1 == *dr_b2)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"found equal ranges ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_a1->dr));
dump_printf (MSG_NOTE, ", ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_b1->dr));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_a2->dr));
dump_printf (MSG_NOTE, ", ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_b2->dr));
dump_printf (MSG_NOTE, "\n");
}
comp_alias_ddrs.ordered_remove (i--);
continue;
}
if (*dr_a1 == *dr_a2 || *dr_b1 == *dr_b2)
{
/* We consider the case that DR_B1 and DR_B2 are same memrefs,
and DR_A1 and DR_A2 are two consecutive memrefs. */
if (*dr_a1 == *dr_a2)
{
std::swap (dr_a1, dr_b1);
std::swap (dr_a2, dr_b2);
}
if (!operand_equal_p (DR_BASE_ADDRESS (dr_a1->dr),
DR_BASE_ADDRESS (dr_a2->dr),
0)
|| !tree_fits_shwi_p (dr_a1->offset)
|| !tree_fits_shwi_p (dr_a2->offset))
continue;
HOST_WIDE_INT diff = (tree_to_shwi (dr_a2->offset)
- tree_to_shwi (dr_a1->offset));
/* Now we check if the following condition is satisfied:
DIFF - SEGMENT_LENGTH_A < SEGMENT_LENGTH_B
where DIFF = DR_A2->OFFSET - DR_A1->OFFSET. However,
SEGMENT_LENGTH_A or SEGMENT_LENGTH_B may not be constant so we
have to make a best estimation. We can get the minimum value
of SEGMENT_LENGTH_B as a constant, represented by MIN_SEG_LEN_B,
then either of the following two conditions can guarantee the
one above:
1: DIFF <= MIN_SEG_LEN_B
2: DIFF - SEGMENT_LENGTH_A < MIN_SEG_LEN_B
*/
HOST_WIDE_INT min_seg_len_b = (tree_fits_shwi_p (dr_b1->seg_len)
? tree_to_shwi (dr_b1->seg_len)
: vect_factor);
if (diff <= min_seg_len_b
|| (tree_fits_shwi_p (dr_a1->seg_len)
&& diff - tree_to_shwi (dr_a1->seg_len) < min_seg_len_b))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"merging ranges for ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_a1->dr));
dump_printf (MSG_NOTE, ", ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_b1->dr));
dump_printf (MSG_NOTE, " and ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_a2->dr));
dump_printf (MSG_NOTE, ", ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
DR_REF (dr_b2->dr));
dump_printf (MSG_NOTE, "\n");
}
dr_a1->seg_len = size_binop (PLUS_EXPR,
dr_a2->seg_len, size_int (diff));
comp_alias_ddrs.ordered_remove (i--);
}
}
}
dump_printf_loc (MSG_NOTE, vect_location,
"improved number of alias checks from %d to %d\n",
may_alias_ddrs.length (), comp_alias_ddrs.length ());
if ((int) comp_alias_ddrs.length () >
PARAM_VALUE (PARAM_VECT_MAX_VERSION_FOR_ALIAS_CHECKS))
return false;
return true;
}
/* Check whether a non-affine read in stmt is suitable for gather load
and if so, return a builtin decl for that operation. */
tree
vect_check_gather (gimple stmt, loop_vec_info loop_vinfo, tree *basep,
tree *offp, int *scalep)
{
HOST_WIDE_INT scale = 1, pbitpos, pbitsize;
struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
tree offtype = NULL_TREE;
tree decl, base, off;
machine_mode pmode;
int punsignedp, pvolatilep;
base = DR_REF (dr);
/* For masked loads/stores, DR_REF (dr) is an artificial MEM_REF,
see if we can use the def stmt of the address. */
if (is_gimple_call (stmt)
&& gimple_call_internal_p (stmt)
&& (gimple_call_internal_fn (stmt) == IFN_MASK_LOAD
|| gimple_call_internal_fn (stmt) == IFN_MASK_STORE)
&& TREE_CODE (base) == MEM_REF
&& TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME
&& integer_zerop (TREE_OPERAND (base, 1))
&& !expr_invariant_in_loop_p (loop, TREE_OPERAND (base, 0)))
{
gimple def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (base, 0));
if (is_gimple_assign (def_stmt)
&& gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
base = TREE_OPERAND (gimple_assign_rhs1 (def_stmt), 0);
}
/* The gather builtins need address of the form
loop_invariant + vector * {1, 2, 4, 8}
or
loop_invariant + sign_extend (vector) * { 1, 2, 4, 8 }.
Unfortunately DR_BASE_ADDRESS/DR_OFFSET can be a mixture
of loop invariants/SSA_NAMEs defined in the loop, with casts,
multiplications and additions in it. To get a vector, we need
a single SSA_NAME that will be defined in the loop and will
contain everything that is not loop invariant and that can be
vectorized. The following code attempts to find such a preexistng
SSA_NAME OFF and put the loop invariants into a tree BASE
that can be gimplified before the loop. */
base = get_inner_reference (base, &pbitsize, &pbitpos, &off,
&pmode, &punsignedp, &pvolatilep, false);
gcc_assert (base != NULL_TREE && (pbitpos % BITS_PER_UNIT) == 0);
if (TREE_CODE (base) == MEM_REF)
{
if (!integer_zerop (TREE_OPERAND (base, 1)))
{
if (off == NULL_TREE)
{
offset_int moff = mem_ref_offset (base);
off = wide_int_to_tree (sizetype, moff);
}
else
off = size_binop (PLUS_EXPR, off,
fold_convert (sizetype, TREE_OPERAND (base, 1)));
}
base = TREE_OPERAND (base, 0);
}
else
base = build_fold_addr_expr (base);
if (off == NULL_TREE)
off = size_zero_node;
/* If base is not loop invariant, either off is 0, then we start with just
the constant offset in the loop invariant BASE and continue with base
as OFF, otherwise give up.
We could handle that case by gimplifying the addition of base + off
into some SSA_NAME and use that as off, but for now punt. */
if (!expr_invariant_in_loop_p (loop, base))
{
if (!integer_zerop (off))
return NULL_TREE;
off = base;
base = size_int (pbitpos / BITS_PER_UNIT);
}
/* Otherwise put base + constant offset into the loop invariant BASE
and continue with OFF. */
else
{
base = fold_convert (sizetype, base);
base = size_binop (PLUS_EXPR, base, size_int (pbitpos / BITS_PER_UNIT));
}
/* OFF at this point may be either a SSA_NAME or some tree expression
from get_inner_reference. Try to peel off loop invariants from it
into BASE as long as possible. */
STRIP_NOPS (off);
while (offtype == NULL_TREE)
{
enum tree_code code;
tree op0, op1, add = NULL_TREE;
if (TREE_CODE (off) == SSA_NAME)
{
gimple def_stmt = SSA_NAME_DEF_STMT (off);
if (expr_invariant_in_loop_p (loop, off))
return NULL_TREE;
if (gimple_code (def_stmt) != GIMPLE_ASSIGN)
break;
op0 = gimple_assign_rhs1 (def_stmt);
code = gimple_assign_rhs_code (def_stmt);
op1 = gimple_assign_rhs2 (def_stmt);
}
else
{
if (get_gimple_rhs_class (TREE_CODE (off)) == GIMPLE_TERNARY_RHS)
return NULL_TREE;
code = TREE_CODE (off);
extract_ops_from_tree (off, &code, &op0, &op1);
}
switch (code)
{
case POINTER_PLUS_EXPR:
case PLUS_EXPR:
if (expr_invariant_in_loop_p (loop, op0))
{
add = op0;
off = op1;
do_add:
add = fold_convert (sizetype, add);
if (scale != 1)
add = size_binop (MULT_EXPR, add, size_int (scale));
base = size_binop (PLUS_EXPR, base, add);
continue;
}
if (expr_invariant_in_loop_p (loop, op1))
{
add = op1;
off = op0;
goto do_add;
}
break;
case MINUS_EXPR:
if (expr_invariant_in_loop_p (loop, op1))
{
add = fold_convert (sizetype, op1);
add = size_binop (MINUS_EXPR, size_zero_node, add);
off = op0;
goto do_add;
}
break;
case MULT_EXPR:
if (scale == 1 && tree_fits_shwi_p (op1))
{
scale = tree_to_shwi (op1);
off = op0;
continue;
}
break;
case SSA_NAME:
off = op0;
continue;
CASE_CONVERT:
if (!POINTER_TYPE_P (TREE_TYPE (op0))
&& !INTEGRAL_TYPE_P (TREE_TYPE (op0)))
break;
if (TYPE_PRECISION (TREE_TYPE (op0))
== TYPE_PRECISION (TREE_TYPE (off)))
{
off = op0;
continue;
}
if (TYPE_PRECISION (TREE_TYPE (op0))
< TYPE_PRECISION (TREE_TYPE (off)))
{
off = op0;
offtype = TREE_TYPE (off);
STRIP_NOPS (off);
continue;
}
break;
default:
break;
}
break;
}
/* If at the end OFF still isn't a SSA_NAME or isn't
defined in the loop, punt. */
if (TREE_CODE (off) != SSA_NAME
|| expr_invariant_in_loop_p (loop, off))
return NULL_TREE;
if (offtype == NULL_TREE)
offtype = TREE_TYPE (off);
decl = targetm.vectorize.builtin_gather (STMT_VINFO_VECTYPE (stmt_info),
offtype, scale);
if (decl == NULL_TREE)
return NULL_TREE;
if (basep)
*basep = base;
if (offp)
*offp = off;
if (scalep)
*scalep = scale;
return decl;
}
/* Function vect_analyze_data_refs.
Find all the data references in the loop or basic block.
The general structure of the analysis of data refs in the vectorizer is as
follows:
1- vect_analyze_data_refs(loop/bb): call
compute_data_dependences_for_loop/bb to find and analyze all data-refs
in the loop/bb and their dependences.
2- vect_analyze_dependences(): apply dependence testing using ddrs.
3- vect_analyze_drs_alignment(): check that ref_stmt.alignment is ok.
4- vect_analyze_drs_access(): check that ref_stmt.step is ok.
*/
bool
vect_analyze_data_refs (loop_vec_info loop_vinfo,
bb_vec_info bb_vinfo,
int *min_vf, unsigned *n_stmts)
{
struct loop *loop = NULL;
basic_block bb = NULL;
unsigned int i;
vec<data_reference_p> datarefs;
struct data_reference *dr;
tree scalar_type;
if (dump_enabled_p ())
dump_printf_loc (MSG_NOTE, vect_location,
"=== vect_analyze_data_refs ===\n");
if (loop_vinfo)
{
basic_block *bbs = LOOP_VINFO_BBS (loop_vinfo);
loop = LOOP_VINFO_LOOP (loop_vinfo);
datarefs = LOOP_VINFO_DATAREFS (loop_vinfo);
if (!find_loop_nest (loop, &LOOP_VINFO_LOOP_NEST (loop_vinfo)))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: loop contains function calls"
" or data references that cannot be analyzed\n");
return false;
}
for (i = 0; i < loop->num_nodes; i++)
{
gimple_stmt_iterator gsi;
for (gsi = gsi_start_bb (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi))
{
gimple stmt = gsi_stmt (gsi);
if (is_gimple_debug (stmt))
continue;
++*n_stmts;
if (!find_data_references_in_stmt (loop, stmt, &datarefs))
{
if (is_gimple_call (stmt) && loop->safelen)
{
tree fndecl = gimple_call_fndecl (stmt), op;
if (fndecl != NULL_TREE)
{
struct cgraph_node *node = cgraph_node::get (fndecl);
if (node != NULL && node->simd_clones != NULL)
{
unsigned int j, n = gimple_call_num_args (stmt);
for (j = 0; j < n; j++)
{
op = gimple_call_arg (stmt, j);
if (DECL_P (op)
|| (REFERENCE_CLASS_P (op)
&& get_base_address (op)))
break;
}
op = gimple_call_lhs (stmt);
/* Ignore #pragma omp declare simd functions
if they don't have data references in the
call stmt itself. */
if (j == n
&& !(op
&& (DECL_P (op)
|| (REFERENCE_CLASS_P (op)
&& get_base_address (op)))))
continue;
}
}
}
LOOP_VINFO_DATAREFS (loop_vinfo) = datarefs;
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: loop contains function "
"calls or data references that cannot "
"be analyzed\n");
return false;
}
}
}
LOOP_VINFO_DATAREFS (loop_vinfo) = datarefs;
}
else
{
gimple_stmt_iterator gsi;
bb = BB_VINFO_BB (bb_vinfo);
for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
{
gimple stmt = gsi_stmt (gsi);
if (is_gimple_debug (stmt))
continue;
++*n_stmts;
if (!find_data_references_in_stmt (NULL, stmt,
&BB_VINFO_DATAREFS (bb_vinfo)))
{
/* Mark the rest of the basic-block as unvectorizable. */
for (; !gsi_end_p (gsi); gsi_next (&gsi))
{
stmt = gsi_stmt (gsi);
STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (stmt)) = false;
}
break;
}
}
datarefs = BB_VINFO_DATAREFS (bb_vinfo);
}
/* Go through the data-refs, check that the analysis succeeded. Update
pointer from stmt_vec_info struct to DR and vectype. */
FOR_EACH_VEC_ELT (datarefs, i, dr)
{
gimple stmt;
stmt_vec_info stmt_info;
tree base, offset, init;
bool gather = false;
bool simd_lane_access = false;
int vf;
again:
if (!dr || !DR_REF (dr))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: unhandled data-ref\n");
return false;
}
stmt = DR_STMT (dr);
stmt_info = vinfo_for_stmt (stmt);
/* Discard clobbers from the dataref vector. We will remove
clobber stmts during vectorization. */
if (gimple_clobber_p (stmt))
{
free_data_ref (dr);
if (i == datarefs.length () - 1)
{
datarefs.pop ();
break;
}
datarefs.ordered_remove (i);
dr = datarefs[i];
goto again;
}
/* Check that analysis of the data-ref succeeded. */
if (!DR_BASE_ADDRESS (dr) || !DR_OFFSET (dr) || !DR_INIT (dr)
|| !DR_STEP (dr))
{
bool maybe_gather
= DR_IS_READ (dr)
&& !TREE_THIS_VOLATILE (DR_REF (dr))
&& targetm.vectorize.builtin_gather != NULL;
bool maybe_simd_lane_access
= loop_vinfo && loop->simduid;
/* If target supports vector gather loads, or if this might be
a SIMD lane access, see if they can't be used. */
if (loop_vinfo
&& (maybe_gather || maybe_simd_lane_access)
&& !nested_in_vect_loop_p (loop, stmt))
{
struct data_reference *newdr
= create_data_ref (NULL, loop_containing_stmt (stmt),
DR_REF (dr), stmt, true);
gcc_assert (newdr != NULL && DR_REF (newdr));
if (DR_BASE_ADDRESS (newdr)
&& DR_OFFSET (newdr)
&& DR_INIT (newdr)
&& DR_STEP (newdr)
&& integer_zerop (DR_STEP (newdr)))
{
if (maybe_simd_lane_access)
{
tree off = DR_OFFSET (newdr);
STRIP_NOPS (off);
if (TREE_CODE (DR_INIT (newdr)) == INTEGER_CST
&& TREE_CODE (off) == MULT_EXPR
&& tree_fits_uhwi_p (TREE_OPERAND (off, 1)))
{
tree step = TREE_OPERAND (off, 1);
off = TREE_OPERAND (off, 0);
STRIP_NOPS (off);
if (CONVERT_EXPR_P (off)
&& TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (off,
0)))
< TYPE_PRECISION (TREE_TYPE (off)))
off = TREE_OPERAND (off, 0);
if (TREE_CODE (off) == SSA_NAME)
{
gimple def = SSA_NAME_DEF_STMT (off);
tree reft = TREE_TYPE (DR_REF (newdr));
if (is_gimple_call (def)
&& gimple_call_internal_p (def)
&& (gimple_call_internal_fn (def)
== IFN_GOMP_SIMD_LANE))
{
tree arg = gimple_call_arg (def, 0);
gcc_assert (TREE_CODE (arg) == SSA_NAME);
arg = SSA_NAME_VAR (arg);
if (arg == loop->simduid
/* For now. */
&& tree_int_cst_equal
(TYPE_SIZE_UNIT (reft),
step))
{
DR_OFFSET (newdr) = ssize_int (0);
DR_STEP (newdr) = step;
DR_ALIGNED_TO (newdr)
= size_int (BIGGEST_ALIGNMENT);
dr = newdr;
simd_lane_access = true;
}
}
}
}
}
if (!simd_lane_access && maybe_gather)
{
dr = newdr;
gather = true;
}
}
if (!gather && !simd_lane_access)
free_data_ref (newdr);
}
if (!gather && !simd_lane_access)
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: data ref analysis "
"failed ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
return false;
}
}
if (TREE_CODE (DR_BASE_ADDRESS (dr)) == INTEGER_CST)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: base addr of dr is a "
"constant\n");
if (bb_vinfo)
break;
if (gather || simd_lane_access)
free_data_ref (dr);
return false;
}
if (TREE_THIS_VOLATILE (DR_REF (dr)))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: volatile type ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
return false;
}
if (stmt_can_throw_internal (stmt))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: statement can throw an "
"exception ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
if (gather || simd_lane_access)
free_data_ref (dr);
return false;
}
if (TREE_CODE (DR_REF (dr)) == COMPONENT_REF
&& DECL_BIT_FIELD (TREE_OPERAND (DR_REF (dr), 1)))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: statement is bitfield "
"access ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
if (gather || simd_lane_access)
free_data_ref (dr);
return false;
}
base = unshare_expr (DR_BASE_ADDRESS (dr));
offset = unshare_expr (DR_OFFSET (dr));
init = unshare_expr (DR_INIT (dr));
if (is_gimple_call (stmt)
&& (!gimple_call_internal_p (stmt)
|| (gimple_call_internal_fn (stmt) != IFN_MASK_LOAD
&& gimple_call_internal_fn (stmt) != IFN_MASK_STORE)))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: dr in a call ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
if (gather || simd_lane_access)
free_data_ref (dr);
return false;
}
/* Update DR field in stmt_vec_info struct. */
/* If the dataref is in an inner-loop of the loop that is considered for
for vectorization, we also want to analyze the access relative to
the outer-loop (DR contains information only relative to the
inner-most enclosing loop). We do that by building a reference to the
first location accessed by the inner-loop, and analyze it relative to
the outer-loop. */
if (loop && nested_in_vect_loop_p (loop, stmt))
{
tree outer_step, outer_base, outer_init;
HOST_WIDE_INT pbitsize, pbitpos;
tree poffset;
machine_mode pmode;
int punsignedp, pvolatilep;
affine_iv base_iv, offset_iv;
tree dinit;
/* Build a reference to the first location accessed by the
inner-loop: *(BASE+INIT). (The first location is actually
BASE+INIT+OFFSET, but we add OFFSET separately later). */
tree inner_base = build_fold_indirect_ref
(fold_build_pointer_plus (base, init));
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"analyze in outer-loop: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, inner_base);
dump_printf (MSG_NOTE, "\n");
}
outer_base = get_inner_reference (inner_base, &pbitsize, &pbitpos,
&poffset, &pmode, &punsignedp, &pvolatilep, false);
gcc_assert (outer_base != NULL_TREE);
if (pbitpos % BITS_PER_UNIT != 0)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"failed: bit offset alignment.\n");
return false;
}
outer_base = build_fold_addr_expr (outer_base);
if (!simple_iv (loop, loop_containing_stmt (stmt), outer_base,
&base_iv, false))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"failed: evolution of base is not affine.\n");
return false;
}
if (offset)
{
if (poffset)
poffset = fold_build2 (PLUS_EXPR, TREE_TYPE (offset), offset,
poffset);
else
poffset = offset;
}
if (!poffset)
{
offset_iv.base = ssize_int (0);
offset_iv.step = ssize_int (0);
}
else if (!simple_iv (loop, loop_containing_stmt (stmt), poffset,
&offset_iv, false))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"evolution of offset is not affine.\n");
return false;
}
outer_init = ssize_int (pbitpos / BITS_PER_UNIT);
split_constant_offset (base_iv.base, &base_iv.base, &dinit);
outer_init = size_binop (PLUS_EXPR, outer_init, dinit);
split_constant_offset (offset_iv.base, &offset_iv.base, &dinit);
outer_init = size_binop (PLUS_EXPR, outer_init, dinit);
outer_step = size_binop (PLUS_EXPR,
fold_convert (ssizetype, base_iv.step),
fold_convert (ssizetype, offset_iv.step));
STMT_VINFO_DR_STEP (stmt_info) = outer_step;
/* FIXME: Use canonicalize_base_object_address (base_iv.base); */
STMT_VINFO_DR_BASE_ADDRESS (stmt_info) = base_iv.base;
STMT_VINFO_DR_INIT (stmt_info) = outer_init;
STMT_VINFO_DR_OFFSET (stmt_info) =
fold_convert (ssizetype, offset_iv.base);
STMT_VINFO_DR_ALIGNED_TO (stmt_info) =
size_int (highest_pow2_factor (offset_iv.base));
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"\touter base_address: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_DR_BASE_ADDRESS (stmt_info));
dump_printf (MSG_NOTE, "\n\touter offset from base address: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_DR_OFFSET (stmt_info));
dump_printf (MSG_NOTE,
"\n\touter constant offset from base address: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_DR_INIT (stmt_info));
dump_printf (MSG_NOTE, "\n\touter step: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_DR_STEP (stmt_info));
dump_printf (MSG_NOTE, "\n\touter aligned to: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_DR_ALIGNED_TO (stmt_info));
dump_printf (MSG_NOTE, "\n");
}
}
if (STMT_VINFO_DATA_REF (stmt_info))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: more than one data ref "
"in stmt: ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
if (gather || simd_lane_access)
free_data_ref (dr);
return false;
}
STMT_VINFO_DATA_REF (stmt_info) = dr;
if (simd_lane_access)
{
STMT_VINFO_SIMD_LANE_ACCESS_P (stmt_info) = true;
free_data_ref (datarefs[i]);
datarefs[i] = dr;
}
/* Set vectype for STMT. */
scalar_type = TREE_TYPE (DR_REF (dr));
STMT_VINFO_VECTYPE (stmt_info)
= get_vectype_for_scalar_type (scalar_type);
if (!STMT_VINFO_VECTYPE (stmt_info))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: no vectype for stmt: ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, " scalar_type: ");
dump_generic_expr (MSG_MISSED_OPTIMIZATION, TDF_DETAILS,
scalar_type);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
if (bb_vinfo)
break;
if (gather || simd_lane_access)
{
STMT_VINFO_DATA_REF (stmt_info) = NULL;
if (gather)
free_data_ref (dr);
}
return false;
}
else
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location,
"got vectype for stmt: ");
dump_gimple_stmt (MSG_NOTE, TDF_SLIM, stmt, 0);
dump_generic_expr (MSG_NOTE, TDF_SLIM,
STMT_VINFO_VECTYPE (stmt_info));
dump_printf (MSG_NOTE, "\n");
}
}
/* Adjust the minimal vectorization factor according to the
vector type. */
vf = TYPE_VECTOR_SUBPARTS (STMT_VINFO_VECTYPE (stmt_info));
if (vf > *min_vf)
*min_vf = vf;
if (gather)
{
tree off;
gather = 0 != vect_check_gather (stmt, loop_vinfo, NULL, &off, NULL);
if (gather
&& get_vectype_for_scalar_type (TREE_TYPE (off)) == NULL_TREE)
gather = false;
if (!gather)
{
STMT_VINFO_DATA_REF (stmt_info) = NULL;
free_data_ref (dr);
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: not suitable for gather "
"load ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return false;
}
datarefs[i] = dr;
STMT_VINFO_GATHER_P (stmt_info) = true;
}
else if (loop_vinfo
&& TREE_CODE (DR_STEP (dr)) != INTEGER_CST)
{
if (nested_in_vect_loop_p (loop, stmt)
|| !DR_IS_READ (dr))
{
if (dump_enabled_p ())
{
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"not vectorized: not suitable for strided "
"load ");
dump_gimple_stmt (MSG_MISSED_OPTIMIZATION, TDF_SLIM, stmt, 0);
dump_printf (MSG_MISSED_OPTIMIZATION, "\n");
}
return false;
}
STMT_VINFO_STRIDE_LOAD_P (stmt_info) = true;
}
}
/* If we stopped analysis at the first dataref we could not analyze
when trying to vectorize a basic-block mark the rest of the datarefs
as not vectorizable and truncate the vector of datarefs. That
avoids spending useless time in analyzing their dependence. */
if (i != datarefs.length ())
{
gcc_assert (bb_vinfo != NULL);
for (unsigned j = i; j < datarefs.length (); ++j)
{
data_reference_p dr = datarefs[j];
STMT_VINFO_VECTORIZABLE (vinfo_for_stmt (DR_STMT (dr))) = false;
free_data_ref (dr);
}
datarefs.truncate (i);
}
return true;
}
/* Function vect_get_new_vect_var.
Returns a name for a new variable. The current naming scheme appends the
prefix "vect_" or "vect_p" (depending on the value of VAR_KIND) to
the name of vectorizer generated variables, and appends that to NAME if
provided. */
tree
vect_get_new_vect_var (tree type, enum vect_var_kind var_kind, const char *name)
{
const char *prefix;
tree new_vect_var;
switch (var_kind)
{
case vect_simple_var:
prefix = "vect";
break;
case vect_scalar_var:
prefix = "stmp";
break;
case vect_pointer_var:
prefix = "vectp";
break;
default:
gcc_unreachable ();
}
if (name)
{
char* tmp = concat (prefix, "_", name, NULL);
new_vect_var = create_tmp_reg (type, tmp);
free (tmp);
}
else
new_vect_var = create_tmp_reg (type, prefix);
return new_vect_var;
}
/* Duplicate ptr info and set alignment/misaligment on NAME from DR. */
static void
vect_duplicate_ssa_name_ptr_info (tree name, data_reference *dr,
stmt_vec_info stmt_info)
{
duplicate_ssa_name_ptr_info (name, DR_PTR_INFO (dr));
unsigned int align = TYPE_ALIGN_UNIT (STMT_VINFO_VECTYPE (stmt_info));
int misalign = DR_MISALIGNMENT (dr);
if (misalign == -1)
mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (name));
else
set_ptr_info_alignment (SSA_NAME_PTR_INFO (name), align, misalign);
}
/* Function vect_create_addr_base_for_vector_ref.
Create an expression that computes the address of the first memory location
that will be accessed for a data reference.
Input:
STMT: The statement containing the data reference.
NEW_STMT_LIST: Must be initialized to NULL_TREE or a statement list.
OFFSET: Optional. If supplied, it is be added to the initial address.
LOOP: Specify relative to which loop-nest should the address be computed.
For example, when the dataref is in an inner-loop nested in an
outer-loop that is now being vectorized, LOOP can be either the
outer-loop, or the inner-loop. The first memory location accessed
by the following dataref ('in' points to short):
for (i=0; i<N; i++)
for (j=0; j<M; j++)
s += in[i+j]
is as follows:
if LOOP=i_loop: &in (relative to i_loop)
if LOOP=j_loop: &in+i*2B (relative to j_loop)
BYTE_OFFSET: Optional, defaulted to NULL. If supplied, it is added to the
initial address. Unlike OFFSET, which is number of elements to
be added, BYTE_OFFSET is measured in bytes.
Output:
1. Return an SSA_NAME whose value is the address of the memory location of
the first vector of the data reference.
2. If new_stmt_list is not NULL_TREE after return then the caller must insert
these statement(s) which define the returned SSA_NAME.
FORNOW: We are only handling array accesses with step 1. */
tree
vect_create_addr_base_for_vector_ref (gimple stmt,
gimple_seq *new_stmt_list,
tree offset,
struct loop *loop,
tree byte_offset)
{
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
tree data_ref_base;
const char *base_name;
tree addr_base;
tree dest;
gimple_seq seq = NULL;
tree base_offset;
tree init;
tree vect_ptr_type;
tree step = TYPE_SIZE_UNIT (TREE_TYPE (DR_REF (dr)));
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
if (loop_vinfo && loop && loop != (gimple_bb (stmt))->loop_father)
{
struct loop *outer_loop = LOOP_VINFO_LOOP (loop_vinfo);
gcc_assert (nested_in_vect_loop_p (outer_loop, stmt));
data_ref_base = unshare_expr (STMT_VINFO_DR_BASE_ADDRESS (stmt_info));
base_offset = unshare_expr (STMT_VINFO_DR_OFFSET (stmt_info));
init = unshare_expr (STMT_VINFO_DR_INIT (stmt_info));
}
else
{
data_ref_base = unshare_expr (DR_BASE_ADDRESS (dr));
base_offset = unshare_expr (DR_OFFSET (dr));
init = unshare_expr (DR_INIT (dr));
}
if (loop_vinfo)
base_name = get_name (data_ref_base);
else
{
base_offset = ssize_int (0);
init = ssize_int (0);
base_name = get_name (DR_REF (dr));
}
/* Create base_offset */
base_offset = size_binop (PLUS_EXPR,
fold_convert (sizetype, base_offset),
fold_convert (sizetype, init));
if (offset)
{
offset = fold_build2 (MULT_EXPR, sizetype,
fold_convert (sizetype, offset), step);
base_offset = fold_build2 (PLUS_EXPR, sizetype,
base_offset, offset);
}
if (byte_offset)
{
byte_offset = fold_convert (sizetype, byte_offset);
base_offset = fold_build2 (PLUS_EXPR, sizetype,
base_offset, byte_offset);
}
/* base + base_offset */
if (loop_vinfo)
addr_base = fold_build_pointer_plus (data_ref_base, base_offset);
else
{
addr_base = build1 (ADDR_EXPR,
build_pointer_type (TREE_TYPE (DR_REF (dr))),
unshare_expr (DR_REF (dr)));
}
vect_ptr_type = build_pointer_type (STMT_VINFO_VECTYPE (stmt_info));
addr_base = fold_convert (vect_ptr_type, addr_base);
dest = vect_get_new_vect_var (vect_ptr_type, vect_pointer_var, base_name);
addr_base = force_gimple_operand (addr_base, &seq, false, dest);
gimple_seq_add_seq (new_stmt_list, seq);
if (DR_PTR_INFO (dr)
&& TREE_CODE (addr_base) == SSA_NAME)
{
vect_duplicate_ssa_name_ptr_info (addr_base, dr, stmt_info);
if (offset || byte_offset)
mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (addr_base));
}
if (dump_enabled_p ())
{
dump_printf_loc (MSG_NOTE, vect_location, "created ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, addr_base);
dump_printf (MSG_NOTE, "\n");
}
return addr_base;
}
/* Function vect_create_data_ref_ptr.
Create a new pointer-to-AGGR_TYPE variable (ap), that points to the first
location accessed in the loop by STMT, along with the def-use update
chain to appropriately advance the pointer through the loop iterations.
Also set aliasing information for the pointer. This pointer is used by
the callers to this function to create a memory reference expression for
vector load/store access.
Input:
1. STMT: a stmt that references memory. Expected to be of the form
GIMPLE_ASSIGN <name, data-ref> or
GIMPLE_ASSIGN <data-ref, name>.
2. AGGR_TYPE: the type of the reference, which should be either a vector
or an array.
3. AT_LOOP: the loop where the vector memref is to be created.
4. OFFSET (optional): an offset to be added to the initial address accessed
by the data-ref in STMT.
5. BSI: location where the new stmts are to be placed if there is no loop
6. ONLY_INIT: indicate if ap is to be updated in the loop, or remain
pointing to the initial address.
7. BYTE_OFFSET (optional, defaults to NULL): a byte offset to be added
to the initial address accessed by the data-ref in STMT. This is
similar to OFFSET, but OFFSET is counted in elements, while BYTE_OFFSET
in bytes.
Output:
1. Declare a new ptr to vector_type, and have it point to the base of the
data reference (initial addressed accessed by the data reference).
For example, for vector of type V8HI, the following code is generated:
v8hi *ap;
ap = (v8hi *)initial_address;
if OFFSET is not supplied:
initial_address = &a[init];
if OFFSET is supplied:
initial_address = &a[init + OFFSET];
if BYTE_OFFSET is supplied:
initial_address = &a[init] + BYTE_OFFSET;
Return the initial_address in INITIAL_ADDRESS.
2. If ONLY_INIT is true, just return the initial pointer. Otherwise, also
update the pointer in each iteration of the loop.
Return the increment stmt that updates the pointer in PTR_INCR.
3. Set INV_P to true if the access pattern of the data reference in the
vectorized loop is invariant. Set it to false otherwise.
4. Return the pointer. */
tree
vect_create_data_ref_ptr (gimple stmt, tree aggr_type, struct loop *at_loop,
tree offset, tree *initial_address,
gimple_stmt_iterator *gsi, gimple *ptr_incr,
bool only_init, bool *inv_p, tree byte_offset)
{
const char *base_name;
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
struct loop *loop = NULL;
bool nested_in_vect_loop = false;
struct loop *containing_loop = NULL;
tree aggr_ptr_type;
tree aggr_ptr;
tree new_temp;
gimple vec_stmt;
gimple_seq new_stmt_list = NULL;
edge pe = NULL;
basic_block new_bb;
tree aggr_ptr_init;
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
tree aptr;
gimple_stmt_iterator incr_gsi;
bool insert_after;
tree indx_before_incr, indx_after_incr;
gimple incr;
tree step;
bb_vec_info bb_vinfo = STMT_VINFO_BB_VINFO (stmt_info);
gcc_assert (TREE_CODE (aggr_type) == ARRAY_TYPE
|| TREE_CODE (aggr_type) == VECTOR_TYPE);
if (loop_vinfo)
{
loop = LOOP_VINFO_LOOP (loop_vinfo);
nested_in_vect_loop = nested_in_vect_loop_p (loop, stmt);
containing_loop = (gimple_bb (stmt))->loop_father;
pe = loop_preheader_edge (loop);
}
else
{
gcc_assert (bb_vinfo);
only_init = true;
*ptr_incr = NULL;
}
/* Check the step (evolution) of the load in LOOP, and record
whether it's invariant. */
if (nested_in_vect_loop)
step = STMT_VINFO_DR_STEP (stmt_info);
else
step = DR_STEP (STMT_VINFO_DATA_REF (stmt_info));
if (integer_zerop (step))
*inv_p = true;
else
*inv_p = false;
/* Create an expression for the first address accessed by this load
in LOOP. */
base_name = get_name (DR_BASE_ADDRESS (dr));
if (dump_enabled_p ())
{
tree dr_base_type = TREE_TYPE (DR_BASE_OBJECT (dr));
dump_printf_loc (MSG_NOTE, vect_location,
"create %s-pointer variable to type: ",
get_tree_code_name (TREE_CODE (aggr_type)));
dump_generic_expr (MSG_NOTE, TDF_SLIM, aggr_type);
if (TREE_CODE (dr_base_type) == ARRAY_TYPE)
dump_printf (MSG_NOTE, " vectorizing an array ref: ");
else if (TREE_CODE (dr_base_type) == VECTOR_TYPE)
dump_printf (MSG_NOTE, " vectorizing a vector ref: ");
else if (TREE_CODE (dr_base_type) == RECORD_TYPE)
dump_printf (MSG_NOTE, " vectorizing a record based array ref: ");
else
dump_printf (MSG_NOTE, " vectorizing a pointer ref: ");
dump_generic_expr (MSG_NOTE, TDF_SLIM, DR_BASE_OBJECT (dr));
dump_printf (MSG_NOTE, "\n");
}
/* (1) Create the new aggregate-pointer variable.
Vector and array types inherit the alias set of their component
type by default so we need to use a ref-all pointer if the data
reference does not conflict with the created aggregated data
reference because it is not addressable. */
bool need_ref_all = false;
if (!alias_sets_conflict_p (get_alias_set (aggr_type),
get_alias_set (DR_REF (dr))))
need_ref_all = true;
/* Likewise for any of the data references in the stmt group. */
else if (STMT_VINFO_GROUP_SIZE (stmt_info) > 1)
{
gimple orig_stmt = STMT_VINFO_GROUP_FIRST_ELEMENT (stmt_info);
do
{
stmt_vec_info sinfo = vinfo_for_stmt (orig_stmt);
struct data_reference *sdr = STMT_VINFO_DATA_REF (sinfo);
if (!alias_sets_conflict_p (get_alias_set (aggr_type),
get_alias_set (DR_REF (sdr))))
{
need_ref_all = true;
break;
}
orig_stmt = STMT_VINFO_GROUP_NEXT_ELEMENT (sinfo);
}
while (orig_stmt);
}
aggr_ptr_type = build_pointer_type_for_mode (aggr_type, ptr_mode,
need_ref_all);
aggr_ptr = vect_get_new_vect_var (aggr_ptr_type, vect_pointer_var, base_name);
/* Note: If the dataref is in an inner-loop nested in LOOP, and we are
vectorizing LOOP (i.e., outer-loop vectorization), we need to create two
def-use update cycles for the pointer: one relative to the outer-loop
(LOOP), which is what steps (3) and (4) below do. The other is relative
to the inner-loop (which is the inner-most loop containing the dataref),
and this is done be step (5) below.
When vectorizing inner-most loops, the vectorized loop (LOOP) is also the
inner-most loop, and so steps (3),(4) work the same, and step (5) is
redundant. Steps (3),(4) create the following:
vp0 = &base_addr;
LOOP: vp1 = phi(vp0,vp2)
...
...
vp2 = vp1 + step
goto LOOP
If there is an inner-loop nested in loop, then step (5) will also be
applied, and an additional update in the inner-loop will be created:
vp0 = &base_addr;
LOOP: vp1 = phi(vp0,vp2)
...
inner: vp3 = phi(vp1,vp4)
vp4 = vp3 + inner_step
if () goto inner
...
vp2 = vp1 + step
if () goto LOOP */
/* (2) Calculate the initial address of the aggregate-pointer, and set
the aggregate-pointer to point to it before the loop. */
/* Create: (&(base[init_val+offset]+byte_offset) in the loop preheader. */
new_temp = vect_create_addr_base_for_vector_ref (stmt, &new_stmt_list,
offset, loop, byte_offset);
if (new_stmt_list)
{
if (pe)
{
new_bb = gsi_insert_seq_on_edge_immediate (pe, new_stmt_list);
gcc_assert (!new_bb);
}
else
gsi_insert_seq_before (gsi, new_stmt_list, GSI_SAME_STMT);
}
*initial_address = new_temp;
/* Create: p = (aggr_type *) initial_base */
if (TREE_CODE (new_temp) != SSA_NAME
|| !useless_type_conversion_p (aggr_ptr_type, TREE_TYPE (new_temp)))
{
vec_stmt = gimple_build_assign (aggr_ptr,
fold_convert (aggr_ptr_type, new_temp));
aggr_ptr_init = make_ssa_name (aggr_ptr, vec_stmt);
/* Copy the points-to information if it exists. */
if (DR_PTR_INFO (dr))
vect_duplicate_ssa_name_ptr_info (aggr_ptr_init, dr, stmt_info);
gimple_assign_set_lhs (vec_stmt, aggr_ptr_init);
if (pe)
{
new_bb = gsi_insert_on_edge_immediate (pe, vec_stmt);
gcc_assert (!new_bb);
}
else
gsi_insert_before (gsi, vec_stmt, GSI_SAME_STMT);
}
else
aggr_ptr_init = new_temp;
/* (3) Handle the updating of the aggregate-pointer inside the loop.
This is needed when ONLY_INIT is false, and also when AT_LOOP is the
inner-loop nested in LOOP (during outer-loop vectorization). */
/* No update in loop is required. */
if (only_init && (!loop_vinfo || at_loop == loop))
aptr = aggr_ptr_init;
else
{
/* The step of the aggregate pointer is the type size. */
tree iv_step = TYPE_SIZE_UNIT (aggr_type);
/* One exception to the above is when the scalar step of the load in
LOOP is zero. In this case the step here is also zero. */
if (*inv_p)
iv_step = size_zero_node;
else if (tree_int_cst_sgn (step) == -1)
iv_step = fold_build1 (NEGATE_EXPR, TREE_TYPE (iv_step), iv_step);
standard_iv_increment_position (loop, &incr_gsi, &insert_after);
create_iv (aggr_ptr_init,
fold_convert (aggr_ptr_type, iv_step),
aggr_ptr, loop, &incr_gsi, insert_after,
&indx_before_incr, &indx_after_incr);
incr = gsi_stmt (incr_gsi);
set_vinfo_for_stmt (incr, new_stmt_vec_info (incr, loop_vinfo, NULL));
/* Copy the points-to information if it exists. */
if (DR_PTR_INFO (dr))
{
vect_duplicate_ssa_name_ptr_info (indx_before_incr, dr, stmt_info);
vect_duplicate_ssa_name_ptr_info (indx_after_incr, dr, stmt_info);
}
if (ptr_incr)
*ptr_incr = incr;
aptr = indx_before_incr;
}
if (!nested_in_vect_loop || only_init)
return aptr;
/* (4) Handle the updating of the aggregate-pointer inside the inner-loop
nested in LOOP, if exists. */
gcc_assert (nested_in_vect_loop);
if (!only_init)
{
standard_iv_increment_position (containing_loop, &incr_gsi,
&insert_after);
create_iv (aptr, fold_convert (aggr_ptr_type, DR_STEP (dr)), aggr_ptr,
containing_loop, &incr_gsi, insert_after, &indx_before_incr,
&indx_after_incr);
incr = gsi_stmt (incr_gsi);
set_vinfo_for_stmt (incr, new_stmt_vec_info (incr, loop_vinfo, NULL));
/* Copy the points-to information if it exists. */
if (DR_PTR_INFO (dr))
{
vect_duplicate_ssa_name_ptr_info (indx_before_incr, dr, stmt_info);
vect_duplicate_ssa_name_ptr_info (indx_after_incr, dr, stmt_info);
}
if (ptr_incr)
*ptr_incr = incr;
return indx_before_incr;
}
else
gcc_unreachable ();
}
/* Function bump_vector_ptr
Increment a pointer (to a vector type) by vector-size. If requested,
i.e. if PTR-INCR is given, then also connect the new increment stmt
to the existing def-use update-chain of the pointer, by modifying
the PTR_INCR as illustrated below:
The pointer def-use update-chain before this function:
DATAREF_PTR = phi (p_0, p_2)
....
PTR_INCR: p_2 = DATAREF_PTR + step
The pointer def-use update-chain after this function:
DATAREF_PTR = phi (p_0, p_2)
....
NEW_DATAREF_PTR = DATAREF_PTR + BUMP
....
PTR_INCR: p_2 = NEW_DATAREF_PTR + step
Input:
DATAREF_PTR - ssa_name of a pointer (to vector type) that is being updated
in the loop.
PTR_INCR - optional. The stmt that updates the pointer in each iteration of
the loop. The increment amount across iterations is expected
to be vector_size.
BSI - location where the new update stmt is to be placed.
STMT - the original scalar memory-access stmt that is being vectorized.
BUMP - optional. The offset by which to bump the pointer. If not given,
the offset is assumed to be vector_size.
Output: Return NEW_DATAREF_PTR as illustrated above.
*/
tree
bump_vector_ptr (tree dataref_ptr, gimple ptr_incr, gimple_stmt_iterator *gsi,
gimple stmt, tree bump)
{
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
tree update = TYPE_SIZE_UNIT (vectype);
gassign *incr_stmt;
ssa_op_iter iter;
use_operand_p use_p;
tree new_dataref_ptr;
if (bump)
update = bump;
new_dataref_ptr = copy_ssa_name (dataref_ptr);
incr_stmt = gimple_build_assign (new_dataref_ptr, POINTER_PLUS_EXPR,
dataref_ptr, update);
vect_finish_stmt_generation (stmt, incr_stmt, gsi);
/* Copy the points-to information if it exists. */
if (DR_PTR_INFO (dr))
{
duplicate_ssa_name_ptr_info (new_dataref_ptr, DR_PTR_INFO (dr));
mark_ptr_info_alignment_unknown (SSA_NAME_PTR_INFO (new_dataref_ptr));
}
if (!ptr_incr)
return new_dataref_ptr;
/* Update the vector-pointer's cross-iteration increment. */
FOR_EACH_SSA_USE_OPERAND (use_p, ptr_incr, iter, SSA_OP_USE)
{
tree use = USE_FROM_PTR (use_p);
if (use == dataref_ptr)
SET_USE (use_p, new_dataref_ptr);
else
gcc_assert (tree_int_cst_compare (use, update) == 0);
}
return new_dataref_ptr;
}
/* Function vect_create_destination_var.
Create a new temporary of type VECTYPE. */
tree
vect_create_destination_var (tree scalar_dest, tree vectype)
{
tree vec_dest;
const char *name;
char *new_name;
tree type;
enum vect_var_kind kind;
kind = vectype ? vect_simple_var : vect_scalar_var;
type = vectype ? vectype : TREE_TYPE (scalar_dest);
gcc_assert (TREE_CODE (scalar_dest) == SSA_NAME);
name = get_name (scalar_dest);
if (name)
new_name = xasprintf ("%s_%u", name, SSA_NAME_VERSION (scalar_dest));
else
new_name = xasprintf ("_%u", SSA_NAME_VERSION (scalar_dest));
vec_dest = vect_get_new_vect_var (type, kind, new_name);
free (new_name);
return vec_dest;
}
/* Function vect_grouped_store_supported.
Returns TRUE if interleave high and interleave low permutations
are supported, and FALSE otherwise. */
bool
vect_grouped_store_supported (tree vectype, unsigned HOST_WIDE_INT count)
{
machine_mode mode = TYPE_MODE (vectype);
/* vect_permute_store_chain requires the group size to be equal to 3 or
be a power of two. */
if (count != 3 && exact_log2 (count) == -1)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"the size of the group of accesses"
" is not a power of 2 or not eqaul to 3\n");
return false;
}
/* Check that the permutation is supported. */
if (VECTOR_MODE_P (mode))
{
unsigned int i, nelt = GET_MODE_NUNITS (mode);
unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
if (count == 3)
{
unsigned int j0 = 0, j1 = 0, j2 = 0;
unsigned int i, j;
for (j = 0; j < 3; j++)
{
int nelt0 = ((3 - j) * nelt) % 3;
int nelt1 = ((3 - j) * nelt + 1) % 3;
int nelt2 = ((3 - j) * nelt + 2) % 3;
for (i = 0; i < nelt; i++)
{
if (3 * i + nelt0 < nelt)
sel[3 * i + nelt0] = j0++;
if (3 * i + nelt1 < nelt)
sel[3 * i + nelt1] = nelt + j1++;
if (3 * i + nelt2 < nelt)
sel[3 * i + nelt2] = 0;
}
if (!can_vec_perm_p (mode, false, sel))
{
if (dump_enabled_p ())
dump_printf (MSG_MISSED_OPTIMIZATION,
"permutaion op not supported by target.\n");
return false;
}
for (i = 0; i < nelt; i++)
{
if (3 * i + nelt0 < nelt)
sel[3 * i + nelt0] = 3 * i + nelt0;
if (3 * i + nelt1 < nelt)
sel[3 * i + nelt1] = 3 * i + nelt1;
if (3 * i + nelt2 < nelt)
sel[3 * i + nelt2] = nelt + j2++;
}
if (!can_vec_perm_p (mode, false, sel))
{
if (dump_enabled_p ())
dump_printf (MSG_MISSED_OPTIMIZATION,
"permutaion op not supported by target.\n");
return false;
}
}
return true;
}
else
{
/* If length is not equal to 3 then only power of 2 is supported. */
gcc_assert (exact_log2 (count) != -1);
for (i = 0; i < nelt / 2; i++)
{
sel[i * 2] = i;
sel[i * 2 + 1] = i + nelt;
}
if (can_vec_perm_p (mode, false, sel))
{
for (i = 0; i < nelt; i++)
sel[i] += nelt / 2;
if (can_vec_perm_p (mode, false, sel))
return true;
}
}
}
if (dump_enabled_p ())
dump_printf (MSG_MISSED_OPTIMIZATION,
"permutaion op not supported by target.\n");
return false;
}
/* Return TRUE if vec_store_lanes is available for COUNT vectors of
type VECTYPE. */
bool
vect_store_lanes_supported (tree vectype, unsigned HOST_WIDE_INT count)
{
return vect_lanes_optab_supported_p ("vec_store_lanes",
vec_store_lanes_optab,
vectype, count);
}
/* Function vect_permute_store_chain.
Given a chain of interleaved stores in DR_CHAIN of LENGTH that must be
a power of 2 or equal to 3, generate interleave_high/low stmts to reorder
the data correctly for the stores. Return the final references for stores
in RESULT_CHAIN.
E.g., LENGTH is 4 and the scalar type is short, i.e., VF is 8.
The input is 4 vectors each containing 8 elements. We assign a number to
each element, the input sequence is:
1st vec: 0 1 2 3 4 5 6 7
2nd vec: 8 9 10 11 12 13 14 15
3rd vec: 16 17 18 19 20 21 22 23
4th vec: 24 25 26 27 28 29 30 31
The output sequence should be:
1st vec: 0 8 16 24 1 9 17 25
2nd vec: 2 10 18 26 3 11 19 27
3rd vec: 4 12 20 28 5 13 21 30
4th vec: 6 14 22 30 7 15 23 31
i.e., we interleave the contents of the four vectors in their order.
We use interleave_high/low instructions to create such output. The input of
each interleave_high/low operation is two vectors:
1st vec 2nd vec
0 1 2 3 4 5 6 7
the even elements of the result vector are obtained left-to-right from the
high/low elements of the first vector. The odd elements of the result are
obtained left-to-right from the high/low elements of the second vector.
The output of interleave_high will be: 0 4 1 5
and of interleave_low: 2 6 3 7
The permutation is done in log LENGTH stages. In each stage interleave_high
and interleave_low stmts are created for each pair of vectors in DR_CHAIN,
where the first argument is taken from the first half of DR_CHAIN and the
second argument from it's second half.
In our example,
I1: interleave_high (1st vec, 3rd vec)
I2: interleave_low (1st vec, 3rd vec)
I3: interleave_high (2nd vec, 4th vec)
I4: interleave_low (2nd vec, 4th vec)
The output for the first stage is:
I1: 0 16 1 17 2 18 3 19
I2: 4 20 5 21 6 22 7 23
I3: 8 24 9 25 10 26 11 27
I4: 12 28 13 29 14 30 15 31
The output of the second stage, i.e. the final result is:
I1: 0 8 16 24 1 9 17 25
I2: 2 10 18 26 3 11 19 27
I3: 4 12 20 28 5 13 21 30
I4: 6 14 22 30 7 15 23 31. */
void
vect_permute_store_chain (vec<tree> dr_chain,
unsigned int length,
gimple stmt,
gimple_stmt_iterator *gsi,
vec<tree> *result_chain)
{
tree vect1, vect2, high, low;
gimple perm_stmt;
tree vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (stmt));
tree perm_mask_low, perm_mask_high;
tree data_ref;
tree perm3_mask_low, perm3_mask_high;
unsigned int i, n, log_length = exact_log2 (length);
unsigned int j, nelt = TYPE_VECTOR_SUBPARTS (vectype);
unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
result_chain->quick_grow (length);
memcpy (result_chain->address (), dr_chain.address (),
length * sizeof (tree));
if (length == 3)
{
unsigned int j0 = 0, j1 = 0, j2 = 0;
for (j = 0; j < 3; j++)
{
int nelt0 = ((3 - j) * nelt) % 3;
int nelt1 = ((3 - j) * nelt + 1) % 3;
int nelt2 = ((3 - j) * nelt + 2) % 3;
for (i = 0; i < nelt; i++)
{
if (3 * i + nelt0 < nelt)
sel[3 * i + nelt0] = j0++;
if (3 * i + nelt1 < nelt)
sel[3 * i + nelt1] = nelt + j1++;
if (3 * i + nelt2 < nelt)
sel[3 * i + nelt2] = 0;
}
perm3_mask_low = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < nelt; i++)
{
if (3 * i + nelt0 < nelt)
sel[3 * i + nelt0] = 3 * i + nelt0;
if (3 * i + nelt1 < nelt)
sel[3 * i + nelt1] = 3 * i + nelt1;
if (3 * i + nelt2 < nelt)
sel[3 * i + nelt2] = nelt + j2++;
}
perm3_mask_high = vect_gen_perm_mask_checked (vectype, sel);
vect1 = dr_chain[0];
vect2 = dr_chain[1];
/* Create interleaving stmt:
low = VEC_PERM_EXPR <vect1, vect2,
{j, nelt, *, j + 1, nelt + j + 1, *,
j + 2, nelt + j + 2, *, ...}> */
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_low");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect1,
vect2, perm3_mask_low);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect1 = data_ref;
vect2 = dr_chain[2];
/* Create interleaving stmt:
low = VEC_PERM_EXPR <vect1, vect2,
{0, 1, nelt + j, 3, 4, nelt + j + 1,
6, 7, nelt + j + 2, ...}> */
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_high");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect1,
vect2, perm3_mask_high);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[j] = data_ref;
}
}
else
{
/* If length is not equal to 3 then only power of 2 is supported. */
gcc_assert (exact_log2 (length) != -1);
for (i = 0, n = nelt / 2; i < n; i++)
{
sel[i * 2] = i;
sel[i * 2 + 1] = i + nelt;
}
perm_mask_high = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < nelt; i++)
sel[i] += nelt / 2;
perm_mask_low = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0, n = log_length; i < n; i++)
{
for (j = 0; j < length/2; j++)
{
vect1 = dr_chain[j];
vect2 = dr_chain[j+length/2];
/* Create interleaving stmt:
high = VEC_PERM_EXPR <vect1, vect2, {0, nelt, 1, nelt+1,
...}> */
high = make_temp_ssa_name (vectype, NULL, "vect_inter_high");
perm_stmt = gimple_build_assign (high, VEC_PERM_EXPR, vect1,
vect2, perm_mask_high);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[2*j] = high;
/* Create interleaving stmt:
low = VEC_PERM_EXPR <vect1, vect2,
{nelt/2, nelt*3/2, nelt/2+1, nelt*3/2+1,
...}> */
low = make_temp_ssa_name (vectype, NULL, "vect_inter_low");
perm_stmt = gimple_build_assign (low, VEC_PERM_EXPR, vect1,
vect2, perm_mask_low);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[2*j+1] = low;
}
memcpy (dr_chain.address (), result_chain->address (),
length * sizeof (tree));
}
}
}
/* Function vect_setup_realignment
This function is called when vectorizing an unaligned load using
the dr_explicit_realign[_optimized] scheme.
This function generates the following code at the loop prolog:
p = initial_addr;
x msq_init = *(floor(p)); # prolog load
realignment_token = call target_builtin;
loop:
x msq = phi (msq_init, ---)
The stmts marked with x are generated only for the case of
dr_explicit_realign_optimized.
The code above sets up a new (vector) pointer, pointing to the first
location accessed by STMT, and a "floor-aligned" load using that pointer.
It also generates code to compute the "realignment-token" (if the relevant
target hook was defined), and creates a phi-node at the loop-header bb
whose arguments are the result of the prolog-load (created by this
function) and the result of a load that takes place in the loop (to be
created by the caller to this function).
For the case of dr_explicit_realign_optimized:
The caller to this function uses the phi-result (msq) to create the
realignment code inside the loop, and sets up the missing phi argument,
as follows:
loop:
msq = phi (msq_init, lsq)
lsq = *(floor(p')); # load in loop
result = realign_load (msq, lsq, realignment_token);
For the case of dr_explicit_realign:
loop:
msq = *(floor(p)); # load in loop
p' = p + (VS-1);
lsq = *(floor(p')); # load in loop
result = realign_load (msq, lsq, realignment_token);
Input:
STMT - (scalar) load stmt to be vectorized. This load accesses
a memory location that may be unaligned.
BSI - place where new code is to be inserted.
ALIGNMENT_SUPPORT_SCHEME - which of the two misalignment handling schemes
is used.
Output:
REALIGNMENT_TOKEN - the result of a call to the builtin_mask_for_load
target hook, if defined.
Return value - the result of the loop-header phi node. */
tree
vect_setup_realignment (gimple stmt, gimple_stmt_iterator *gsi,
tree *realignment_token,
enum dr_alignment_support alignment_support_scheme,
tree init_addr,
struct loop **at_loop)
{
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
struct data_reference *dr = STMT_VINFO_DATA_REF (stmt_info);
struct loop *loop = NULL;
edge pe = NULL;
tree scalar_dest = gimple_assign_lhs (stmt);
tree vec_dest;
gimple inc;
tree ptr;
tree data_ref;
basic_block new_bb;
tree msq_init = NULL_TREE;
tree new_temp;
gphi *phi_stmt;
tree msq = NULL_TREE;
gimple_seq stmts = NULL;
bool inv_p;
bool compute_in_loop = false;
bool nested_in_vect_loop = false;
struct loop *containing_loop = (gimple_bb (stmt))->loop_father;
struct loop *loop_for_initial_load = NULL;
if (loop_vinfo)
{
loop = LOOP_VINFO_LOOP (loop_vinfo);
nested_in_vect_loop = nested_in_vect_loop_p (loop, stmt);
}
gcc_assert (alignment_support_scheme == dr_explicit_realign
|| alignment_support_scheme == dr_explicit_realign_optimized);
/* We need to generate three things:
1. the misalignment computation
2. the extra vector load (for the optimized realignment scheme).
3. the phi node for the two vectors from which the realignment is
done (for the optimized realignment scheme). */
/* 1. Determine where to generate the misalignment computation.
If INIT_ADDR is NULL_TREE, this indicates that the misalignment
calculation will be generated by this function, outside the loop (in the
preheader). Otherwise, INIT_ADDR had already been computed for us by the
caller, inside the loop.
Background: If the misalignment remains fixed throughout the iterations of
the loop, then both realignment schemes are applicable, and also the
misalignment computation can be done outside LOOP. This is because we are
vectorizing LOOP, and so the memory accesses in LOOP advance in steps that
are a multiple of VS (the Vector Size), and therefore the misalignment in
different vectorized LOOP iterations is always the same.
The problem arises only if the memory access is in an inner-loop nested
inside LOOP, which is now being vectorized using outer-loop vectorization.
This is the only case when the misalignment of the memory access may not
remain fixed throughout the iterations of the inner-loop (as explained in
detail in vect_supportable_dr_alignment). In this case, not only is the
optimized realignment scheme not applicable, but also the misalignment
computation (and generation of the realignment token that is passed to
REALIGN_LOAD) have to be done inside the loop.
In short, INIT_ADDR indicates whether we are in a COMPUTE_IN_LOOP mode
or not, which in turn determines if the misalignment is computed inside
the inner-loop, or outside LOOP. */
if (init_addr != NULL_TREE || !loop_vinfo)
{
compute_in_loop = true;
gcc_assert (alignment_support_scheme == dr_explicit_realign);
}
/* 2. Determine where to generate the extra vector load.
For the optimized realignment scheme, instead of generating two vector
loads in each iteration, we generate a single extra vector load in the
preheader of the loop, and in each iteration reuse the result of the
vector load from the previous iteration. In case the memory access is in
an inner-loop nested inside LOOP, which is now being vectorized using
outer-loop vectorization, we need to determine whether this initial vector
load should be generated at the preheader of the inner-loop, or can be
generated at the preheader of LOOP. If the memory access has no evolution
in LOOP, it can be generated in the preheader of LOOP. Otherwise, it has
to be generated inside LOOP (in the preheader of the inner-loop). */
if (nested_in_vect_loop)
{
tree outerloop_step = STMT_VINFO_DR_STEP (stmt_info);
bool invariant_in_outerloop =
(tree_int_cst_compare (outerloop_step, size_zero_node) == 0);
loop_for_initial_load = (invariant_in_outerloop ? loop : loop->inner);
}
else
loop_for_initial_load = loop;
if (at_loop)
*at_loop = loop_for_initial_load;
if (loop_for_initial_load)
pe = loop_preheader_edge (loop_for_initial_load);
/* 3. For the case of the optimized realignment, create the first vector
load at the loop preheader. */
if (alignment_support_scheme == dr_explicit_realign_optimized)
{
/* Create msq_init = *(floor(p1)) in the loop preheader */
gassign *new_stmt;
gcc_assert (!compute_in_loop);
vec_dest = vect_create_destination_var (scalar_dest, vectype);
ptr = vect_create_data_ref_ptr (stmt, vectype, loop_for_initial_load,
NULL_TREE, &init_addr, NULL, &inc,
true, &inv_p);
new_temp = copy_ssa_name (ptr);
new_stmt = gimple_build_assign
(new_temp, BIT_AND_EXPR, ptr,
build_int_cst (TREE_TYPE (ptr),
-(HOST_WIDE_INT)TYPE_ALIGN_UNIT (vectype)));
new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
gcc_assert (!new_bb);
data_ref
= build2 (MEM_REF, TREE_TYPE (vec_dest), new_temp,
build_int_cst (reference_alias_ptr_type (DR_REF (dr)), 0));
new_stmt = gimple_build_assign (vec_dest, data_ref);
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_assign_set_lhs (new_stmt, new_temp);
if (pe)
{
new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
gcc_assert (!new_bb);
}
else
gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
msq_init = gimple_assign_lhs (new_stmt);
}
/* 4. Create realignment token using a target builtin, if available.
It is done either inside the containing loop, or before LOOP (as
determined above). */
if (targetm.vectorize.builtin_mask_for_load)
{
gcall *new_stmt;
tree builtin_decl;
/* Compute INIT_ADDR - the initial addressed accessed by this memref. */
if (!init_addr)
{
/* Generate the INIT_ADDR computation outside LOOP. */
init_addr = vect_create_addr_base_for_vector_ref (stmt, &stmts,
NULL_TREE, loop);
if (loop)
{
pe = loop_preheader_edge (loop);
new_bb = gsi_insert_seq_on_edge_immediate (pe, stmts);
gcc_assert (!new_bb);
}
else
gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
}
builtin_decl = targetm.vectorize.builtin_mask_for_load ();
new_stmt = gimple_build_call (builtin_decl, 1, init_addr);
vec_dest =
vect_create_destination_var (scalar_dest,
gimple_call_return_type (new_stmt));
new_temp = make_ssa_name (vec_dest, new_stmt);
gimple_call_set_lhs (new_stmt, new_temp);
if (compute_in_loop)
gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
else
{
/* Generate the misalignment computation outside LOOP. */
pe = loop_preheader_edge (loop);
new_bb = gsi_insert_on_edge_immediate (pe, new_stmt);
gcc_assert (!new_bb);
}
*realignment_token = gimple_call_lhs (new_stmt);
/* The result of the CALL_EXPR to this builtin is determined from
the value of the parameter and no global variables are touched
which makes the builtin a "const" function. Requiring the
builtin to have the "const" attribute makes it unnecessary
to call mark_call_clobbered. */
gcc_assert (TREE_READONLY (builtin_decl));
}
if (alignment_support_scheme == dr_explicit_realign)
return msq;
gcc_assert (!compute_in_loop);
gcc_assert (alignment_support_scheme == dr_explicit_realign_optimized);
/* 5. Create msq = phi <msq_init, lsq> in loop */
pe = loop_preheader_edge (containing_loop);
vec_dest = vect_create_destination_var (scalar_dest, vectype);
msq = make_ssa_name (vec_dest);
phi_stmt = create_phi_node (msq, containing_loop->header);
add_phi_arg (phi_stmt, msq_init, pe, UNKNOWN_LOCATION);
return msq;
}
/* Function vect_grouped_load_supported.
Returns TRUE if even and odd permutations are supported,
and FALSE otherwise. */
bool
vect_grouped_load_supported (tree vectype, unsigned HOST_WIDE_INT count)
{
machine_mode mode = TYPE_MODE (vectype);
/* vect_permute_load_chain requires the group size to be equal to 3 or
be a power of two. */
if (count != 3 && exact_log2 (count) == -1)
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"the size of the group of accesses"
" is not a power of 2 or not equal to 3\n");
return false;
}
/* Check that the permutation is supported. */
if (VECTOR_MODE_P (mode))
{
unsigned int i, j, nelt = GET_MODE_NUNITS (mode);
unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
if (count == 3)
{
unsigned int k;
for (k = 0; k < 3; k++)
{
for (i = 0; i < nelt; i++)
if (3 * i + k < 2 * nelt)
sel[i] = 3 * i + k;
else
sel[i] = 0;
if (!can_vec_perm_p (mode, false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shuffle of 3 loads is not supported by"
" target\n");
return false;
}
for (i = 0, j = 0; i < nelt; i++)
if (3 * i + k < 2 * nelt)
sel[i] = i;
else
sel[i] = nelt + ((nelt + k) % 3) + 3 * (j++);
if (!can_vec_perm_p (mode, false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shuffle of 3 loads is not supported by"
" target\n");
return false;
}
}
return true;
}
else
{
/* If length is not equal to 3 then only power of 2 is supported. */
gcc_assert (exact_log2 (count) != -1);
for (i = 0; i < nelt; i++)
sel[i] = i * 2;
if (can_vec_perm_p (mode, false, sel))
{
for (i = 0; i < nelt; i++)
sel[i] = i * 2 + 1;
if (can_vec_perm_p (mode, false, sel))
return true;
}
}
}
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"extract even/odd not supported by target\n");
return false;
}
/* Return TRUE if vec_load_lanes is available for COUNT vectors of
type VECTYPE. */
bool
vect_load_lanes_supported (tree vectype, unsigned HOST_WIDE_INT count)
{
return vect_lanes_optab_supported_p ("vec_load_lanes",
vec_load_lanes_optab,
vectype, count);
}
/* Function vect_permute_load_chain.
Given a chain of interleaved loads in DR_CHAIN of LENGTH that must be
a power of 2 or equal to 3, generate extract_even/odd stmts to reorder
the input data correctly. Return the final references for loads in
RESULT_CHAIN.
E.g., LENGTH is 4 and the scalar type is short, i.e., VF is 8.
The input is 4 vectors each containing 8 elements. We assign a number to each
element, the input sequence is:
1st vec: 0 1 2 3 4 5 6 7
2nd vec: 8 9 10 11 12 13 14 15
3rd vec: 16 17 18 19 20 21 22 23
4th vec: 24 25 26 27 28 29 30 31
The output sequence should be:
1st vec: 0 4 8 12 16 20 24 28
2nd vec: 1 5 9 13 17 21 25 29
3rd vec: 2 6 10 14 18 22 26 30
4th vec: 3 7 11 15 19 23 27 31
i.e., the first output vector should contain the first elements of each
interleaving group, etc.
We use extract_even/odd instructions to create such output. The input of
each extract_even/odd operation is two vectors
1st vec 2nd vec
0 1 2 3 4 5 6 7
and the output is the vector of extracted even/odd elements. The output of
extract_even will be: 0 2 4 6
and of extract_odd: 1 3 5 7
The permutation is done in log LENGTH stages. In each stage extract_even
and extract_odd stmts are created for each pair of vectors in DR_CHAIN in
their order. In our example,
E1: extract_even (1st vec, 2nd vec)
E2: extract_odd (1st vec, 2nd vec)
E3: extract_even (3rd vec, 4th vec)
E4: extract_odd (3rd vec, 4th vec)
The output for the first stage will be:
E1: 0 2 4 6 8 10 12 14
E2: 1 3 5 7 9 11 13 15
E3: 16 18 20 22 24 26 28 30
E4: 17 19 21 23 25 27 29 31
In order to proceed and create the correct sequence for the next stage (or
for the correct output, if the second stage is the last one, as in our
example), we first put the output of extract_even operation and then the
output of extract_odd in RESULT_CHAIN (which is then copied to DR_CHAIN).
The input for the second stage is:
1st vec (E1): 0 2 4 6 8 10 12 14
2nd vec (E3): 16 18 20 22 24 26 28 30
3rd vec (E2): 1 3 5 7 9 11 13 15
4th vec (E4): 17 19 21 23 25 27 29 31
The output of the second stage:
E1: 0 4 8 12 16 20 24 28
E2: 2 6 10 14 18 22 26 30
E3: 1 5 9 13 17 21 25 29
E4: 3 7 11 15 19 23 27 31
And RESULT_CHAIN after reordering:
1st vec (E1): 0 4 8 12 16 20 24 28
2nd vec (E3): 1 5 9 13 17 21 25 29
3rd vec (E2): 2 6 10 14 18 22 26 30
4th vec (E4): 3 7 11 15 19 23 27 31. */
static void
vect_permute_load_chain (vec<tree> dr_chain,
unsigned int length,
gimple stmt,
gimple_stmt_iterator *gsi,
vec<tree> *result_chain)
{
tree data_ref, first_vect, second_vect;
tree perm_mask_even, perm_mask_odd;
tree perm3_mask_low, perm3_mask_high;
gimple perm_stmt;
tree vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (stmt));
unsigned int i, j, log_length = exact_log2 (length);
unsigned nelt = TYPE_VECTOR_SUBPARTS (vectype);
unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
result_chain->quick_grow (length);
memcpy (result_chain->address (), dr_chain.address (),
length * sizeof (tree));
if (length == 3)
{
unsigned int k;
for (k = 0; k < 3; k++)
{
for (i = 0; i < nelt; i++)
if (3 * i + k < 2 * nelt)
sel[i] = 3 * i + k;
else
sel[i] = 0;
perm3_mask_low = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0, j = 0; i < nelt; i++)
if (3 * i + k < 2 * nelt)
sel[i] = i;
else
sel[i] = nelt + ((nelt + k) % 3) + 3 * (j++);
perm3_mask_high = vect_gen_perm_mask_checked (vectype, sel);
first_vect = dr_chain[0];
second_vect = dr_chain[1];
/* Create interleaving stmt (low part of):
low = VEC_PERM_EXPR <first_vect, second_vect2, {k, 3 + k, 6 + k,
...}> */
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_low");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, first_vect,
second_vect, perm3_mask_low);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
/* Create interleaving stmt (high part of):
high = VEC_PERM_EXPR <first_vect, second_vect2, {k, 3 + k, 6 + k,
...}> */
first_vect = data_ref;
second_vect = dr_chain[2];
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3_high");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, first_vect,
second_vect, perm3_mask_high);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[k] = data_ref;
}
}
else
{
/* If length is not equal to 3 then only power of 2 is supported. */
gcc_assert (exact_log2 (length) != -1);
for (i = 0; i < nelt; ++i)
sel[i] = i * 2;
perm_mask_even = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < nelt; ++i)
sel[i] = i * 2 + 1;
perm_mask_odd = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < log_length; i++)
{
for (j = 0; j < length; j += 2)
{
first_vect = dr_chain[j];
second_vect = dr_chain[j+1];
/* data_ref = permute_even (first_data_ref, second_data_ref); */
data_ref = make_temp_ssa_name (vectype, NULL, "vect_perm_even");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
first_vect, second_vect,
perm_mask_even);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[j/2] = data_ref;
/* data_ref = permute_odd (first_data_ref, second_data_ref); */
data_ref = make_temp_ssa_name (vectype, NULL, "vect_perm_odd");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
first_vect, second_vect,
perm_mask_odd);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[j/2+length/2] = data_ref;
}
memcpy (dr_chain.address (), result_chain->address (),
length * sizeof (tree));
}
}
}
/* Function vect_shift_permute_load_chain.
Given a chain of loads in DR_CHAIN of LENGTH 2 or 3, generate
sequence of stmts to reorder the input data accordingly.
Return the final references for loads in RESULT_CHAIN.
Return true if successed, false otherwise.
E.g., LENGTH is 3 and the scalar type is short, i.e., VF is 8.
The input is 3 vectors each containing 8 elements. We assign a
number to each element, the input sequence is:
1st vec: 0 1 2 3 4 5 6 7
2nd vec: 8 9 10 11 12 13 14 15
3rd vec: 16 17 18 19 20 21 22 23
The output sequence should be:
1st vec: 0 3 6 9 12 15 18 21
2nd vec: 1 4 7 10 13 16 19 22
3rd vec: 2 5 8 11 14 17 20 23
We use 3 shuffle instructions and 3 * 3 - 1 shifts to create such output.
First we shuffle all 3 vectors to get correct elements order:
1st vec: ( 0 3 6) ( 1 4 7) ( 2 5)
2nd vec: ( 8 11 14) ( 9 12 15) (10 13)
3rd vec: (16 19 22) (17 20 23) (18 21)
Next we unite and shift vector 3 times:
1st step:
shift right by 6 the concatenation of:
"1st vec" and "2nd vec"
( 0 3 6) ( 1 4 7) |( 2 5) _ ( 8 11 14) ( 9 12 15)| (10 13)
"2nd vec" and "3rd vec"
( 8 11 14) ( 9 12 15) |(10 13) _ (16 19 22) (17 20 23)| (18 21)
"3rd vec" and "1st vec"
(16 19 22) (17 20 23) |(18 21) _ ( 0 3 6) ( 1 4 7)| ( 2 5)
| New vectors |
So that now new vectors are:
1st vec: ( 2 5) ( 8 11 14) ( 9 12 15)
2nd vec: (10 13) (16 19 22) (17 20 23)
3rd vec: (18 21) ( 0 3 6) ( 1 4 7)
2nd step:
shift right by 5 the concatenation of:
"1st vec" and "3rd vec"
( 2 5) ( 8 11 14) |( 9 12 15) _ (18 21) ( 0 3 6)| ( 1 4 7)
"2nd vec" and "1st vec"
(10 13) (16 19 22) |(17 20 23) _ ( 2 5) ( 8 11 14)| ( 9 12 15)
"3rd vec" and "2nd vec"
(18 21) ( 0 3 6) |( 1 4 7) _ (10 13) (16 19 22)| (17 20 23)
| New vectors |
So that now new vectors are:
1st vec: ( 9 12 15) (18 21) ( 0 3 6)
2nd vec: (17 20 23) ( 2 5) ( 8 11 14)
3rd vec: ( 1 4 7) (10 13) (16 19 22) READY
3rd step:
shift right by 5 the concatenation of:
"1st vec" and "1st vec"
( 9 12 15) (18 21) |( 0 3 6) _ ( 9 12 15) (18 21)| ( 0 3 6)
shift right by 3 the concatenation of:
"2nd vec" and "2nd vec"
(17 20 23) |( 2 5) ( 8 11 14) _ (17 20 23)| ( 2 5) ( 8 11 14)
| New vectors |
So that now all vectors are READY:
1st vec: ( 0 3 6) ( 9 12 15) (18 21)
2nd vec: ( 2 5) ( 8 11 14) (17 20 23)
3rd vec: ( 1 4 7) (10 13) (16 19 22)
This algorithm is faster than one in vect_permute_load_chain if:
1. "shift of a concatination" is faster than general permutation.
This is usually so.
2. The TARGET machine can't execute vector instructions in parallel.
This is because each step of the algorithm depends on previous.
The algorithm in vect_permute_load_chain is much more parallel.
The algorithm is applicable only for LOAD CHAIN LENGTH less than VF.
*/
static bool
vect_shift_permute_load_chain (vec<tree> dr_chain,
unsigned int length,
gimple stmt,
gimple_stmt_iterator *gsi,
vec<tree> *result_chain)
{
tree vect[3], vect_shift[3], data_ref, first_vect, second_vect;
tree perm2_mask1, perm2_mask2, perm3_mask;
tree select_mask, shift1_mask, shift2_mask, shift3_mask, shift4_mask;
gimple perm_stmt;
tree vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (stmt));
unsigned int i;
unsigned nelt = TYPE_VECTOR_SUBPARTS (vectype);
unsigned char *sel = XALLOCAVEC (unsigned char, nelt);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
result_chain->quick_grow (length);
memcpy (result_chain->address (), dr_chain.address (),
length * sizeof (tree));
if (exact_log2 (length) != -1 && LOOP_VINFO_VECT_FACTOR (loop_vinfo) > 4)
{
unsigned int j, log_length = exact_log2 (length);
for (i = 0; i < nelt / 2; ++i)
sel[i] = i * 2;
for (i = 0; i < nelt / 2; ++i)
sel[nelt / 2 + i] = i * 2 + 1;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shuffle of 2 fields structure is not \
supported by target\n");
return false;
}
perm2_mask1 = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < nelt / 2; ++i)
sel[i] = i * 2 + 1;
for (i = 0; i < nelt / 2; ++i)
sel[nelt / 2 + i] = i * 2;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shuffle of 2 fields structure is not \
supported by target\n");
return false;
}
perm2_mask2 = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to shift all elements.
For vector length 8 it is {4 5 6 7 8 9 10 11}. */
for (i = 0; i < nelt; i++)
sel[i] = nelt / 2 + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shift permutation is not supported by target\n");
return false;
}
shift1_mask = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to select vector from 2.
For vector length 8 it is {0 1 2 3 12 13 14 15}. */
for (i = 0; i < nelt / 2; i++)
sel[i] = i;
for (i = nelt / 2; i < nelt; i++)
sel[i] = nelt + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"select is not supported by target\n");
return false;
}
select_mask = vect_gen_perm_mask_checked (vectype, sel);
for (i = 0; i < log_length; i++)
{
for (j = 0; j < length; j += 2)
{
first_vect = dr_chain[j];
second_vect = dr_chain[j + 1];
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle2");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
first_vect, first_vect,
perm2_mask1);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect[0] = data_ref;
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle2");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
second_vect, second_vect,
perm2_mask2);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect[1] = data_ref;
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
vect[0], vect[1], shift1_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[j/2 + length/2] = data_ref;
data_ref = make_temp_ssa_name (vectype, NULL, "vect_select");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
vect[0], vect[1], select_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[j/2] = data_ref;
}
memcpy (dr_chain.address (), result_chain->address (),
length * sizeof (tree));
}
return true;
}
if (length == 3 && LOOP_VINFO_VECT_FACTOR (loop_vinfo) > 2)
{
unsigned int k = 0, l = 0;
/* Generating permutation constant to get all elements in rigth order.
For vector length 8 it is {0 3 6 1 4 7 2 5}. */
for (i = 0; i < nelt; i++)
{
if (3 * k + (l % 3) >= nelt)
{
k = 0;
l += (3 - (nelt % 3));
}
sel[i] = 3 * k + (l % 3);
k++;
}
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shuffle of 3 fields structure is not \
supported by target\n");
return false;
}
perm3_mask = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to shift all elements.
For vector length 8 it is {6 7 8 9 10 11 12 13}. */
for (i = 0; i < nelt; i++)
sel[i] = 2 * (nelt / 3) + (nelt % 3) + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shift permutation is not supported by target\n");
return false;
}
shift1_mask = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to shift all elements.
For vector length 8 it is {5 6 7 8 9 10 11 12}. */
for (i = 0; i < nelt; i++)
sel[i] = 2 * (nelt / 3) + 1 + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shift permutation is not supported by target\n");
return false;
}
shift2_mask = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to shift all elements.
For vector length 8 it is {3 4 5 6 7 8 9 10}. */
for (i = 0; i < nelt; i++)
sel[i] = (nelt / 3) + (nelt % 3) / 2 + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shift permutation is not supported by target\n");
return false;
}
shift3_mask = vect_gen_perm_mask_checked (vectype, sel);
/* Generating permutation constant to shift all elements.
For vector length 8 it is {5 6 7 8 9 10 11 12}. */
for (i = 0; i < nelt; i++)
sel[i] = 2 * (nelt / 3) + (nelt % 3) / 2 + i;
if (!can_vec_perm_p (TYPE_MODE (vectype), false, sel))
{
if (dump_enabled_p ())
dump_printf_loc (MSG_MISSED_OPTIMIZATION, vect_location,
"shift permutation is not supported by target\n");
return false;
}
shift4_mask = vect_gen_perm_mask_checked (vectype, sel);
for (k = 0; k < 3; k++)
{
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shuffle3");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
dr_chain[k], dr_chain[k],
perm3_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect[k] = data_ref;
}
for (k = 0; k < 3; k++)
{
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift1");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
vect[k % 3], vect[(k + 1) % 3],
shift1_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect_shift[k] = data_ref;
}
for (k = 0; k < 3; k++)
{
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift2");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR,
vect_shift[(4 - k) % 3],
vect_shift[(3 - k) % 3],
shift2_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
vect[k] = data_ref;
}
(*result_chain)[3 - (nelt % 3)] = vect[2];
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift3");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect[0],
vect[0], shift3_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[nelt % 3] = data_ref;
data_ref = make_temp_ssa_name (vectype, NULL, "vect_shift4");
perm_stmt = gimple_build_assign (data_ref, VEC_PERM_EXPR, vect[1],
vect[1], shift4_mask);
vect_finish_stmt_generation (stmt, perm_stmt, gsi);
(*result_chain)[0] = data_ref;
return true;
}
return false;
}
/* Function vect_transform_grouped_load.
Given a chain of input interleaved data-refs (in DR_CHAIN), build statements
to perform their permutation and ascribe the result vectorized statements to
the scalar statements.
*/
void
vect_transform_grouped_load (gimple stmt, vec<tree> dr_chain, int size,
gimple_stmt_iterator *gsi)
{
machine_mode mode;
vec<tree> result_chain = vNULL;
/* DR_CHAIN contains input data-refs that are a part of the interleaving.
RESULT_CHAIN is the output of vect_permute_load_chain, it contains permuted
vectors, that are ready for vector computation. */
result_chain.create (size);
/* If reassociation width for vector type is 2 or greater target machine can
execute 2 or more vector instructions in parallel. Otherwise try to
get chain for loads group using vect_shift_permute_load_chain. */
mode = TYPE_MODE (STMT_VINFO_VECTYPE (vinfo_for_stmt (stmt)));
if (targetm.sched.reassociation_width (VEC_PERM_EXPR, mode) > 1
|| exact_log2 (size) != -1
|| !vect_shift_permute_load_chain (dr_chain, size, stmt,
gsi, &result_chain))
vect_permute_load_chain (dr_chain, size, stmt, gsi, &result_chain);
vect_record_grouped_load_vectors (stmt, result_chain);
result_chain.release ();
}
/* RESULT_CHAIN contains the output of a group of grouped loads that were
generated as part of the vectorization of STMT. Assign the statement
for each vector to the associated scalar statement. */
void
vect_record_grouped_load_vectors (gimple stmt, vec<tree> result_chain)
{
gimple first_stmt = GROUP_FIRST_ELEMENT (vinfo_for_stmt (stmt));
gimple next_stmt, new_stmt;
unsigned int i, gap_count;
tree tmp_data_ref;
/* Put a permuted data-ref in the VECTORIZED_STMT field.
Since we scan the chain starting from it's first node, their order
corresponds the order of data-refs in RESULT_CHAIN. */
next_stmt = first_stmt;
gap_count = 1;
FOR_EACH_VEC_ELT (result_chain, i, tmp_data_ref)
{
if (!next_stmt)
break;
/* Skip the gaps. Loads created for the gaps will be removed by dead
code elimination pass later. No need to check for the first stmt in
the group, since it always exists.
GROUP_GAP is the number of steps in elements from the previous
access (if there is no gap GROUP_GAP is 1). We skip loads that
correspond to the gaps. */
if (next_stmt != first_stmt
&& gap_count < GROUP_GAP (vinfo_for_stmt (next_stmt)))
{
gap_count++;
continue;
}
while (next_stmt)
{
new_stmt = SSA_NAME_DEF_STMT (tmp_data_ref);
/* We assume that if VEC_STMT is not NULL, this is a case of multiple
copies, and we put the new vector statement in the first available
RELATED_STMT. */
if (!STMT_VINFO_VEC_STMT (vinfo_for_stmt (next_stmt)))
STMT_VINFO_VEC_STMT (vinfo_for_stmt (next_stmt)) = new_stmt;
else
{
if (!GROUP_SAME_DR_STMT (vinfo_for_stmt (next_stmt)))
{
gimple prev_stmt =
STMT_VINFO_VEC_STMT (vinfo_for_stmt (next_stmt));
gimple rel_stmt =
STMT_VINFO_RELATED_STMT (vinfo_for_stmt (prev_stmt));
while (rel_stmt)
{
prev_stmt = rel_stmt;
rel_stmt =
STMT_VINFO_RELATED_STMT (vinfo_for_stmt (rel_stmt));
}
STMT_VINFO_RELATED_STMT (vinfo_for_stmt (prev_stmt)) =
new_stmt;
}
}
next_stmt = GROUP_NEXT_ELEMENT (vinfo_for_stmt (next_stmt));
gap_count = 1;
/* If NEXT_STMT accesses the same DR as the previous statement,
put the same TMP_DATA_REF as its vectorized statement; otherwise
get the next data-ref from RESULT_CHAIN. */
if (!next_stmt || !GROUP_SAME_DR_STMT (vinfo_for_stmt (next_stmt)))
break;
}
}
}
/* Function vect_force_dr_alignment_p.
Returns whether the alignment of a DECL can be forced to be aligned
on ALIGNMENT bit boundary. */
bool
vect_can_force_dr_alignment_p (const_tree decl, unsigned int alignment)
{
if (TREE_CODE (decl) != VAR_DECL)
return false;
if (decl_in_symtab_p (decl)
&& !symtab_node::get (decl)->can_increase_alignment_p ())
return false;
if (TREE_STATIC (decl))
return (alignment <= MAX_OFILE_ALIGNMENT);
else
return (alignment <= MAX_STACK_ALIGNMENT);
}
/* Return whether the data reference DR is supported with respect to its
alignment.
If CHECK_ALIGNED_ACCESSES is TRUE, check if the access is supported even
it is aligned, i.e., check if it is possible to vectorize it with different
alignment. */
enum dr_alignment_support
vect_supportable_dr_alignment (struct data_reference *dr,
bool check_aligned_accesses)
{
gimple stmt = DR_STMT (dr);
stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
machine_mode mode = TYPE_MODE (vectype);
loop_vec_info loop_vinfo = STMT_VINFO_LOOP_VINFO (stmt_info);
struct loop *vect_loop = NULL;
bool nested_in_vect_loop = false;
if (aligned_access_p (dr) && !check_aligned_accesses)
return dr_aligned;
/* For now assume all conditional loads/stores support unaligned
access without any special code. */
if (is_gimple_call (stmt)
&& gimple_call_internal_p (stmt)
&& (gimple_call_internal_fn (stmt) == IFN_MASK_LOAD
|| gimple_call_internal_fn (stmt) == IFN_MASK_STORE))
return dr_unaligned_supported;
if (loop_vinfo)
{
vect_loop = LOOP_VINFO_LOOP (loop_vinfo);
nested_in_vect_loop = nested_in_vect_loop_p (vect_loop, stmt);
}
/* Possibly unaligned access. */
/* We can choose between using the implicit realignment scheme (generating
a misaligned_move stmt) and the explicit realignment scheme (generating
aligned loads with a REALIGN_LOAD). There are two variants to the
explicit realignment scheme: optimized, and unoptimized.
We can optimize the realignment only if the step between consecutive
vector loads is equal to the vector size. Since the vector memory
accesses advance in steps of VS (Vector Size) in the vectorized loop, it
is guaranteed that the misalignment amount remains the same throughout the
execution of the vectorized loop. Therefore, we can create the
"realignment token" (the permutation mask that is passed to REALIGN_LOAD)
at the loop preheader.
However, in the case of outer-loop vectorization, when vectorizing a
memory access in the inner-loop nested within the LOOP that is now being
vectorized, while it is guaranteed that the misalignment of the
vectorized memory access will remain the same in different outer-loop
iterations, it is *not* guaranteed that is will remain the same throughout
the execution of the inner-loop. This is because the inner-loop advances
with the original scalar step (and not in steps of VS). If the inner-loop
step happens to be a multiple of VS, then the misalignment remains fixed
and we can use the optimized realignment scheme. For example:
for (i=0; i<N; i++)
for (j=0; j<M; j++)
s += a[i+j];
When vectorizing the i-loop in the above example, the step between
consecutive vector loads is 1, and so the misalignment does not remain
fixed across the execution of the inner-loop, and the realignment cannot
be optimized (as illustrated in the following pseudo vectorized loop):
for (i=0; i<N; i+=4)
for (j=0; j<M; j++){
vs += vp[i+j]; // misalignment of &vp[i+j] is {0,1,2,3,0,1,2,3,...}
// when j is {0,1,2,3,4,5,6,7,...} respectively.
// (assuming that we start from an aligned address).
}
We therefore have to use the unoptimized realignment scheme:
for (i=0; i<N; i+=4)
for (j=k; j<M; j+=4)
vs += vp[i+j]; // misalignment of &vp[i+j] is always k (assuming
// that the misalignment of the initial address is
// 0).
The loop can then be vectorized as follows:
for (k=0; k<4; k++){
rt = get_realignment_token (&vp[k]);
for (i=0; i<N; i+=4){
v1 = vp[i+k];
for (j=k; j<M; j+=4){
v2 = vp[i+j+VS-1];
va = REALIGN_LOAD <v1,v2,rt>;
vs += va;
v1 = v2;
}
}
} */
if (DR_IS_READ (dr))
{
bool is_packed = false;
tree type = (TREE_TYPE (DR_REF (dr)));
if (optab_handler (vec_realign_load_optab, mode) != CODE_FOR_nothing
&& (!targetm.vectorize.builtin_mask_for_load
|| targetm.vectorize.builtin_mask_for_load ()))
{
tree vectype = STMT_VINFO_VECTYPE (stmt_info);
if ((nested_in_vect_loop
&& (TREE_INT_CST_LOW (DR_STEP (dr))
!= GET_MODE_SIZE (TYPE_MODE (vectype))))
|| !loop_vinfo)
return dr_explicit_realign;
else
return dr_explicit_realign_optimized;
}
if (!known_alignment_for_access_p (dr))
is_packed = not_size_aligned (DR_REF (dr));
if ((TYPE_USER_ALIGN (type) && !is_packed)
|| targetm.vectorize.
support_vector_misalignment (mode, type,
DR_MISALIGNMENT (dr), is_packed))
/* Can't software pipeline the loads, but can at least do them. */
return dr_unaligned_supported;
}
else
{
bool is_packed = false;
tree type = (TREE_TYPE (DR_REF (dr)));
if (!known_alignment_for_access_p (dr))
is_packed = not_size_aligned (DR_REF (dr));
if ((TYPE_USER_ALIGN (type) && !is_packed)
|| targetm.vectorize.
support_vector_misalignment (mode, type,
DR_MISALIGNMENT (dr), is_packed))
return dr_unaligned_supported;
}
/* Unsupported. */
return dr_unaligned_unsupported;
}
|
Polygon.c | #include "Polygon.h"
#include "utils.h"
void P_init(Polygon *p){
p->_nb_vertices=0;
p->_is_closed=FALSE;
p->_is_filled=FALSE;
p->_is_convex=TRUE;
}
// initialise un polygone (0 sommets)
void P_copy(Polygon *original, Polygon *copie){
int i;
copie->_nb_vertices=original->_nb_vertices;
copie->_is_closed=original->_is_closed;
copie->_is_filled=original->_is_filled;
copie->_is_convex=original->_is_convex;
#pragma omp parallel for
for (i = 0; i < P_MAX_VERTICES; i++) {
copie->_vertices[i]=(Vector)original->_vertices[i];
}
}
// original et copie sont deux polygones déjà alloués.
// Cette fonction copie les donnée
// depuis original vers copie de façon à ce que les
// deux polygones soient identiques.
void P_addVertex(Polygon *P, Vector pos){
int index;
bool is_filled=P->_is_filled;
index=P->_nb_vertices;
if (!is_filled) {
P->_vertices[index]=(Vector)pos;
P->_nb_vertices++;
}
if (P->_nb_vertices==P_MAX_VERTICES) {
P->_is_filled=TRUE;
}
}
// ajoute un sommet au polygone P. Ce nouveau sommet est situé en pos.
void P_removeLastVertex(Polygon *P){
P->_nb_vertices--;
if (P->_nb_vertices<0) {
P->_nb_vertices=0;
}
}
// enlève le dernier sommet de P
void P_draw(Polygon *P){
Vector* tab=P->_vertices;
int nb_vertices=P->_nb_vertices;
bool is_closed=P->_is_closed;
int i;
Vector current;
Vector current2;
if (P->_is_convex) {
//glColor rouge
glColor3d(1,0,0);
}
else{
//glColor bleu
glColor3d(0,0,1);
}
if(is_closed){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_POLYGON);
for (i = 0; i < nb_vertices ; i++) {
current=(Vector) tab[i];
glVertex3f(current.x,current.y,current.z+325);
}
glEnd();
}
else{
if (nb_vertices>1) {
for (i = 0; i < nb_vertices-1; i++) {
current=(Vector) tab[i];
current2=(Vector) tab[i+1];
current.z++;
current2.z++;
drawLine(current,current2);
}
}
}
}
// dessine le polygone P
void P_print(Polygon *P, char *message){
Vector* tab=P->_vertices;
int nb_vertices=P->_nb_vertices;
Vector current;
int i;
for (i = 0; i < nb_vertices; i++) {
current=(Vector) tab[i];
printf("point %d : x %f, y %f, z %f \n",i,current.x,current.y,current.z);
}
}
// Affiche sur une console les données de P
// à des fins de debuggage.
Vector P_center(Polygon *P){
int i;
int x=0,y=0,z=0;
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
for (i = 0; i <nb_vertices; i++) {
x+=vertices[i].x;
y+=vertices[i].y;
z+=vertices[i].z;
}
if(nb_vertices==0) //cas polygone vide
nb_vertices=1;
return V_new(x/nb_vertices,y/nb_vertices,z/nb_vertices);
}
int P_close(Polygon *P){
/*On ajoute un vertex egale au vertex du debut pour tester si le polygone est simple
* puis on l'enleve */
if (!P->_is_closed ){
P_addVertex(P,P->_vertices[0]);
if(P_simple(P)){
P->_is_convex=P_isConvex(P);
P_removeLastVertex(P);
P->_is_closed=TRUE;
return TRUE;
}
else{
P_removeLastVertex(P);
P->_is_closed=FALSE;
return FALSE;
}
}
return FALSE;
}
Vector P_normal(Polygon *P){
if (!P->_is_closed) {
return V_new(0,0,0);
}
Vector* vertices=P->_vertices;
Vector V1=V_substract(vertices[1],vertices[0]);
Vector V2=V_substract(vertices[2],vertices[1]);
Vector normal=V_cross(V1,V2);
Vector normal_unit=V_multiply((double)(1./V_length(normal)),normal);
return normal_unit;
}
void P_translate(Polygon *P, Vector trans){
int i;
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
#pragma omp parallel for
for (i = 0; i < nb_vertices; i++) {
vertices[i].x+=trans.x;
vertices[i].y+=trans.y;
vertices[i].z+=trans.z;
}
}
//Marche uniquement pour de s point avec z=0;
int P_isConvex(Polygon *P){
int i;
int nb_vertices=P->_nb_vertices;
int signe;
if (nb_vertices<3) {
return TRUE;
}
Vector* vertices=P->_vertices;
Vector V1;
Vector V2;
Vector crossProduct;
V1=V_substract(vertices[1],vertices[0]);
V2=V_substract(vertices[2],vertices[1]);
crossProduct=V_cross(V1,V2);
if(crossProduct.z>0)
signe=1;
else
signe=0;
for (i = 1; i < nb_vertices-2; i++) {
V1=V_substract(vertices[i+1],vertices[i]);
V2=V_substract(vertices[i+2],vertices[i+1]);
crossProduct=V_cross(V1,V2);
if(!((crossProduct.z>0 && signe==1) || (crossProduct.z<0 && signe==0)))
return FALSE;
}
if(P->_is_closed){
V1=V_substract(vertices[nb_vertices-1],vertices[nb_vertices-2]);
V2=V_substract(vertices[0],vertices[nb_vertices-1]);
crossProduct=V_cross(V1,V2);
if(!((crossProduct.z>0 && signe==1) || (crossProduct.z<0 && signe==0)))
return FALSE;
}
return TRUE;
}
int P_simple(Polygon *P){
Vector* vertices=P->_vertices;
int nb_vertices=P->_nb_vertices;
Vector last_vertex=vertices[nb_vertices-1];
Vector before_last_vertex=vertices[nb_vertices-2];
int i;
/*Un polygone est toujours simple avec n sommet n < 3*/
if (nb_vertices<3) {
return TRUE;
}
/*On verifie que le dernier segment du polygone coupe un des segment precedent*/
for (i = 0; i < nb_vertices-2; i++) {
if (V_segmentsIntersect(last_vertex,before_last_vertex,vertices[i],vertices[i+1])) {
return FALSE;
}
}
return TRUE;
}
void drawRepereTest(Vector x,Vector y, Vector z,Vector center,int mod){
glColor3d(1,0+mod,0);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*x.x,center.y-10*x.y,325+center.z+10*x.z);
glEnd();
glColor3d(0,1,0+mod);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*y.x,center.y-10*y.y,325+center.z+10*y.z);
glEnd();
glColor3d(0+mod,0,1);
glBegin(GL_LINES);
glVertex3d(center.x,center.y,325+center.z);
glVertex3d(center.x+10*z.x,center.y-10*z.y,325+center.z+10*z.z);
glEnd();
}
//transform un vecteur de A dans B
Vector transform(Vector Ax,Vector Ay,Vector Az,Vector Bx,Vector By,Vector Bz,Vector P){
double newX,newY,newZ;
newX=V_dot(Bx,Ax)*P.x+V_dot(Bx,Ay)*P.y+V_dot(Bx,Az)*P.z;
newY=V_dot(By,Ax)*P.x+V_dot(By,Ay)*P.y+V_dot(By,Az)*P.z;
newZ=V_dot(Bz,Ax)*P.x+V_dot(Bz,Ay)*P.y+V_dot(Bz,Az)*P.z;
return V_new(newX,newY,newZ);
}
void P_rotate(Vector a,Vector b,Vector center,Polygon* P){
int i;
int nb_vertices=P->_nb_vertices;
Vector* vertices=P->_vertices;
b=V_unit(b);
Vector P1;
//repere perlin
Vector bx,by;
V_uxUyFromUz(b,&bx,&by);
//repere normal
Vector ax,ay;
V_uxUyFromUz(a,&ax,&ay);
#pragma omp parallel for
for (i = 0; i <nb_vertices; i++) {
vertices[i]=V_translate(vertices[i],center,1);
P1=V_new(V_decompose(V_substract(vertices[i],center),bx),
V_decompose(V_substract(vertices[i],center),by),
V_decompose(V_substract(vertices[i],center),b));
vertices[i]=V_recompose(P1.x,P1.y,P1.z,ax,ay,a);
vertices[i]=V_translate(vertices[i],center,-1);
}
}
|
omp_test_nest_lock.c | <ompts:test>
<ompts:testdescription>Test which checks the omp_test_nest_lock function.</ompts:testdescription>
<ompts:ompversion>2.0</ompts:ompversion>
<ompts:directive>omp_test_nest_lock</ompts:directive>
<ompts:dependences>omp flush</ompts:dependences>
<ompts:testcode>
#include <stdio.h>
#include "omp_testsuite.h"
static omp_nest_lock_t lck;
int <ompts:testcode:functionname>omp_test_nest_lock</ompts:testcode:functionname>(FILE * logFile)
{
int nr_threads_in_single = 0;
int result = 0;
int nr_iterations = 0;
int i;
omp_init_nest_lock (&lck);
#pragma omp parallel shared(lck)
{
#pragma omp for
for (i = 0; i < LOOPCOUNT; i++)
{
/*omp_set_lock(&lck);*/
<ompts:orphan>
<ompts:check>while(!omp_test_nest_lock (&lck))
{};</ompts:check>
</ompts:orphan>
#pragma omp flush
nr_threads_in_single++;
#pragma omp flush
nr_iterations++;
nr_threads_in_single--;
result = result + nr_threads_in_single;
<ompts:check>omp_unset_nest_lock (&lck);</ompts:check>
}
}
omp_destroy_nest_lock (&lck);
return ((result == 0) && (nr_iterations == LOOPCOUNT));
}
</ompts:testcode>
</ompts:test>
|
pzdr_saidai.c | /* author gumboshi <gumboshi@gmail.com> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
/* #ifdef AVX */
/* #include <immintrin.h> */
/* #include <x86intrin.h> */
/* #endif */
#ifdef _OPENMP
#include <omp.h>
#endif
#include "patterns.h"
#include "pzdr_def.h"
#include "pzdr_saidai.h"
double gettimeofday_sec()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + (double)tv.tv_usec*1e-6;
}
int main(int argc, char* argv[]){
int width = 6;
int hight = 5;
int start = 0;
int end = width*hight;
int specified_end = end;
int reverse_length;
int half_size;
int LS = 0;
int isStrong = 0;
int simuave = 0;
int i;
int useCUDA = 0;
#ifdef CUDA
useCUDA = 1;
#endif
int line = 0;
int way = 0;
int table_size = NORMAL_TABLE;
unsigned seed;
if (argc != 1) {
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-s") == 0) {
i++;
start = atoi(argv[i]);
}
else if (strcmp(argv[i], "-e") == 0) {
i++;
specified_end = atoi(argv[i]);
}
else if (strcmp(argv[i], "-l") == 0) {
i++;
line = atoi(argv[i]);
}
else if (strcmp(argv[i], "-w") == 0) {
i++;
way = atoi(argv[i]);
}
else if (strcmp(argv[i], "-small") == 0) {
table_size = SMALL_TABLE;
}
else if (strcmp(argv[i], "-normal") == 0) {
table_size = NORMAL_TABLE;
}
else if (strcmp(argv[i], "-big") == 0) {
table_size = BIG_TABLE;
}
else if (strcmp(argv[i], "-strong") == 0) {
isStrong = 1;
}
else if (strcmp(argv[i], "-laku") == 0 || strcmp(argv[i], "-paru") == 0) {
LS = LAKU_PARU;
}
else if (strcmp(argv[i], "-krishna") == 0) {
LS = KRISHNA;
}
else if (strcmp(argv[i], "-hero") == 0) {
LS = HERO;
}
else if (strcmp(argv[i], "-sonia") == 0) {
LS = SONIA;
}
else if (strcmp(argv[i], "-noLS") == 0) {
LS = NOLS;
}
else if (strcmp(argv[i], "-ave") == 0) {
simuave = 1;
}
#ifdef CUDA
else if (strcmp(argv[i], "-gpu") == 0) {
useCUDA = 1;
}
else if (strcmp(argv[i], "-cpu") == 0) {
useCUDA = 0;
}
#endif
else if (strcmp(argv[i], "-ID2TN") == 0) {
i++;
unsigned long long ID = atoll(argv[i]);
ID2table(ID, 6, 5);
fprintf(stdout,"please use ID2table.jar (GUI interface)\n");
exit(1);
}
else if (strcmp(argv[i], "-ID2TB") == 0) {
i++;
unsigned long long ID = atoll(argv[i]);
ID2table(ID, 7, 6);
fprintf(stdout,"please see ID2table.jar (GUI interface)\n");
exit(1);
}
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
fprintf(stdout,"options\n");
fprintf(stdout,"-s <arg> : Start number of main color. (default=0)\n");
fprintf(stdout,"-e <arg> : End number of main color. (default=TABLE_SIZE)\n");
fprintf(stdout,"-small : Simulate with 4x5 table\n");
fprintf(stdout,"-normal : Simulate with 5x6 table\n");
fprintf(stdout,"-big : Simulate with 6x7 table\n");
fprintf(stdout,"-l <arg> : Number of \"LINE\"s \n");
fprintf(stdout,"-w <arg> : Number of \"2WAY\"s \n");
fprintf(stdout,"-strong : Use Enhanced Orbs. (drop kyouka)\n");
fprintf(stdout,"-laku, -paru: Simulate with Lakshmi or Parvati leader skill mode. \n");
fprintf(stdout,"-krishna : Simulate with krishna leader skill mode. \n");
fprintf(stdout,"-hero : Simulate with Helo leader skill mode. \n");
fprintf(stdout,"-sonia : Simulate with Red Sonia mode. \n");
fprintf(stdout,"-noLS : Simulate with fixed leader skill. \n");
fprintf(stdout,"-ave : execute 10000 times OCHIKON simulation. \n");
fprintf(stdout,"-gpu : execute by gpu. (To enable gpu mode, type command `make gpu`) \n");
fprintf(stdout,"-cpu : execute by cpu. \n");
fprintf(stdout,"-ID2TN <arg>: print normal size table equivalent of input ID (unsigned long long value) \n");
fprintf(stdout,"-ID2TB <arg>: print big size table equivalent of input ID (unsigned long long value) \n");
fprintf(stdout,"\n *********** example ************ \n");
fprintf(stdout,"(1): to simulate 13-17 ~ 18-12, \n");
fprintf(stdout,"$(exefile) -normal -s 13 -e 18\n\n");
fprintf(stdout,"(2): to simulate Parvati LS with 2way*2, \n");
fprintf(stdout,"$(exefile) -normal -paru -w 2\n\n");
fprintf(stdout,"(3): to simulate with large table, \n");
fprintf(stdout,"$(exefile) -big \n\n");
fprintf(stdout,"(4): OCHIKON simulation, \n");
fprintf(stdout,"$(exefile) -ave \n\n");
fprintf(stdout,"(5): to check the output ID, \n");
fprintf(stdout,"$(exefile) -ID2TN <ID> \n\n");
exit(1);
}
else {
fprintf(stderr,"unknown option. See --help.\n");
exit(1);
}
}
}
unsigned long long *num_patterns;
int *num_patterns_half;
int combo_length;
switch(table_size){
case SMALL_TABLE:
width = 5;
hight = 4;
num_patterns = num_patterns20;
num_patterns_half = num_patterns10;
combo_length = 7;
break;
case NORMAL_TABLE:
width = 6;
hight = 5;
num_patterns = num_patterns30;
num_patterns_half = num_patterns15;
combo_length = 10;
break;
case BIG_TABLE:
width = 7;
hight = 6;
num_patterns = num_patterns42;
num_patterns_half = num_patterns21;
combo_length = 14;
break;
default:
fprintf(stderr,"unknown\n");
exit(1);
}
if(end == specified_end){
end = width * hight;
}else{
end = specified_end;
}
half_size = width*hight/2;
reverse_length = 1 << width;
int bit_count_table[256];
int reversed_bit_table[reverse_length];
init_reversed_bit_table(reversed_bit_table, width);
int *tableID_half_table;
int *tableID_half_prefix;
tableID_half_table = (int*)malloc(sizeof(int)*(1L << half_size));
tableID_half_prefix = (int*)malloc(sizeof(int)*half_size);
init_bit_count_table(bit_count_table);
create_half_tableID(tableID_half_table, tableID_half_prefix, bit_count_table, num_patterns_half, half_size);
if(useCUDA){
#ifdef CUDA
simulate_all_cuda(table_size, start, end, /*bit_count_table, */reversed_bit_table, tableID_half_table, tableID_half_prefix, /*num_patterns,*/ num_patterns_half, width, hight, combo_length, LS, isStrong, line, way, simuave);
#endif
}else{
simulate_all(table_size, start, end, /*bit_count_table, */reversed_bit_table, tableID_half_table, tableID_half_prefix, num_patterns, num_patterns_half, width, hight, combo_length, LS, isStrong, line, way, simuave);
}
free(tableID_half_table);
free(tableID_half_prefix);
return 0;
}
/* void init_combo_info(int *color_combo, int *num_drops_combo, int *isLine_combo, int combo_length){ */
/* int i; */
/* for(i = 0;i < combo_length;i++){ */
/* color_combo[i] = 0; */
/* num_drops_combo[i] = 0; */
/* isLine_combo[i] = 0; */
/* } */
/* } */
void init_bit_count_table(int *bit_count_table){
int i, j;
for(i = 0;i < 256;i++){
int count = 0;
int compared_num = i;
for(j = 0;j < 8;j++){
if((compared_num >> j & 1) == 1){
count++;
}
}
bit_count_table[i] = count;
}
}
void init_reversed_bit_table(int *reversed_bit_table, const int width){
int i, j;
for(i = 0;i < (1 << width);i++){
int ii[width];
for(j = 0;j < width;j++){
ii[j] = ((i >> j) & 1) << (width-1 - j);
}
int sum = 0;
for(j = 0;j < width;j++){
sum += ii[j];
}
reversed_bit_table[i] = sum;
}
}
void create_half_tableID(int *tableID_half_table, int *tableID_half_prefix, int * const bit_count_table, int * const num_patterns, const int half_table_size){
int num_attacks;
int max_tableID = 1 << half_table_size;
int num_chunks = (half_table_size-1)/8+1;
int sum = 0;
for(num_attacks = 0;num_attacks <= half_table_size;num_attacks++){
tableID_half_prefix[num_attacks] = sum;
sum = sum + num_patterns[num_attacks];
}
for(num_attacks = 0;num_attacks <= half_table_size;num_attacks++){
int chunk[num_chunks];
int tableID = 0;
int index = 0;
while(tableID <= max_tableID){
int count = 0;
int i;
for(i = 0;i < num_chunks;i++){
chunk[i] = (tableID >> 8*i ) & 255;
count += bit_count_table[chunk[i]];
}
if(count == num_attacks){
tableID_half_table[index+tableID_half_prefix[num_attacks]] = tableID;
index++;
}
tableID++;
}
}
}
#define WID 7
inline void generate_table_small(unsigned long long tableID, unsigned long long *color_table){
unsigned long long ID = tableID;
unsigned long long b0 = ID & 31;
unsigned long long b1 = (ID >> 5 ) & 31;
unsigned long long b2 = (ID >> 10) & 31;
unsigned long long b3 = (ID >> 15) & 31;
color_table[0] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1));
ID = ~ID;
b0 = ID & 31;
b1 = (ID >> 5 ) & 31;
b2 = (ID >> 10) & 31;
b3 = (ID >> 15) & 31;
color_table[1] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1));
}
#undef WID
#define WID 8
inline void generate_table_normal(unsigned long long tableID, unsigned long long *color_table){
unsigned long long ID = tableID;
unsigned long long b0 = ID & 63;
unsigned long long b1 = (ID >> 6 ) & 63;
unsigned long long b2 = (ID >> 12) & 63;
unsigned long long b3 = (ID >> 18) & 63;
unsigned long long b4 = (ID >> 24) & 63;
color_table[0] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1)) | (b4 << (WID*5+1));
ID = ~ID;
b0 = ID & 63;
b1 = (ID >> 6 ) & 63;
b2 = (ID >> 12) & 63;
b3 = (ID >> 18) & 63;
b4 = (ID >> 24) & 63;
color_table[1] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1)) | (b4 << (WID*5+1));
}
#undef WID
#define WID 9
inline void generate_table_big(unsigned long long tableID, unsigned long long *color_table){
unsigned long long b0, b1, b2, b3, b4, b5;
unsigned long long ID = tableID;
b0 = ID & 127;
b1 = (ID >> 7 ) & 127;
b2 = (ID >> 14) & 127;
b3 = (ID >> 21) & 127;
b4 = (ID >> 28) & 127;
b5 = (ID >> 35) & 127;
color_table[0] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1))
| (b4 << (WID*5+1)) | (b5 << (WID*6+1));
ID = ~ID;
b0 = ID & 127;
b1 = (ID >> 7 ) & 127;
b2 = (ID >> 14) & 127;
b3 = (ID >> 21) & 127;
b4 = (ID >> 28) & 127;
b5 = (ID >> 35) & 127;
color_table[1] = (b0 << (WID+1)) | (b1 << (WID*2+1))
| (b2 << (WID*3+1)) | (b3 << (WID*4+1))
| (b4 << (WID*5+1)) | (b5 << (WID*6+1));
}
/* #ifdef AVX */
/* inline void generate_table_big_simd(__m256i tableID, __m256i *color_table){ */
/* __m256i b0, b1, b2, b3, b4, b5; */
/* __m256i ID; */
/* unsigned long long zero[4]; */
/* zero[0] = 0; */
/* zero[1] = 0; */
/* zero[2] = 0; */
/* zero[3] = 0; */
/* __m256i main_color = _mm256_load_si256((__m256i*)zero); */
/* __m256i sub_color = _mm256_load_si256((__m256i*)zero); */
/* __m256_store_si256(ID,tableID); */
/* b0 = _mm256_srli_epi64(ID,0); */
/* b0 = _mm256_and_si256(b0,127); */
/* b0 = _mm256_srli_epi64(b0,WID+1); */
/* b1 = _mm256_srli_epi64(ID,7); */
/* b1 = _mm256_and_si256(b1,127); */
/* b1 = _mm256_srli_epi64(b1,WID*2+1); */
/* b2 = _mm256_srli_epi64(ID,14); */
/* b2 = _mm256_and_si256(b2,127); */
/* b2 = _mm256_srli_epi64(b2,WID*3+1); */
/* b3 = _mm256_srli_epi64(ID,21); */
/* b3 = _mm256_and_si256(b3,127); */
/* b3 = _mm256_srli_epi64(b3,WID*4+1); */
/* b4 = _mm256_srli_epi64(ID,28); */
/* b4 = _mm256_and_si256(b4,127); */
/* b4 = _mm256_srli_epi64(b4,WID*5+1); */
/* b5 = _mm256_srli_epi64(ID,35); */
/* b5 = _mm256_and_si256(b5,127); */
/* b5 = _mm256_srli_epi64(b5,WID*6+1); */
/* main_color = _mm256_or_si256(b0,b1); */
/* main_color = _mm256_or_si256(main_color,b2); */
/* main_color = _mm256_or_si256(main_color,b3); */
/* main_color = _mm256_or_si256(main_color,b4); */
/* main_color = _mm256_or_si256(main_color,b5); */
/* unsigned long long filter4[4]; */
/* filter4[0] = 0xFFFFFFFFFFFFFFFFLU; */
/* filter4[1] = 0xFFFFFFFFFFFFFFFFLU; */
/* filter4[2] = 0xFFFFFFFFFFFFFFFFLU; */
/* filter4[3] = 0xFFFFFFFFFFFFFFFFLU; */
/* __m256i filter = _mm256_load_si256((__m256i*)(filter4)); */
/* b0 = _mm256_andnot_si256(ID,filter); */
/* b0 = _mm256_and_si256(b0,127); */
/* b0 = _mm256_srli_epi64(b0,WID+1); */
/* b1 = _mm256_srli_epi64(ID,7); */
/* b1 = _mm256_and_si256(b1,127); */
/* b1 = _mm256_srli_epi64(b1,WID*2+1); */
/* b2 = _mm256_srli_epi64(ID,14); */
/* b2 = _mm256_and_si256(b2,127); */
/* b2 = _mm256_srli_epi64(b2,WID*3+1); */
/* b3 = _mm256_srli_epi64(ID,21); */
/* b3 = _mm256_and_si256(b3,127); */
/* b3 = _mm256_srli_epi64(b3,WID*4+1); */
/* b4 = _mm256_srli_epi64(ID,28); */
/* b4 = _mm256_and_si256(b4,127); */
/* b4 = _mm256_srli_epi64(b4,WID*5+1); */
/* b5 = _mm256_srli_epi64(ID,35); */
/* b5 = _mm256_and_si256(b5,127); */
/* b5 = _mm256_srli_epi64(b5,WID*6+1); */
/* sub_color = _mm256_or_si256(b0,b1); */
/* sub_color = _mm256_or_si256(sub_color,b2); */
/* sub_color = _mm256_or_si256(sub_color,b3); */
/* sub_color = _mm256_or_si256(sub_color,b4); */
/* sub_color = _mm256_or_si256(sub_color,b5); */
/* __m256_store_si256(color_table[0],main_color); */
/* __m256_store_si256(color_table[1],sub_color); */
/* } */
/* #endif */
#undef WID
void simulate_all(const int table_size, const int start, const int end, /*int * const bit_count_table,*/ int * const reversed_bit_table, int * const tableID_half_table, int * const tableID_half_prefix, unsigned long long * const num_patterns, int * const num_patterns_half, const int width, const int hight, const int combo_length, const int LS, const int isStrong, const int line, const int way, const int simuave){
const float pline = (float)line;
const float pway = pow(1.5,way);
const unsigned long long filter = (1L << (width*hight))-1;
int num_threads = 1;
#ifdef _OPENMP
num_threads = omp_get_max_threads();
#endif
unsigned long long tableID = 0;
//int rank = MIN(RANKINGLENGTH, num_patterns[num_attacks]);
const int rank = RANKINGLENGTH;
unsigned long long max_powerID[num_threads][2][rank];
float max_power[num_threads][2][rank];
unsigned long long final_MID[43][rank];
float final_MP[43][rank];
int i, j, k, m;
int color_combo[combo_length];
int num_drops_combo[combo_length];
int isLine_combo[combo_length];
const int half_table_size = width*hight/2;
const int reverse_length = 1 << width;
int num_attacks;
for(i = 0;i < 43;i++){
final_MID[i][0] = 0xFFFFFFFFFFFFFFFFLU;
}
for(num_attacks = start;num_attacks <= end;num_attacks++){
if(half_table_size < num_attacks && num_attacks <= width*hight-start) break;
printf("calculating %2d-%2d & %2d-%2d ...\n", num_attacks, width*hight-num_attacks, width*hight-num_attacks, num_attacks);
if(num_attacks == half_table_size){
for(i = 0;i < num_threads;i++){
for(j = 0;j < rank;j++){
max_powerID[i][0][j] = 0;
max_power[i][0][j] = 0;
max_powerID[i][1][j] = 0;
max_power[i][1][j] = 0;
}
}
#pragma omp parallel private(i,j,k,tableID, color_combo, num_drops_combo, isLine_combo)
{
int thread_num = 0;
#ifdef _OPENMP
thread_num = omp_get_thread_num();
#endif
int u, l, uu, ll;
for(u = 0;u <= num_attacks;u++){
l = num_attacks - u;
int uoffset = tableID_half_prefix[u];
int loffset = tableID_half_prefix[l];
#pragma omp for
for(uu = 0;uu < num_patterns_half[u];uu++){
for(ll = 0;ll < num_patterns_half[l];ll++){
unsigned long long upperID = (long long)tableID_half_table[uu+uoffset];
unsigned long long lowerID = (long long)tableID_half_table[ll+loffset];
tableID = (upperID << half_table_size) | lowerID;
unsigned long long reversed = 0;
int reverse_bit;
for(i = 0;i < hight; i++){
reverse_bit = (tableID >> width*i ) & (reverse_length-1);
reversed = reversed | (((long long)reversed_bit_table[reverse_bit]) << width*i);
}
unsigned long long inversed = (~tableID) & filter;
if(tableID <= reversed && tableID <= inversed){
//init_combo_info(color_combo, num_drops_combo, isLine_combo, combo_length);
int combo_counter = 0;
unsigned long long color_table[NUM_COLORS];
int num_c;
for(num_c = 0;num_c < NUM_COLORS;num_c++){
color_table[num_c] = 0;
}
switch(table_size){
case SMALL_TABLE:
generate_table_small(tableID, color_table);
break;
case NORMAL_TABLE:
generate_table_normal(tableID, color_table);
break;
case BIG_TABLE:
generate_table_big(tableID, color_table);
break;
default:
fprintf(stderr, "unknown table size\n");
exit(1);
}
int returned_combo_counter = 0;
do{
combo_counter = returned_combo_counter;
switch(table_size){
case SMALL_TABLE:
returned_combo_counter = one_step_small(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
case NORMAL_TABLE:
returned_combo_counter = one_step_normal(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
case BIG_TABLE:
returned_combo_counter = one_step_big(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
}
}while(returned_combo_counter != combo_counter);
//float power = return_attack(combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway);
float power[2];
return_attack_double(power, combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway);
if(max_power[thread_num][0][rank-1] < power[0]){
for(j = 0;j < rank;j++){
if(max_power[thread_num][0][j] < power[0]){
for(k = rank-2;k >= j;k--){
max_powerID[thread_num][0][k+1] = max_powerID[thread_num][0][k];
max_power[thread_num][0][k+1] = max_power[thread_num][0][k];
}
max_powerID[thread_num][0][j] = tableID;
max_power[thread_num][0][j] = power[0];
break;
}
}
}
if(max_power[thread_num][1][rank-1] < power[1]){
for(j = 0;j < rank;j++){
if(max_power[thread_num][1][j] < power[1]){
for(k = rank-2;k >= j;k--){
max_powerID[thread_num][1][k+1] = max_powerID[thread_num][1][k];
max_power[thread_num][1][k+1] = max_power[thread_num][1][k];
}
max_powerID[thread_num][1][j] = (~tableID) & filter;
max_power[thread_num][1][j] = power[1];
break;
}
}
}
}
}
}
}
} //omp end
float MP[rank];
unsigned long long MID[rank];
int ms;
for(i = 0;i < rank;i++){
MP[i] = 0.0;
MID[i]= 0;
}
for(i = 0;i < num_threads;i++){
for(ms = 0; ms < 2; ms++){
for(j = 0;j < rank;j++){
float power = max_power[i][ms][j];
tableID = max_powerID[i][ms][j];
if(MP[rank-1] < power){
for(k = 0;k < rank;k++){
if(MP[k] < power){
for(m = rank-2;m >= k;m--){
MID[m+1] = MID[m];
MP[m+1] = MP[m];
}
MID[k] = tableID;
MP[k] = power;
break;
}
}
}
}
}
}
for(i = 0;i < rank;i++){
float power = MP[i];
unsigned long long tmp = MID[i];
unsigned long long minID = tmp;
int index = i;
for(j = i+1;j < rank;j++){
if(power == MP[j]){
if(minID > MID[j]){
minID = MID[j];
index = j;
}
}else{
break;
}
}
MID[index] = tmp;
MID[i] = minID;
}
for(i = 0;i < rank;i++){
final_MID[num_attacks][i] = MID[i];
final_MP [num_attacks][i] = MP [i];
}
}else{
for(i = 0;i < num_threads;i++){
for(j = 0;j < rank;j++){
max_powerID[i][0][j] = 0;
max_power[i][0][j] = 0;
max_powerID[i][1][j] = 0;
max_power[i][1][j] = 0;
}
}
#pragma omp parallel private(i,j,k,tableID, color_combo, num_drops_combo, isLine_combo)
{
int thread_num = 0;
#ifdef _OPENMP
thread_num = omp_get_thread_num();
#endif
int u, l, uu, ll;
for(u = 0;u <= num_attacks;u++){
l = num_attacks - u;
if(u <= half_table_size && l <= half_table_size){
int uoffset = tableID_half_prefix[u];
int loffset = tableID_half_prefix[l];
#pragma omp for
for(uu = 0;uu < num_patterns_half[u];uu++){
for(ll = 0;ll < num_patterns_half[l];ll++){
unsigned long long upperID = (long long)tableID_half_table[uu+uoffset];
unsigned long long lowerID = (long long)tableID_half_table[ll+loffset];
tableID = (upperID << half_table_size) | lowerID;
unsigned long long reversed = 0;
int reverse_bit;
for(i = 0;i < hight; i++){
reverse_bit = (tableID >> width*i ) & (reverse_length-1);
reversed = reversed | (((long long)reversed_bit_table[reverse_bit]) << width*i);
}
if(tableID <= reversed){
//init_combo_info(color_combo, num_drops_combo, isLine_combo, combo_length);
int combo_counter = 0;
unsigned long long color_table[NUM_COLORS];
int num_c;
for(num_c = 0;num_c < NUM_COLORS;num_c++){
color_table[num_c] = 0;
}
switch(table_size){
case SMALL_TABLE:
generate_table_small(tableID, color_table);
break;
case NORMAL_TABLE:
generate_table_normal(tableID, color_table);
break;
case BIG_TABLE:
generate_table_big(tableID, color_table);
break;
default:
fprintf(stderr, "unknown table size\n");
exit(1);
}
int returned_combo_counter = 0;
do{
combo_counter = returned_combo_counter;
switch(table_size){
case SMALL_TABLE:
returned_combo_counter = one_step_small(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
case NORMAL_TABLE:
returned_combo_counter = one_step_normal(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
case BIG_TABLE:
returned_combo_counter = one_step_big(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS);
break;
}
}while(returned_combo_counter != combo_counter);
//float power = return_attack(combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway);
float power[2];
return_attack_double(power, combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway);
if(max_power[thread_num][0][rank-1] < power[0]){
for(j = 0;j < rank;j++){
if(max_power[thread_num][0][j] < power[0]){
for(k = rank-2;k >= j;k--){
max_powerID[thread_num][0][k+1] = max_powerID[thread_num][0][k];
max_power[thread_num][0][k+1] = max_power[thread_num][0][k];
}
max_powerID[thread_num][0][j] = tableID;
max_power[thread_num][0][j] = power[0];
break;
}
}
}
if(max_power[thread_num][1][rank-1] < power[1]){
for(j = 0;j < rank;j++){
if(max_power[thread_num][1][j] < power[1]){
for(k = rank-2;k >= j;k--){
max_powerID[thread_num][1][k+1] = max_powerID[thread_num][1][k];
max_power[thread_num][1][k+1] = max_power[thread_num][1][k];
}
max_powerID[thread_num][1][j] = (~tableID) & filter;
max_power[thread_num][1][j] = power[1];
break;
}
}
}
}
}
}
}
}
} //omp end
float MP[2][rank];
unsigned long long MID[2][rank];
int ms;
for(ms = 0; ms < 2; ms++){
for(i = 0;i < rank;i++){
MP[ms][i] = 0.0;
MID[ms][i]= 0;
}
for(i = 0;i < num_threads;i++){
for(j = 0;j < rank;j++){
float power = max_power[i][ms][j];
tableID = max_powerID[i][ms][j];
if(MP[ms][rank-1] < power){
for(k = 0;k < rank;k++){
if(MP[ms][k] < power){
for(m = rank-2;m >= k;m--){
MID[ms][m+1] = MID[ms][m];
MP[ms][m+1] = MP[ms][m];
}
MID[ms][k] = tableID;
MP[ms][k] = power;
break;
}
}
}
}
}
for(i = 0;i < rank;i++){
float power = MP[ms][i];
unsigned long long tmp = MID[ms][i];
unsigned long long minID = tmp;
int index = i;
for(j = i+1;j < rank;j++){
if(power == MP[ms][j]){
if(minID > MID[ms][j]){
minID = MID[ms][j];
index = j;
}
}else{
break;
}
}
MID[ms][index] = tmp;
MID[ms][i] = minID;
}
}
for(i = 0;i < rank;i++){
final_MID[num_attacks][i] = MID[0][i];
final_MP [num_attacks][i] = MP [0][i];
final_MID[width*hight-num_attacks][i] = MID[1][i];
final_MP [width*hight-num_attacks][i] = MP [1][i];
}
}
}
for(num_attacks = 0;num_attacks <= width*hight;num_attacks++){
if(final_MID[num_attacks][0] != 0xFFFFFFFFFFFFFFFFLU){
printf("%2d-%2d, line %d, way %d\n", num_attacks, width*hight-num_attacks, line, way);
if(simuave){
simulate_average(table_size, final_MID[num_attacks], final_MP[num_attacks], num_attacks, width, hight, LS, isStrong, pline, pway);
}else{
for(i = 0;i < rank;i++){
printf("%d,max ID,%lld,power,%f\n",i,final_MID[num_attacks][i],final_MP[num_attacks][i]);
}
}
}
}
}
/* #ifdef AVX */
/* void simulate_all_simd(const int table_size, const int start, const int end, /\*int * const bit_count_table,*\/ int * const reversed_bit_table, int * const tableID_half_table, int * const tableID_half_prefix, unsigned long long * const num_patterns, int * const num_patterns_half, const int width, const int hight, const int combo_length, const int LS, const int isStrong, const int line, const int way, const int simuave){ */
/* const float pline = (float)line; */
/* const float pway = pow(1.5,way); */
/* const unsigned long long filter = (1L << (width*hight))-1; */
/* int num_threads = 1; */
/* #ifdef _OPENMP */
/* num_threads = omp_get_max_threads(); */
/* #endif */
/* //int rank = MIN(RANKINGLENGTH, num_patterns[num_attacks]); */
/* const int rank = RANKINGLENGTH; */
/* unsigned long long max_powerID[num_threads][2][rank]; */
/* float max_power[num_threads][2][rank]; */
/* unsigned long long final_MID[42][rank]; */
/* float final_MP[42][rank]; */
/* int i, j, k, m; */
/* int color_combo[combo_length]; */
/* int num_drops_combo[combo_length]; */
/* int isLine_combo[combo_length]; */
/* const int half_table_size = width*hight/2; */
/* const int reverse_length = 1 << width; */
/* int num_attacks; */
/* for(i = 0;i < 42;i++){ */
/* final_MID[i][0] = 0xFFFFFFFFFFFFFFFFLU; */
/* } */
/* for(num_attacks = start;num_attacks <= end;num_attacks++){ */
/* if(half_table_size < num_attacks && num_attacks <= width*hight-start) break; */
/* printf("calculating %2d-%2d & %2d-%2d ...\n", num_attacks, width*hight-num_attacks, width*hight-num_attacks, num_attacks); */
/* if(num_attacks == half_table_size){ */
/* for(i = 0;i < num_threads;i++){ */
/* for(j = 0;j < rank;j++){ */
/* max_powerID[i][0][j] = 0; */
/* max_power[i][0][j] = 0; */
/* max_powerID[i][1][j] = 0; */
/* max_power[i][1][j] = 0; */
/* } */
/* } */
/* #pragma omp parallel private(i,j,k,tableID, color_combo, num_drops_combo, isLine_combo) */
/* { */
/* int thread_num = 0; */
/* #ifdef _OPENMP */
/* thread_num = omp_get_thread_num(); */
/* #endif */
/* int u, l, uu, ll; */
/* for(u = 0;u <= num_attacks;u++){ */
/* l = num_attacks - u; */
/* int uoffset = tableID_half_prefix[u]; */
/* int loffset = tableID_half_prefix[l]; */
/* #pragma omp for */
/* for(uu = 0;uu < num_patterns_half[u];uu++){ */
/* //for(ll = 0;ll < num_patterns_half[l];ll++){ */
/* while(ll < num_patterns_half[l]){ */
/* int count4 = 0; */
/* unsigned long long tableID4[4]; */
/* tableID4[0] = 0; */
/* tableID4[1] = 0; */
/* tableID4[2] = 0; */
/* tableID4[3] = 0; */
/* while(count4 < 4 && ll < num_patterns_half[l]){ */
/* unsigned long long upperID = (long long)tableID_half_table[uu+uoffset]; */
/* unsigned long long lowerID = (long long)tableID_half_table[ll+loffset]; */
/* unsigned long long tableID_tmp = (upperID << half_table_size) | lowerID; */
/* unsigned long long reversed = 0; */
/* int reverse_bit; */
/* for(i = 0;i < hight; i++){ */
/* reverse_bit = (tableID_tmp >> width*i ) & (reverse_length-1); */
/* reversed = reversed | (((long long)reversed_bit_table[reverse_bit]) << width*i); */
/* } */
/* unsigned long long inversed = (~tableID_tmp) & filter; */
/* if(tableID_tmp <= reversed && tableID_tmp <= inversed){ */
/* tableID4[count4]= tableID_tmp; */
/* count4++; */
/* } */
/* ll++; */
/* } */
/* __m256i tableIDs = _mm256_load_si256((__m256i*)(tableID4)); */
/* int combo_counter[4] = {0}; */
/* __m256i color_table[2]; */
/* switch(table_size){ */
/* case SMALL_TABLE: */
/* //generate_table_small_simd(tableIDs, color_table); */
/* break; */
/* case NORMAL_TABLE: */
/* //generate_table_normal_simd(tableIDs, color_table); */
/* break; */
/* case BIG_TABLE: */
/* generate_table_big_simd(tableIDs, color_table); */
/* break; */
/* default: */
/* fprintf(stderr, "unknown table size\n"); */
/* exit(1); */
/* } */
/* int returned_combo_counter = 0; */
/* do{ */
/* combo_counter = returned_combo_counter; */
/* switch(table_size){ */
/* case SMALL_TABLE: */
/* returned_combo_counter = one_step_small(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* case NORMAL_TABLE: */
/* returned_combo_counter = one_step_normal(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* case BIG_TABLE: */
/* returned_combo_counter = one_step_big(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* } */
/* }while(returned_combo_counter != combo_counter); */
/* //float power = return_attack(combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway); */
/* float power[2]; */
/* return_attack_double(power, combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway); */
/* if(max_power[thread_num][0][rank-1] < power[0]){ */
/* for(j = 0;j < rank;j++){ */
/* if(max_power[thread_num][0][j] < power[0]){ */
/* for(k = rank-2;k >= j;k--){ */
/* max_powerID[thread_num][0][k+1] = max_powerID[thread_num][0][k]; */
/* max_power[thread_num][0][k+1] = max_power[thread_num][0][k]; */
/* } */
/* max_powerID[thread_num][0][j] = tableID; */
/* max_power[thread_num][0][j] = power[0]; */
/* break; */
/* } */
/* } */
/* } */
/* if(max_power[thread_num][1][rank-1] < power[1]){ */
/* for(j = 0;j < rank;j++){ */
/* if(max_power[thread_num][1][j] < power[1]){ */
/* for(k = rank-2;k >= j;k--){ */
/* max_powerID[thread_num][1][k+1] = max_powerID[thread_num][1][k]; */
/* max_power[thread_num][1][k+1] = max_power[thread_num][1][k]; */
/* } */
/* max_powerID[thread_num][1][j] = (~tableID) & filter; */
/* max_power[thread_num][1][j] = power[1]; */
/* break; */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } //omp end */
/* float MP[rank]; */
/* unsigned long long MID[rank]; */
/* int ms; */
/* for(i = 0;i < rank;i++){ */
/* MP[i] = 0.0; */
/* MID[i]= 0; */
/* } */
/* for(i = 0;i < num_threads;i++){ */
/* for(ms = 0; ms < 2; ms++){ */
/* for(j = 0;j < rank;j++){ */
/* float power = max_power[i][ms][j]; */
/* tableID = max_powerID[i][ms][j]; */
/* if(MP[rank-1] < power){ */
/* for(k = 0;k < rank;k++){ */
/* if(MP[k] < power){ */
/* for(m = rank-2;m >= k;m--){ */
/* MID[m+1] = MID[m]; */
/* MP[m+1] = MP[m]; */
/* } */
/* MID[k] = tableID; */
/* MP[k] = power; */
/* break; */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* for(i = 0;i < rank;i++){ */
/* float power = MP[i]; */
/* unsigned long long tmp = MID[i]; */
/* unsigned long long minID = tmp; */
/* int index = i; */
/* for(j = i+1;j < rank;j++){ */
/* if(power == MP[j]){ */
/* if(minID > MID[j]){ */
/* minID = MID[j]; */
/* index = j; */
/* } */
/* }else{ */
/* break; */
/* } */
/* } */
/* MID[index] = tmp; */
/* MID[i] = minID; */
/* } */
/* for(i = 0;i < rank;i++){ */
/* final_MID[num_attacks][i] = MID[i]; */
/* final_MP [num_attacks][i] = MP [i]; */
/* } */
/* }else{ */
/* for(i = 0;i < num_threads;i++){ */
/* for(j = 0;j < rank;j++){ */
/* max_powerID[i][0][j] = 0; */
/* max_power[i][0][j] = 0; */
/* max_powerID[i][1][j] = 0; */
/* max_power[i][1][j] = 0; */
/* } */
/* } */
/* #pragma omp parallel private(i,j,k,tableID, color_combo, num_drops_combo, isLine_combo) */
/* { */
/* int thread_num = 0; */
/* #ifdef _OPENMP */
/* thread_num = omp_get_thread_num(); */
/* #endif */
/* int u, l, uu, ll; */
/* for(u = 0;u <= num_attacks;u++){ */
/* l = num_attacks - u; */
/* if(u <= half_table_size && l <= half_table_size){ */
/* int uoffset = tableID_half_prefix[u]; */
/* int loffset = tableID_half_prefix[l]; */
/* #pragma omp for */
/* for(uu = 0;uu < num_patterns_half[u];uu++){ */
/* for(ll = 0;ll < num_patterns_half[l];ll++){ */
/* unsigned long long upperID = (long long)tableID_half_table[uu+uoffset]; */
/* unsigned long long lowerID = (long long)tableID_half_table[ll+loffset]; */
/* tableID = (upperID << half_table_size) | lowerID; */
/* unsigned long long reversed = 0; */
/* int reverse_bit; */
/* for(i = 0;i < hight; i++){ */
/* reverse_bit = (tableID >> width*i ) & (reverse_length-1); */
/* reversed = reversed | (((long long)reversed_bit_table[reverse_bit]) << width*i); */
/* } */
/* if(tableID <= reversed){ */
/* //init_combo_info(color_combo, num_drops_combo, isLine_combo, combo_length); */
/* int combo_counter = 0; */
/* unsigned long long color_table[NUM_COLORS]; */
/* int num_c; */
/* for(num_c = 0;num_c < NUM_COLORS;num_c++){ */
/* color_table[num_c] = 0; */
/* } */
/* switch(table_size){ */
/* case SMALL_TABLE: */
/* generate_table_small(tableID, color_table); */
/* break; */
/* case NORMAL_TABLE: */
/* generate_table_normal(tableID, color_table); */
/* break; */
/* case BIG_TABLE: */
/* generate_table_big(tableID, color_table); */
/* break; */
/* default: */
/* fprintf(stderr, "unknown table size\n"); */
/* exit(1); */
/* } */
/* int returned_combo_counter = 0; */
/* do{ */
/* combo_counter = returned_combo_counter; */
/* switch(table_size){ */
/* case SMALL_TABLE: */
/* returned_combo_counter = one_step_small(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* case NORMAL_TABLE: */
/* returned_combo_counter = one_step_normal(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* case BIG_TABLE: */
/* returned_combo_counter = one_step_big(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, NUM_COLORS); */
/* break; */
/* } */
/* }while(returned_combo_counter != combo_counter); */
/* //float power = return_attack(combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway); */
/* float power[2]; */
/* return_attack_double(power, combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, pline, pway); */
/* if(max_power[thread_num][0][rank-1] < power[0]){ */
/* for(j = 0;j < rank;j++){ */
/* if(max_power[thread_num][0][j] < power[0]){ */
/* for(k = rank-2;k >= j;k--){ */
/* max_powerID[thread_num][0][k+1] = max_powerID[thread_num][0][k]; */
/* max_power[thread_num][0][k+1] = max_power[thread_num][0][k]; */
/* } */
/* max_powerID[thread_num][0][j] = tableID; */
/* max_power[thread_num][0][j] = power[0]; */
/* break; */
/* } */
/* } */
/* } */
/* if(max_power[thread_num][1][rank-1] < power[1]){ */
/* for(j = 0;j < rank;j++){ */
/* if(max_power[thread_num][1][j] < power[1]){ */
/* for(k = rank-2;k >= j;k--){ */
/* max_powerID[thread_num][1][k+1] = max_powerID[thread_num][1][k]; */
/* max_power[thread_num][1][k+1] = max_power[thread_num][1][k]; */
/* } */
/* max_powerID[thread_num][1][j] = (~tableID) & filter; */
/* max_power[thread_num][1][j] = power[1]; */
/* break; */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } */
/* } //omp end */
/* float MP[2][rank]; */
/* unsigned long long MID[2][rank]; */
/* int ms; */
/* for(ms = 0; ms < 2; ms++){ */
/* for(i = 0;i < rank;i++){ */
/* MP[ms][i] = 0.0; */
/* MID[ms][i]= 0; */
/* } */
/* for(i = 0;i < num_threads;i++){ */
/* for(j = 0;j < rank;j++){ */
/* float power = max_power[i][ms][j]; */
/* tableID = max_powerID[i][ms][j]; */
/* if(MP[ms][rank-1] < power){ */
/* for(k = 0;k < rank;k++){ */
/* if(MP[ms][k] < power){ */
/* for(m = rank-2;m >= k;m--){ */
/* MID[ms][m+1] = MID[ms][m]; */
/* MP[ms][m+1] = MP[ms][m]; */
/* } */
/* MID[ms][k] = tableID; */
/* MP[ms][k] = power; */
/* break; */
/* } */
/* } */
/* } */
/* } */
/* } */
/* for(i = 0;i < rank;i++){ */
/* float power = MP[ms][i]; */
/* unsigned long long tmp = MID[ms][i]; */
/* unsigned long long minID = tmp; */
/* int index = i; */
/* for(j = i+1;j < rank;j++){ */
/* if(power == MP[ms][j]){ */
/* if(minID > MID[ms][j]){ */
/* minID = MID[ms][j]; */
/* index = j; */
/* } */
/* }else{ */
/* break; */
/* } */
/* } */
/* MID[ms][index] = tmp; */
/* MID[ms][i] = minID; */
/* } */
/* } */
/* for(i = 0;i < rank;i++){ */
/* final_MID[num_attacks][i] = MID[0][i]; */
/* final_MP [num_attacks][i] = MP [0][i]; */
/* final_MID[width*hight-num_attacks][i] = MID[1][i]; */
/* final_MP [width*hight-num_attacks][i] = MP [1][i]; */
/* } */
/* } */
/* } */
/* for(num_attacks = 0;num_attacks <= width*hight;num_attacks++){ */
/* if(final_MID[num_attacks][0] != 0xFFFFFFFFFFFFFFFFLU){ */
/* printf("%2d-%2d, line %d, way %d\n", num_attacks, width*hight-num_attacks, line, way); */
/* if(simuave){ */
/* simulate_average(table_size, final_MID[num_attacks], final_MP[num_attacks], num_attacks, width, hight, LS, isStrong, pline, pway); */
/* }else{ */
/* for(i = 0;i < rank;i++){ */
/* printf("%d,max ID,%lld,power,%f\n",i,final_MID[num_attacks][i],final_MP[num_attacks][i]); */
/* } */
/* } */
/* } */
/* } */
/* } */
/* #endif */
#define WID 7
inline int one_step_small(unsigned long long *color_table, int *color_combo, int *num_drops_combo, int *isLine_combo, int finish, int num_colors){
// 0 → width
// ↓
// hight
// 000000000
// 000000000
// 000000000
// 000000000
// 000000000
// 000000010
// 000000111
// 000000010
unsigned long long isErase_tables[num_colors];
int combo_counter = finish;
int num_c;
unsigned long long tmp, tmp2;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
//自身の上下シフト・左右シフトとビット積をとる。その上下・左右が消すべきビット
unsigned long long n, w, s, e;
n = color >> WID;
w = color >> 1;
s = color << WID;
e = color << 1;
tmp = (color & n & s);
tmp = tmp | (tmp >> WID) | (tmp << WID);
tmp2 = (color & w & e);
tmp2 = tmp2 | (tmp2 >> 1 ) | (tmp2 << 1 );
isErase_tables[num_c] = (color & tmp) | (color & tmp2);
}
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long isErase_table = isErase_tables[num_c];
color_table[num_c] = color_table[num_c] & (~isErase_table);
unsigned long long p = 1L << (WID+1);
while(isErase_table) {
while(!(isErase_table & p)){
p = p << 1;
}
tmp = p;
color_combo[combo_counter] = num_c;
unsigned long long tmp_old;
do{
tmp_old = tmp;
tmp = (tmp | (tmp << 1) | (tmp >> 1) | (tmp << WID) | (tmp >> WID)) & isErase_table;
}while(tmp_old != tmp);
isErase_table = isErase_table & (~tmp);
unsigned long long bits = tmp;
bits = (bits & 0x5555555555555555LU) + ((bits >> 1) & 0x5555555555555555LU);
bits = (bits & 0x3333333333333333LU) + ((bits >> 2) & 0x3333333333333333LU);
bits = (bits + (bits >> 4)) & 0x0F0F0F0F0F0F0F0FLU;
bits = bits + (bits >> 8);
bits = bits + (bits >> 16);
bits = (bits + (bits >> 32)) & 0x0000007F;
num_drops_combo[combo_counter] = bits;
isLine_combo[combo_counter] = ((tmp >> (WID +1)) & 31) == 31
|| ((tmp >> (WID*2+1)) & 31) == 31
|| ((tmp >> (WID*3+1)) & 31) == 31
|| ((tmp >> (WID*4+1)) & 31) == 31;
combo_counter++;
}
}
if(finish != combo_counter){
unsigned long long exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
unsigned long long exist_org;
do{
exist_org = exist_table;
unsigned long long exist_u = (exist_table >> WID) | 16642998272L;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
unsigned long long color_u = color & exist_u;
unsigned long long color_d = (color << WID) & (~exist_table) & (~2130303778816L);
color_table[num_c] = color_u | color_d;
}
exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
}while(exist_org != exist_table);
}
return combo_counter;
}
#undef WID
#define WID 8
inline int one_step_normal(unsigned long long *color_table, int *color_combo, int *num_drops_combo, int *isLine_combo, int finish, int num_colors){
// 0 → width
// ↓
// hight
// 000000000
// 000000000
// 000000000
// 000000000
// 000000000
// 000000010
// 000000111
// 000000010
unsigned long long isErase_tables[num_colors];
int combo_counter = finish;
int num_c;
unsigned long long tmp, tmp2;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
//自身の上下シフト・左右シフトとビット積をとる。その上下・左右が消すべきビット
unsigned long long n, w, s, e;
n = color >> WID;
w = color >> 1;
s = color << WID;
e = color << 1;
tmp = (color & n & s);
tmp = tmp | (tmp >> WID) | (tmp << WID);
tmp2 = (color & w & e);
tmp2 = tmp2 | (tmp2 >> 1 ) | (tmp2 << 1 );
isErase_tables[num_c] = (color & tmp) | (color & tmp2);
}
// #if num_colors==2
/* if(isErase_tables[0] == isErase_tables[1]) */
/* return combo_counter; */
// // isErase_table[0~N] == 0, つまりは消えるドロップがないなら以降の処理は必要ない。
// // が、しかしおそらくWarp divergenceの関係で、ない方が速い。(少なくともGPUでは) (CPUでもない方が速いことを確認。分岐予測の方が優秀)
// // とすれば、isEraseをtableにしてループ分割する必要はないが、おそらく最適化の関係で分割した方が速い。
// #endif
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long isErase_table = isErase_tables[num_c];
color_table[num_c] = color_table[num_c] & (~isErase_table);
unsigned long long p = 1L << (WID+1);
while(isErase_table) {
while(!(isErase_table & p)){
p = p << 1;
}
tmp = p;
color_combo[combo_counter] = num_c;
unsigned long long tmp_old;
do{
// ひとかたまりで消えるドロップは必ず隣接しているので、上下左右の隣接bitを探索する。
// 消去ドロップの仕様変更のおかげで可能になった
tmp_old = tmp;
tmp = (tmp | (tmp << 1) | (tmp >> 1) | (tmp << WID) | (tmp >> WID)) & isErase_table;
}while(tmp_old != tmp);
isErase_table = isErase_table & (~tmp);
// tmp の立ってるbit数を数えることで、ひとかたまりのドロップ数を数える
// いわゆるpopcnt。
// int b1, b2, b3, b4, b5, b6;
// b1 = tmp >> (WID*1+1) & 127;
// b2 = tmp >> (WID*2+1) & 127;
// b3 = tmp >> (WID*3+1) & 127;
// b4 = tmp >> (WID*4+1) & 127;
// b5 = tmp >> (WID*5+1) & 127;
// b6 = tmp >> (WID*6+1) & 127;
// num_drops_combo[combo_counter] = bit_count_table[b1] + bit_count_table[b2]
// + bit_count_table[b3] + bit_count_table[b4] + bit_count_table[b5] + bit_count_table[b6];
unsigned long long bits = tmp;
bits = (bits & 0x5555555555555555LU) + ((bits >> 1) & 0x5555555555555555LU);
bits = (bits & 0x3333333333333333LU) + ((bits >> 2) & 0x3333333333333333LU);
bits = (bits + (bits >> 4)) & 0x0F0F0F0F0F0F0F0FLU;
bits = bits + (bits >> 8);
bits = bits + (bits >> 16);
bits = (bits + (bits >> 32)) & 0x0000007F;
num_drops_combo[combo_counter] = bits;
// num_drops_combo[combo_counter] = __popcnt(tmp);
isLine_combo[combo_counter] = ((tmp >> (WID +1)) & 63) == 63
|| ((tmp >> (WID*2+1)) & 63) == 63
|| ((tmp >> (WID*3+1)) & 63) == 63
|| ((tmp >> (WID*4+1)) & 63) == 63
|| ((tmp >> (WID*5+1)) & 63) == 63;
combo_counter++;
}
}
if(finish != combo_counter){
unsigned long long exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
unsigned long long exist_org;
do{
exist_org = exist_table;
unsigned long long exist_u = (exist_table >> WID) | 138538465099776L;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
unsigned long long color_u = color & exist_u;
unsigned long long color_d = (color << WID) & (~exist_table) & (~35465847065542656L); // color << WIDが諸悪の根源。非常に扱いに気をつけるべき。bit_tableだとオーバーフローで消えるので(~354...)はいらない。
color_table[num_c] = color_u | color_d;
}
exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
}while(exist_org != exist_table);
}
return combo_counter;
}
#undef WID
#define WID 9
inline int one_step_big(unsigned long long *color_table, int *color_combo, int *num_drops_combo, int *isLine_combo, int finish, int num_colors){
// 0 → width
// ↓
// hight
// 000000000
// 000000000
// 000000000
// 000000000
// 000000000
// 000000010
// 000000111
// 000000010
unsigned long long isErase_tables[num_colors];
//unsigned long long isErase_table;
int combo_counter = finish;
int num_c;
unsigned long long tmp, tmp2;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
unsigned long long n, w, s, e;
n = color >> WID;
w = color >> 1;
s = color << WID;
e = color << 1;
tmp = (color & n & s);
tmp = tmp | (tmp >> WID) | (tmp << WID);
tmp2 = (color & w & e);
tmp2 = tmp2 | (tmp2 >> 1 ) | (tmp2 << 1 );
isErase_tables[num_c] = (color & tmp) | (color & tmp2);
//isErase_table = (color & tmp) | (color & tmp2);
}
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long isErase_table = isErase_tables[num_c];
color_table[num_c] = color_table[num_c] & (~isErase_table);
unsigned long long p = 1L << (WID+1);
while(isErase_table) {
while(!(isErase_table & p)){
p = p << 1;
}
tmp = p;
color_combo[combo_counter] = num_c;
unsigned long long tmp_old;
do{
tmp_old = tmp;
tmp = (tmp | (tmp << 1) | (tmp >> 1) | (tmp << WID) | (tmp >> WID)) & isErase_table;
}while(tmp_old != tmp);
isErase_table = isErase_table & (~tmp);
// int b1, b2, b3, b4, b5, b6;
// b1 = tmp >> (WID*1+1) & 127;
// b2 = tmp >> (WID*2+1) & 127;
// b3 = tmp >> (WID*3+1) & 127;
// b4 = tmp >> (WID*4+1) & 127;
// b5 = tmp >> (WID*5+1) & 127;
// b6 = tmp >> (WID*6+1) & 127;
// num_drops_combo[combo_counter] = bit_count_table[b1] + bit_count_table[b2]
// + bit_count_table[b3] + bit_count_table[b4] + bit_count_table[b5] + bit_count_table[b6];
unsigned long long bits = tmp;
bits = (bits & 0x5555555555555555LU) + ((bits >> 1) & 0x5555555555555555LU);
bits = (bits & 0x3333333333333333LU) + ((bits >> 2) & 0x3333333333333333LU);
bits = (bits + (bits >> 4)) & 0x0F0F0F0F0F0F0F0FLU;
bits = bits + (bits >> 8);
bits = bits + (bits >> 16);
bits = (bits + (bits >> 32)) & 0x0000007F;
num_drops_combo[combo_counter] = bits;
isLine_combo[combo_counter] = ((tmp >> (WID +1)) & 127) == 127
|| ((tmp >> (WID*2+1)) & 127) == 127
|| ((tmp >> (WID*3+1)) & 127) == 127
|| ((tmp >> (WID*4+1)) & 127) == 127
|| ((tmp >> (WID*5+1)) & 127) == 127
|| ((tmp >> (WID*6+1)) & 127) == 127;
// bits = tmp;
// bits = bits & (bits >> 1);
// bits = bits & (bits >> 2);
// bits = bits & (bits >> 3);
// isLine_combo[combo_counter] = ((bits & 36099303471055872L) != 0);
combo_counter++;
}
}
if(finish != combo_counter){
unsigned long long exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
unsigned long long exist_org;
do{
exist_org = exist_table;
unsigned long long exist_u = (exist_table >> WID) | 4575657221408423936L;
for(num_c = 0;num_c < num_colors;num_c++){
unsigned long long color = color_table[num_c];
unsigned long long color_u = color & exist_u;
unsigned long long color_d = (color << WID) & (~exist_table);
color_table[num_c] = color_u | color_d;
}
exist_table = color_table[0];
for(num_c = 1;num_c < num_colors;num_c++){
exist_table = exist_table | color_table[num_c];
}
}while(exist_org != exist_table);
}
return combo_counter;
}
#undef WID
void print_table(const unsigned long long *color_table, const int width, const int hight){
int i, j;
for(i = 1;i <= hight;i++){
for(j = 1;j <= width;j++){
unsigned long long p = (1L << ((width+2)*i+j));
if((color_table[0] & p) == p)
printf("G ");
else if((color_table[1] & p) == p)
printf("Y ");
else
printf("? ");
}
putchar('\n');
}
putchar('\n');
}
void print_table2(const unsigned long long color_table, const int width, const int hight){
int i, j;
for(i = 1;i <= hight;i++){
for(j = 1;j <= width;j++){
unsigned long long p = (1L << ((width+2)*i+j));
printf("%d ", (color_table & p) == p);
}
putchar('\n');
}
putchar('\n');
}
void ID2table(const unsigned long long ID, const int width, const int hight){
int i, j;
for(i = 0;i < hight;i++){
for(j = 0;j < width;j++){
unsigned long long p = (1L << ((width)*i+j));
if((ID & p) == p)
printf("G ");
else
printf("Y ");
}
putchar('\n');
}
putchar('\n');
}
float return_attack(const int combo_counter, int *const color_combo, int *const num_drops_combo, int *const isLine_combo, const int LS, const int strong, const float line, const float way){
// used for simulation mode
// [FIXME] check only Green attack
const float AT = 1.0;
int num_line = 0;
float attack = 0;
float l = 1.0;
int i;
for(i = 0;i < combo_counter;i++){
int color = color_combo[i];
float drop_pwr;
switch(color){
case MAINCOLOR:
drop_pwr = num_drops_combo[i]==4 ? (1+0.25*(num_drops_combo[i]-3))*way : 1+0.25*(num_drops_combo[i]-3);
if(strong)
drop_pwr = drop_pwr * (1+0.06*num_drops_combo[i]);
attack += drop_pwr;
if(isLine_combo[i]) num_line++;
break;
default:
break;
}
}
int count;
switch(LS){
case HERO:
for(i = 0;i < combo_counter;i++){
if(MAINCOLOR == color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 8){
l = 16;
}else if(num_drops == 7 && l < 12.25){
l = 12.25;
}else if(num_drops == 6 && l < 9){
l = 9;
}
}
}
break;
case SONIA:
if(combo_counter < 6)
l = 6.25;
else
l = 2.75*2.75;
break;
case KRISHNA:
count = 0;
for(i = 0;i < combo_counter;i++){
if(MAINCOLOR == color_combo[i]){
count++;
int num_drops = num_drops_combo[i];
if(num_drops == 5)
l = 2.25;
}
}
if(count == 2)
l = l * 3 * 3;
else if(count >= 3)
l = l * 4.5 * 4.5;
else
l = 1;
break;
case BASTET:
if(combo_counter == 5)
l = 3.0*3.0;
else if(combo_counter == 6)
l = 3.5*3.5;
else if(combo_counter >= 7)
l = 4.0*4.0;
else
l = 1.0;
break;
case LAKU_PARU:
l = 6.25;
for(i = 0;i < combo_counter;i++){
if(MAINCOLOR != color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 5)
l = 25;
}
}
break;
default:
break;
}
attack = attack * (1+0.25*(combo_counter-1)) * AT * l * (1+0.1*line*num_line) ;
return attack;
}
void return_attack_double(float *power, const int combo_counter, int *const color_combo, int *const num_drops_combo, int *const isLine_combo, const int LS, const int strong, const float line, const float way){
// used for simulation mode
// [FIXME] check only Green attack
const float AT = 1.0;
int num_line_m = 0;
float attack_m = 0;
int num_line_s = 0;
float attack_s = 0;
float l_m = 1.0;
float l_s = 1.0;
int i;
float drop_pwr;
for(i = 0;i < combo_counter;i++){
int color = color_combo[i];
switch(color){
case MAINCOLOR:
drop_pwr = num_drops_combo[i]==4 ? (1+0.25*(num_drops_combo[i]-3))*way : 1+0.25*(num_drops_combo[i]-3);
if(strong)
drop_pwr = drop_pwr * (1+0.06*num_drops_combo[i]);
attack_m += drop_pwr;
if(isLine_combo[i]) num_line_m++;
break;
case SUBCOLOR:
drop_pwr = num_drops_combo[i]==4 ? (1+0.25*(num_drops_combo[i]-3))*way : 1+0.25*(num_drops_combo[i]-3);
if(strong)
drop_pwr = drop_pwr * (1+0.06*num_drops_combo[i]);
attack_s += drop_pwr;
if(isLine_combo[i]) num_line_s++;
break;
default:
break;
}
}
int count_m;
int count_s;
switch(LS){
case HERO:
for(i = 0;i < combo_counter;i++){
if(MAINCOLOR == color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 8){
l_m = 16;
}else if(num_drops == 7 && l_m < 12.25){
l_m = 12.25;
}else if(num_drops == 6 && l_m < 9){
l_m = 9;
}
}
if(SUBCOLOR == color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 8){
l_s = 16;
}else if(num_drops == 7 && l_s < 12.25){
l_s = 12.25;
}else if(num_drops == 6 && l_s < 9){
l_s = 9;
}
}
}
break;
case SONIA:
if(combo_counter < 6){
l_m = 6.25;
l_s = 6.25;
}else{
l_m = 2.75*2.75;
l_s = 2.75*2.75;
}
break;
case KRISHNA:
count_m = 0;
for(i = 0;i < combo_counter;i++){
if(MAINCOLOR == color_combo[i]){
count_m++;
int num_drops = num_drops_combo[i];
if(num_drops == 5)
l_m = 2.25;
}
}
if(count_m == 2)
l_m = l_m * 3 * 3;
else if(count_m >= 3)
l_m = l_m * 4.5 * 4.5;
else
l_m = 1;
count_s = 0;
for(i = 0;i < combo_counter;i++){
if(SUBCOLOR == color_combo[i]){
count_s++;
int num_drops = num_drops_combo[i];
if(num_drops == 5)
l_s = 2.25;
}
}
if(count_s == 2)
l_s = l_s * 3 * 3;
else if(count_s >= 3)
l_s = l_s * 4.5 * 4.5;
else
l_s = 1;
break;
case BASTET:
if(combo_counter == 5){
l_m = 3.0*3.0;
l_s = 3.0*3.0;
}else if(combo_counter == 6){
l_m = 3.5*3.5;
l_s = 3.5*3.5;
}else if(combo_counter >= 7){
l_m = 4.0*4.0;
l_s = 4.0*4.0;
}else{
l_m = 1.0;
l_s = 1.0;
}
break;
case LAKU_PARU:
l_m = 6.25;
l_s = 6.25;
for(i = 0;i < combo_counter;i++){
if(SUBCOLOR == color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 5)
l_m = 25;
}
if(MAINCOLOR == color_combo[i]){
int num_drops = num_drops_combo[i];
if(num_drops >= 5)
l_s = 25;
}
}
break;
default:
break;
}
power[0] = attack_m * (1+0.25*(combo_counter-1)) * AT * l_m * (1+0.1*line*num_line_m);
power[1] = attack_s * (1+0.25*(combo_counter-1)) * AT * l_s * (1+0.1*line*num_line_s);
}
void fill_random(unsigned long long *color_table, const int width, const int hight, /*struct drand48_data drand_buf*/ unsigned int *seed){
int i, j, k;
for(i = 1;i <= hight;i++){
for(j = 1;j <= width;j++){
unsigned long long p = (1L << ((width+2)*i+j));
int flag = 1;
for(k = 0;k < 6;k++){
if((color_table[k] & p) == p){
flag = 0;
}
}
if(flag){
/* double rand; */
/* drand48_r(&drand_buf,&rand); */
/* int color = ((int)rand)%6; */
int color = rand_r(seed)%6;
color_table[color] = color_table[color] | p;
}
}
}
}
void simulate_average(const int table_size, unsigned long long * const MID, float * const MP, const int num_attacks, const int width, const int hight, const int LS, const int isStrong, const float line, const float way){
const int combo_length = 100;
const int rank = RANKINGLENGTH;
int i, j;
float average_power[rank];
float min_power[rank];
float average_combo[rank];
int min_combo[rank];
unsigned long long tableID;
unsigned long long color_table[6];
//struct drand48_data drand_buf;
#pragma omp parallel private(i,j, tableID, color_table)
{
int seed = 98503+(unsigned)time(NULL);
#ifdef __OPENMP
seed = seed + omp_get_thread_num()*1999;
#endif
//srand48_r(seed,&drand_buf);
#pragma omp for
for(i = 0;i < rank;i++){
tableID = MID[i];
float pave = 0.0;
float cave = 0.0;
float pmin = 1000000000.0;
int cmin = combo_length;
for(j = 0;j < 10000;j++){
//init_combo_info(color_combo, num_drops_combo, isLine_combo, combo_length);
int color_combo[combo_length];
int num_drops_combo[combo_length];
int isLine_combo[combo_length];
int num_c;
for(num_c = 0;num_c < 6;num_c++){
color_table[num_c] = 0;
}
switch(table_size){
case SMALL_TABLE:
generate_table_small(tableID, color_table);
break;
case NORMAL_TABLE:
generate_table_normal(tableID, color_table);
break;
case BIG_TABLE:
generate_table_big(tableID, color_table);
break;
default:
fprintf(stderr, "unknown table size\n");
exit(1);
}
int combo_counter = 0;
int returned_combo_counter = 0;
do{
combo_counter = returned_combo_counter;
switch(table_size){
case SMALL_TABLE:
returned_combo_counter = one_step_small(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, 6);
break;
case NORMAL_TABLE:
returned_combo_counter = one_step_normal(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, 6);
break;
case BIG_TABLE:
returned_combo_counter = one_step_big(color_table, color_combo, num_drops_combo, isLine_combo, combo_counter, 6);
break;
}
fill_random(color_table, width, hight, /*drand_buf*/&seed);
}while(returned_combo_counter != combo_counter);
float power = return_attack(combo_counter, color_combo, num_drops_combo, isLine_combo, LS, isStrong, line, way);
if(power < pmin){
pmin = power;
}
if(combo_counter < cmin){
cmin = combo_counter;
}
pave += power;
cave += combo_counter;
}
average_combo[i] = cave/10000.0;
average_power[i] = pave/10000.0;
min_combo[i] = cmin;
min_power[i] = pmin;
}
}
printf("rank,tableID ,power ,ave power ,min power ,ave combo ,min combo\n");
for(i = 0;i < rank;i++){
printf("%4d,%13lld,%10.3f,%10.3f,%10.3f,%10.3f,%6d\n",i,MID[i],MP[i],average_power[i],min_power[i],average_combo[i],min_combo[i]);
}
}
|
v_add.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 10000000
#define REPEAT 100
void v_add_naive(double* x, double* y, double* z)
{
#pragma omp parallel
{
for (int i = 0; i < ARRAY_SIZE; i++)
z[i] = x[i] + y[i];
}
}
// Edit this function (Method 1)
void v_add_optimized_adjacent(double* x, double* y, double* z)
{
#pragma omp parallel
{
int thread_num = omp_get_num_threads();
int id = omp_get_thread_num();
for (int i = id; i < ARRAY_SIZE; i += thread_num)
z[i] = x[i] + y[i];
}
}
// Edit this function (Method 2)
void v_add_optimized_chunks(double* x, double* y, double* z)
{
int thread_num;
int chunk;
#pragma omp parallel
{
thread_num = omp_get_num_threads();
chunk = ARRAY_SIZE / thread_num;
int id = omp_get_thread_num();
int start = (id - 1) * chunk;
for (int i = start; i < start + chunk; i++)
z[i] = x[i] + y[i];
}
for (int i = (thread_num - 1) * chunk; i < ARRAY_SIZE; i += 1) {
z[i] = x[i] + y[i];
}
}
double* gen_array(int n)
{
double* array = (double*)malloc(n * sizeof(double));
for (int i = 0; i < n; i++)
array[i] = drand48();
return array;
}
// Double check if it is correct
int verify(double* x, double* y, void (*funct)(double* x, double* y, double* z))
{
double* z_v_add = (double*)malloc(ARRAY_SIZE * sizeof(double));
double* z_oracle = (double*)malloc(ARRAY_SIZE * sizeof(double));
(*funct)(x, y, z_v_add);
for (int i = 0; i < ARRAY_SIZE; i++)
z_oracle[i] = x[i] + y[i];
for (int i = 0; i < ARRAY_SIZE; i++)
if (z_oracle[i] != z_v_add[i])
return 0;
return 1;
}
int main()
{
// Generate input vectors and destination vector
double* x = gen_array(ARRAY_SIZE);
double* y = gen_array(ARRAY_SIZE);
double* z = (double*)malloc(ARRAY_SIZE * sizeof(double));
// Test framework that sweeps the number of threads and times each run
double start_time, run_time;
int num_threads = omp_get_max_threads();
for (int i = 1; i <= num_threads; i++) {
omp_set_num_threads(i);
start_time = omp_get_wtime();
for (int j = 0; j < REPEAT; j++)
v_add_optimized_adjacent(x, y, z);
run_time = omp_get_wtime() - start_time;
if (!verify(x, y, v_add_optimized_adjacent)) {
printf("v_add optimized adjacent does not match oracle\n");
return -1;
}
printf("Optimized adjacent: %d thread(s) took %f seconds\n", i, run_time);
}
for (int i = 1; i <= num_threads; i++) {
omp_set_num_threads(i);
start_time = omp_get_wtime();
for (int j = 0; j < REPEAT; j++)
v_add_optimized_chunks(x, y, z);
run_time = omp_get_wtime() - start_time;
if (!verify(x, y, v_add_optimized_chunks)) {
printf("v_add optimized chunks does not match oracle\n");
return -1;
}
printf("Optimized chunks: %d thread(s) took %f seconds\n", i, run_time);
}
for (int i = 1; i <= num_threads; i++) {
omp_set_num_threads(i);
start_time = omp_get_wtime();
for (int j = 0; j < REPEAT; j++)
v_add_naive(x, y, z);
run_time = omp_get_wtime() - start_time;
printf("Naive: %d thread(s) took %f seconds\n", i, run_time);
}
return 0;
}
|
fourier.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF OOO U U RRRR IIIII EEEEE RRRR %
% F O O U U R R I E R R %
% FFF O O U U RRRR I EEE RRRR %
% F O O U U R R I E R R %
% F OOO UUU R R IIIII EEEEE R R %
% %
% %
% MagickCore Discrete Fourier Transform Methods %
% %
% Software Design %
% Sean Burke %
% Fred Weinhaus %
% Cristy %
% July 2009 %
% %
% %
% Copyright 1999-2017 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/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/fourier.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#if defined(MAGICKCORE_FFTW_DELEGATE)
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
#include <complex.h>
#endif
#include <fftw3.h>
#if !defined(MAGICKCORE_HAVE_CABS)
#define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1]))
#endif
#if !defined(MAGICKCORE_HAVE_CARG)
#define carg(z) (atan2(cimag(z),creal(z)))
#endif
#if !defined(MAGICKCORE_HAVE_CIMAG)
#define cimag(z) (z[1])
#endif
#if !defined(MAGICKCORE_HAVE_CREAL)
#define creal(z) (z[0])
#endif
#endif
/*
Typedef declarations.
*/
typedef struct _FourierInfo
{
PixelChannel
channel;
MagickBooleanType
modulus;
size_t
width,
height;
ssize_t
center;
} FourierInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p l e x I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ComplexImages() performs complex mathematics on an image sequence.
%
% The format of the ComplexImages method is:
%
% MagickBooleanType ComplexImages(Image *images,const ComplexOperator op,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A complex operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,images->columns,images->rows,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,images->columns,images->rows,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ComplexImages)
#endif
proceed=SetImageProgress(images,ComplexImageTag,progress++,
images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r w a r d F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ForwardFourierTransformImage() implements the discrete Fourier transform
% (DFT) of the image either as a magnitude / phase or real / imaginary image
% pair.
%
% The format of the ForwadFourierTransformImage method is:
%
% Image *ForwardFourierTransformImage(const Image *image,
% const MagickBooleanType modulus,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulus: if true, return as transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType RollFourier(const size_t width,const size_t height,
const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels)
{
double
*source_pixels;
MemoryInfo
*source_info;
register ssize_t
i,
x;
ssize_t
u,
v,
y;
/*
Move zero frequency (DC, average color) from (0,0) to (width/2,height/2).
*/
source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
return(MagickFalse);
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
i=0L;
for (y=0L; y < (ssize_t) height; y++)
{
if (y_offset < 0L)
v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset;
else
v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height :
y+y_offset;
for (x=0L; x < (ssize_t) width; x++)
{
if (x_offset < 0L)
u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset;
else
u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width :
x+x_offset;
source_pixels[v*width+u]=roll_pixels[i++];
}
}
(void) CopyMagickMemory(roll_pixels,source_pixels,height*width*
sizeof(*source_pixels));
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType ForwardQuadrantSwap(const size_t width,
const size_t height,double *source_pixels,double *forward_pixels)
{
MagickBooleanType
status;
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,
source_pixels);
if (status == MagickFalse)
return(MagickFalse);
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x];
for (y=1; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[(height-y)*width+width/2L-x-1L]=
source_pixels[y*center+x+1L];
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[width/2L-x-1L]=source_pixels[x+1L];
return(MagickTrue);
}
static void CorrectPhaseLHS(const size_t width,const size_t height,
double *fourier_pixels)
{
register ssize_t
x;
ssize_t
y;
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
fourier_pixels[y*width+x]*=(-1.0);
}
static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info,
Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*magnitude_pixels,
*phase_pixels;
Image
*magnitude_image,
*phase_image;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
register Quantum
*q;
register ssize_t
x;
ssize_t
i,
y;
magnitude_image=GetFirstImageInList(image);
phase_image=GetNextImageInList(image);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",image->filename);
return(MagickFalse);
}
/*
Create "Fourier Transform" image from constituent arrays.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
(void) ResetMagickMemory(magnitude_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*magnitude_pixels));
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
(void) ResetMagickMemory(phase_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*phase_pixels));
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude,magnitude_pixels);
if (status != MagickFalse)
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase,
phase_pixels);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]/=(2.0*MagickPI);
phase_pixels[i]+=0.5;
i++;
}
}
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(magnitude_image);
}
status=SyncCacheViewAuthenticPixels(magnitude_view,exception);
if (status == MagickFalse)
break;
}
magnitude_view=DestroyCacheView(magnitude_view);
i=0L;
phase_view=AcquireAuthenticCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(phase_image);
}
status=SyncCacheViewAuthenticPixels(phase_view,exception);
if (status == MagickFalse)
break;
}
phase_view=DestroyCacheView(phase_view);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
const Image *image,double *magnitude_pixels,double *phase_pixels,
ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_complex
*forward_pixels;
fftw_plan
fftw_r2c_plan;
MemoryInfo
*forward_info,
*source_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Generate the forward Fourier transform.
*/
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
ResetMagickMemory(source_pixels,0,fourier_info->width*fourier_info->height*
sizeof(*source_pixels));
i=0L;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
source_pixels[i]=QuantumScale*GetPixelRed(image,p);
break;
}
case GreenPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelGreen(image,p);
break;
}
case BluePixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlue(image,p);
break;
}
case BlackPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlack(image,p);
break;
}
case AlphaPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelAlpha(image,p);
break;
}
}
i++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
forward_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*forward_pixels));
if (forward_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
return(MagickFalse);
}
forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height,
source_pixels,forward_pixels,FFTW_ESTIMATE);
fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels);
fftw_destroy_plan(fftw_r2c_plan);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0))
{
double
gamma;
/*
Normalize fourier transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
forward_pixels[i]*=gamma;
#else
forward_pixels[i][0]*=gamma;
forward_pixels[i][1]*=gamma;
#endif
i++;
}
}
/*
Generate magnitude and phase (or real and imaginary).
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=cabs(forward_pixels[i]);
phase_pixels[i]=carg(forward_pixels[i]);
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=creal(forward_pixels[i]);
phase_pixels[i]=cimag(forward_pixels[i]);
i++;
}
forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info);
return(MagickTrue);
}
static MagickBooleanType ForwardFourierTransformChannel(const Image *image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
double
*magnitude_pixels,
*phase_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
fourier_info.width=image->columns;
fourier_info.height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows : image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info == (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels,
phase_pixels,exception);
if (status != MagickFalse)
status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels,
phase_pixels,exception);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
#endif
MagickExport Image *ForwardFourierTransformImage(const Image *image,
const MagickBooleanType modulus,ExceptionInfo *exception)
{
Image
*fourier_image;
fourier_image=NewImageList();
#if !defined(MAGICKCORE_FFTW_DELEGATE)
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
image->filename);
#else
{
Image
*magnitude_image;
size_t
height,
width;
width=image->columns;
height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows :
image->columns;
width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
height=width;
magnitude_image=CloneImage(image,width,height,MagickTrue,exception);
if (magnitude_image != (Image *) NULL)
{
Image
*phase_image;
magnitude_image->storage_class=DirectClass;
magnitude_image->depth=32UL;
phase_image=CloneImage(image,width,height,MagickTrue,exception);
if (phase_image == (Image *) NULL)
magnitude_image=DestroyImage(magnitude_image);
else
{
MagickBooleanType
is_gray,
status;
phase_image->storage_class=DirectClass;
phase_image->depth=32UL;
AppendImageToList(&fourier_image,magnitude_image);
AppendImageToList(&fourier_image,phase_image);
status=MagickTrue;
is_gray=IsImageGray(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=ForwardFourierTransformChannel(image,
RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->colorspace == CMYKColorspace)
thread_status=ForwardFourierTransformChannel(image,
BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->alpha_trait != UndefinedPixelTrait)
thread_status=ForwardFourierTransformChannel(image,
AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImageList(fourier_image);
fftw_cleanup();
}
}
}
#endif
return(fourier_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n v e r s e F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InverseFourierTransformImage() implements the inverse discrete Fourier
% transform (DFT) of the image either as a magnitude / phase or real /
% imaginary image pair.
%
% The format of the InverseFourierTransformImage method is:
%
% Image *InverseFourierTransformImage(const Image *magnitude_image,
% const Image *phase_image,const MagickBooleanType modulus,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o magnitude_image: the magnitude or real image.
%
% o phase_image: the phase or imaginary image.
%
% o modulus: if true, return transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType InverseQuadrantSwap(const size_t width,
const size_t height,const double *source,double *destination)
{
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
for (y=1L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L+1L); x++)
destination[(height-y)*center-x+width/2L]=source[y*width+x];
for (y=0L; y < (ssize_t) height; y++)
destination[y*center]=source[y*width+width/2L];
for (x=0L; x < center; x++)
destination[x]=source[center-x-1L];
return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination));
}
static MagickBooleanType InverseFourier(FourierInfo *fourier_info,
const Image *magnitude_image,const Image *phase_image,
fftw_complex *fourier_pixels,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*inverse_pixels,
*magnitude_pixels,
*phase_pixels;
MagickBooleanType
status;
MemoryInfo
*inverse_info,
*magnitude_info,
*phase_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Inverse fourier - read image and break down into a double array.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
inverse_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*inverse_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL) ||
(inverse_info == (MemoryInfo *) NULL))
{
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (inverse_info != (MemoryInfo *) NULL)
inverse_info=RelinquishVirtualMemory(inverse_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info);
i=0L;
magnitude_view=AcquireVirtualCacheView(magnitude_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p);
break;
}
case GreenPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p);
break;
}
case BluePixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p);
break;
}
case BlackPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p);
break;
}
case AlphaPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p);
break;
}
}
i++;
p+=GetPixelChannels(magnitude_image);
}
}
magnitude_view=DestroyCacheView(magnitude_view);
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude_pixels,inverse_pixels);
(void) CopyMagickMemory(magnitude_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*magnitude_pixels));
i=0L;
phase_view=AcquireVirtualCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p);
break;
}
case GreenPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p);
break;
}
case BluePixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p);
break;
}
case BlackPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p);
break;
}
case AlphaPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p);
break;
}
}
i++;
p+=GetPixelChannels(phase_image);
}
}
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]-=0.5;
phase_pixels[i]*=(2.0*MagickPI);
i++;
}
}
phase_view=DestroyCacheView(phase_view);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (status != MagickFalse)
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
phase_pixels,inverse_pixels);
(void) CopyMagickMemory(phase_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*phase_pixels));
inverse_info=RelinquishVirtualMemory(inverse_info);
/*
Merge two sets.
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I*
magnitude_pixels[i]*sin(phase_pixels[i]);
#else
fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]);
fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]);
#endif
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i];
#else
fourier_pixels[i][0]=magnitude_pixels[i];
fourier_pixels[i][1]=phase_pixels[i];
#endif
i++;
}
magnitude_info=RelinquishVirtualMemory(magnitude_info);
phase_info=RelinquishVirtualMemory(phase_info);
return(status);
}
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_plan
fftw_c2r_plan;
MemoryInfo
*source_info;
register Quantum
*q;
register ssize_t
i,
x;
ssize_t
y;
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"inverse") == 0)
{
double
gamma;
/*
Normalize inverse transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]*=gamma;
#else
fourier_pixels[i][0]*=gamma;
fourier_pixels[i][1]*=gamma;
#endif
i++;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_InverseFourierTransform)
#endif
fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
fourier_pixels,source_pixels,FFTW_ESTIMATE);
fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels);
fftw_destroy_plan(fftw_c2r_plan);
i=0L;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
if (y >= (ssize_t) image->rows)
break;
q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width >
image->columns ? image->columns : fourier_info->width,1UL,exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
if (x < (ssize_t) image->columns)
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
}
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType InverseFourierTransformChannel(
const Image *magnitude_image,const Image *phase_image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
fftw_complex
*inverse_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*inverse_info;
fourier_info.width=magnitude_image->columns;
fourier_info.height=magnitude_image->rows;
if ((magnitude_image->columns != magnitude_image->rows) ||
((magnitude_image->columns % 2) != 0) ||
((magnitude_image->rows % 2) != 0))
{
size_t extent=magnitude_image->columns < magnitude_image->rows ?
magnitude_image->rows : magnitude_image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
inverse_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*inverse_pixels));
if (inverse_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info);
status=InverseFourier(&fourier_info,magnitude_image,phase_image,
inverse_pixels,exception);
if (status != MagickFalse)
status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image,
exception);
inverse_info=RelinquishVirtualMemory(inverse_info);
return(status);
}
#endif
MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image,
const Image *phase_image,const MagickBooleanType modulus,
ExceptionInfo *exception)
{
Image
*fourier_image;
assert(magnitude_image != (Image *) NULL);
assert(magnitude_image->signature == MagickCoreSignature);
if (magnitude_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
magnitude_image->filename);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",magnitude_image->filename);
return((Image *) NULL);
}
#if !defined(MAGICKCORE_FFTW_DELEGATE)
fourier_image=(Image *) NULL;
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
magnitude_image->filename);
#else
{
fourier_image=CloneImage(magnitude_image,magnitude_image->columns,
magnitude_image->rows,MagickTrue,exception);
if (fourier_image != (Image *) NULL)
{
MagickBooleanType
is_gray,
status;
status=MagickTrue;
is_gray=IsImageGray(magnitude_image);
if (is_gray != MagickFalse)
is_gray=IsImageGray(phase_image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->colorspace == CMYKColorspace)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->alpha_trait != UndefinedPixelTrait)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImage(fourier_image);
}
fftw_cleanup();
}
#endif
return(fourier_image);
}
|
convolution_5x5.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 conv5x5s1_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 float* kernel = _kernel;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
for (int q = 0; q < inch; q++)
{
float* outptr = out;
float* outptr2 = outptr + outw;
const float* img0 = bottom_blob.channel(q);
const float* kernel0 = kernel + p * inch * 25 + q * 25;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* r4 = img0 + w * 4;
const float* r5 = img0 + w * 5;
const float* k0 = kernel0;
const float* k1 = kernel0 + 5;
const float* k2 = kernel0 + 10;
const float* k3 = kernel0 + 15;
const float* k4 = kernel0 + 20;
#if __ARM_NEON
float32x4_t _k0123 = vld1q_f32(kernel0);
float32x4_t _k4567 = vld1q_f32(kernel0 + 4);
float32x4_t _k891011 = vld1q_f32(kernel0 + 8);
float32x4_t _k12131415 = vld1q_f32(kernel0 + 12);
float32x4_t _k16171819 = vld1q_f32(kernel0 + 16);
float32x4_t _k20212223 = vld1q_f32(kernel0 + 20);
float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]);
#endif // __ARM_NEON
int i = 0;
for (; i + 1 < outh; i += 2)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw - (nn << 2);
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
// v11 = rx1 / rx3
// v12 = rx2
// v13 v14 = intermediate sum register
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v7.4s}, [%1] \n" // v7 = out
"0: \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v8.4s}, [%2] \n" // v8 = out2
// r1
"prfm pldl1keep, [%4, #256] \n"
"ld1 {v9.4s, v10.4s}, [%4] \n" // v9 v10 = r10 r14
"add %4, %4, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n" //r11
"fmul v13.4s, v9.4s, %19.s[1] \n"
"fmla v8.4s, v9.4s, %18.s[0] \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n" //r12
"fmla v7.4s, v11.4s, %19.s[2] \n"
"fmul v14.4s, v11.4s, %18.s[1] \n"
"ext v11.16b, v9.16b, v10.16b, #12 \n" //r13
"fmla v13.4s, v12.4s, %19.s[3] \n"
"fmla v8.4s, v12.4s, %18.s[2] \n"
"fmla v7.4s, v11.4s, %20.s[0] \n"
"fmla v14.4s, v11.4s, %18.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"fmla v13.4s, v10.4s, %20.s[1] \n"
"fmla v8.4s, v10.4s, %19.s[0] \n"
// r2
"ld1 {v9.4s, v10.4s}, [%5] \n" // v9 v10 = r20 r24
"add %5, %5, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n" //r21
"fmla v7.4s, v9.4s, %20.s[2] \n"
"fmla v14.4s, v9.4s, %19.s[1] \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n" //r22
"fmla v13.4s, v11.4s, %20.s[3] \n"
"fmla v8.4s, v11.4s, %19.s[2] \n"
"ext v11.16b, v9.16b, v10.16b, #12 \n" //r23
"fmla v7.4s, v12.4s, %21.s[0] \n"
"fmla v14.4s, v12.4s, %19.s[3] \n"
"fmla v13.4s, v11.4s, %21.s[1] \n"
"fmla v8.4s, v11.4s, %20.s[0] \n"
"prfm pldl1keep, [%6, #256] \n"
"fmla v7.4s, v10.4s, %21.s[2] \n"
"fmla v14.4s, v10.4s, %20.s[1] \n"
// r3
"ld1 {v9.4s, v10.4s}, [%6] \n" // v9 v10 = r30 r34
"add %6, %6, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n" //r31
"fmla v13.4s, v9.4s, %21.s[3] \n"
"fmla v8.4s, v9.4s, %20.s[2] \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n" //r32
"fmla v7.4s, v11.4s, %22.s[0] \n"
"fmla v14.4s, v11.4s, %20.s[3] \n"
"ext v11.16b, v9.16b, v10.16b, #12 \n" //r33
"fmla v13.4s, v12.4s, %22.s[1] \n"
"fmla v8.4s, v12.4s, %21.s[0] \n"
"fmla v7.4s, v11.4s, %22.s[2] \n"
"fmla v14.4s, v11.4s, %21.s[1] \n"
"prfm pldl1keep, [%7, #256] \n"
"fmla v13.4s, v10.4s, %22.s[3] \n"
"fmla v8.4s, v10.4s, %21.s[2] \n"
// r4
"ld1 {v9.4s, v10.4s}, [%7] \n" // v9 v10 = r40 r44
"add %7, %7, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n" //r41
"fmla v7.4s, v9.4s, %23.s[0] \n"
"fmla v14.4s, v9.4s, %21.s[3] \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n" //r41
"fmla v13.4s, v11.4s, %23.s[1] \n"
"fmla v8.4s, v11.4s, %22.s[0] \n"
"ext v11.16b, v9.16b, v10.16b, #12 \n" //r41
"fmla v7.4s, v12.4s, %23.s[2] \n"
"fmla v14.4s, v12.4s, %22.s[1] \n"
"fmla v13.4s, v11.4s, %23.s[3] \n"
"fmla v8.4s, v11.4s, %22.s[2] \n"
"prfm pldl1keep, [%3, #256] \n"
"fmla v7.4s, v10.4s, %24.s[0] \n"
"fmla v14.4s, v10.4s, %22.s[3] \n"
// r0 and r5
"ld1 {v9.4s, v10.4s}, [%3] \n" // v9 v10 = r00 r04
"add %3, %3, #16 \n"
"ext v11.16b, v9.16b, v10.16b, #4 \n" //r01
"fmla v13.4s, v11.4s, %18.s[1] \n"
"ext v12.16b, v9.16b, v10.16b, #8 \n" //r02
"fmla v7.4s, v12.4s, %18.s[2] \n"
"ext v11.16b, v9.16b, v10.16b, #12 \n" //r03
"prfm pldl1keep, [%8, #256] \n"
"fmla v13.4s, v11.4s, %18.s[3] \n"
// r5
"ld1 {v11.4s, v12.4s}, [%8] \n" // v11 v12 = r50 r54
"add %8, %8, #16 \n"
"fmla v8.4s, v11.4s, %23.s[0] \n"
"fmla v14.4s, v12.4s, %24.s[0] \n"
"fmla v7.4s, v9.4s, %18.s[0] \n"
"fmla v13.4s, v10.4s, %19.s[0] \n"
"ext v9.16b, v11.16b, v12.16b, #4 \n" //r51
"ext v10.16b, v11.16b, v12.16b, #8 \n" //r52
"fmla v14.4s, v9.4s, %23.s[1] \n"
"ext v9.16b, v11.16b, v12.16b, #12 \n" //r53
"fmla v8.4s, v10.4s, %23.s[2] \n"
"fmla v14.4s, v9.4s, %23.s[3] \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"st1 {v7.4s}, [%1], #16 \n"
"fadd v8.4s, v8.4s, v14.4s \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v7.4s}, [%1] \n" // v7 = out
"st1 {v8.4s}, [%2], #16 \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(outptr2), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3), // %6
"=r"(r4), // %7
"=r"(r5) // %8
: "0"(nn),
"1"(outptr),
"2"(outptr2),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3),
"7"(r4),
"8"(r5),
"w"(_k0123), // %18
"w"(_k4567), // %19
"w"(_k891011), // %20
"w"(_k12131415), // %21
"w"(_k16171819), // %22
"w"(_k20212223), // %23
"w"(_k24242424) // %24
: "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
// "veor q13, q13 \n"
// "veor q14, q14 \n"
"pld [%1, #128] \n"
"vld1.f32 {d14-d15}, [%1] \n" // q7 = out
"0: \n"
// q11 = rx1 / rx3
// q12 = rx2
// q13 q14 = intermediate sum register
"pld [%2, #128] \n"
"vld1.f32 {d16-d17}, [%2] \n" // q8 = out2
"pld [%4, #256] \n"
// r1
"vld1.f32 {d18-d21}, [%4] \n" // q9 q10 = r10 r14
"add %4, #16 \n"
"vext.32 q11, q9, q10, #1 \n" // r11
"vmul.f32 q13, q9, %e19[1] \n"
"vmla.f32 q8, q9, %e18[0] \n"
"vext.32 q12, q9, q10, #2 \n" // r12
"vmla.f32 q7, q11, %f19[0] \n"
"vmul.f32 q14, q11, %e18[1] \n"
"vext.32 q11, q9, q10, #3 \n" // r13
"vmla.f32 q13, q12, %f19[1] \n"
"vmla.f32 q8, q12, %f18[0] \n"
"vmla.f32 q7, q11, %e20[0] \n"
"vmla.f32 q14, q11, %f18[1] \n"
"pld [%5, #256] \n"
"vmla.f32 q13, q10, %e20[1] \n"
"vmla.f32 q8, q10, %e19[0] \n"
// r2
"vld1.f32 {d18-d21}, [%5] \n" // q9 q10 = r20 r24
"add %5, #16 \n"
"vext.32 q11, q9, q10, #1 \n" // r21
"vmla.f32 q7, q9, %f20[0] \n"
"vmla.f32 q14, q9, %e19[1] \n"
"vext.32 q12, q9, q10, #2 \n" // r22
"vmla.f32 q13, q11, %f20[1] \n"
"vmla.f32 q8, q11, %f19[0] \n"
"vext.32 q11, q9, q10, #3 \n" // r23
"vmla.f32 q7, q12, %e21[0] \n"
"vmla.f32 q14, q12, %f19[1] \n"
"vmla.f32 q13, q11, %e21[1] \n"
"vmla.f32 q8, q11, %e20[0] \n"
"pld [%6, #256] \n"
"vmla.f32 q7, q10, %f21[0] \n"
"vmla.f32 q14, q10, %e20[1] \n"
// r3
"vld1.f32 {d18-d21}, [%6] \n" // q9 q10 = r30 r34
"add %6, #16 \n"
"vext.32 q11, q9, q10, #1 \n" // r31
"vmla.f32 q13, q9, %f21[1] \n"
"vmla.f32 q8, q9, %f20[0] \n"
"vext.32 q12, q9, q10, #2 \n" // r32
"vmla.f32 q7, q11, %e22[0] \n"
"vmla.f32 q14, q11, %f20[1] \n"
"vext.32 q11, q9, q10, #3 \n" // r33
"vmla.f32 q13, q12, %e22[1] \n"
"vmla.f32 q8, q12, %e21[0] \n"
"vmla.f32 q7, q11, %f22[0] \n"
"vmla.f32 q14, q11, %e21[1] \n"
"pld [%7, #256] \n"
"vmla.f32 q13, q10, %f22[1] \n"
"vmla.f32 q8, q10, %f21[0] \n"
// r4
"vld1.f32 {d18-d21}, [%7] \n" // q9 q10 = r40 r44
"add %7, #16 \n"
"vext.32 q11, q9, q10, #1 \n" // r41
"vmla.f32 q7, q9, %e23[0] \n"
"vmla.f32 q14, q9, %f21[1] \n"
"vext.32 q12, q9, q10, #2 \n" // r42
"vmla.f32 q13, q11, %e23[1] \n"
"vmla.f32 q8, q11, %e22[0] \n"
"vext.32 q11, q9, q10, #3 \n" // r43
"vmla.f32 q7, q12, %f23[0] \n"
"vmla.f32 q14, q12, %e22[1] \n"
"vmla.f32 q13, q11, %f23[1] \n"
"vmla.f32 q8, q11, %f22[0] \n"
"pld [%3, #256] \n"
"vmla.f32 q7, q10, %e24[0] \n"
"vmla.f32 q14, q10, %f22[1] \n"
// r0 and r5
"vld1.f32 {d18-d21}, [%3] \n" // q9 q10 = r00 r04
"add %3, #16 \n"
"vext.32 q11, q9, q10, #1 \n" // r01
"vmla.f32 q13, q11, %e18[1] \n"
"vext.32 q12, q9, q10, #2 \n" // r02
"vmla.f32 q7, q12, %f18[0] \n"
"vext.32 q11, q9, q10, #3 \n" // r03
"pld [%8, #256] \n"
"vmla.f32 q13, q11, %f18[1] \n"
// r5
"vld1.f32 {d22-d25}, [%8] \n" // q11 q12 = r50 r54
"add %8, #16 \n"
"vmla.f32 q8, q11, %e23[0] \n"
"vmla.f32 q14, q12, %e24[0] \n"
"vmla.f32 q7, q9, %e18[0] \n"
"vmla.f32 q13, q10, %e19[0] \n"
"vext.32 q9, q11, q12, #1 \n" // r51
"vext.32 q10, q11, q12, #2 \n" // r52
"vmla.f32 q14, q9, %e23[1] \n"
"vext.32 q9, q11, q12, #3 \n" // r53
"vmla.f32 q8, q10, %f23[0] \n"
"vmla.f32 q14, q9, %f23[1] \n"
"vadd.f32 q7, q7, q13 \n"
// "veor q13, q13 \n"
"vst1.f32 {d14-d15}, [%1]! \n"
"vadd.f32 q8, q8, q14 \n"
"pld [%1, #128] \n"
"vld1.f32 {d14-d15}, [%1] \n" // q7 = out
// "veor q14, q14 \n"
"vst1.f32 {d16-d17}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(outptr2), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3), // %6
"=r"(r4), // %7
"=r"(r5) // %8
: "0"(nn),
"1"(outptr),
"2"(outptr2),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3),
"7"(r4),
"8"(r5),
"w"(_k0123), // %18
"w"(_k4567), // %19
"w"(_k891011), // %20
"w"(_k12131415), // %21
"w"(_k16171819), // %22
"w"(_k20212223), // %23
"w"(_k24242424) // %24
: "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
float sum = 0;
float sum2 = 0;
#if __ARM_NEON
float32x4_t _r1 = vld1q_f32(r1);
float32x4_t _k1 = vld1q_f32(k1);
float32x4_t _sum = vmulq_f32(_r1, _k1);
float32x4_t _sum2 = vmulq_f32(_r1, _k0123);
float32x4_t _r2 = vld1q_f32(r2);
float32x4_t _k2 = vld1q_f32(k2);
_sum = vmlaq_f32(_sum, _r2, _k2);
_sum2 = vmlaq_f32(_sum2, _r2, _k1);
float32x4_t _r3 = vld1q_f32(r3);
float32x4_t _k3 = vld1q_f32(k3);
_sum = vmlaq_f32(_sum, _r3, _k3);
_sum2 = vmlaq_f32(_sum2, _r3, _k2);
float32x4_t _r4 = vld1q_f32(r4);
_sum = vmlaq_f32(_sum, _r4, _k20212223);
_sum2 = vmlaq_f32(_sum2, _r4, _k3);
float32x4_t _r0 = vld1q_f32(r0);
_sum = vmlaq_f32(_sum, _r0, _k0123);
float32x4_t _r5 = vld1q_f32(r5);
_sum2 = vmlaq_f32(_sum2, _r5, _k20212223);
float32x4_t _k_t4 = {};
_k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0);
_k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1);
_k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2);
_k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3);
float32x4_t _r_t4 = {};
_r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0);
_r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1);
_r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2);
_r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3);
_sum = vmlaq_f32(_sum, _r_t4, _k_t4);
sum = r4[4] * k4[4];
_r_t4 = vextq_f32(_r_t4, _r_t4, 1);
_r_t4 = vsetq_lane_f32(r4[4], _r_t4, 3);
_sum2 = vmlaq_f32(_sum2, _r_t4, _k_t4);
sum2 = r5[4] * k4[4];
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2));
float32x2_t _ss_ss2 = vpadd_f32(_ss, _ss2);
sum += vget_lane_f32(_ss_ss2, 0);
sum2 += vget_lane_f32(_ss_ss2, 1);
#else
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r1[3] * k0[3];
sum2 += r1[4] * k0[4];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r2[3] * k1[3];
sum2 += r2[4] * k1[4];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
sum2 += r3[3] * k2[3];
sum2 += r3[4] * k2[4];
sum2 += r4[0] * k3[0];
sum2 += r4[1] * k3[1];
sum2 += r4[2] * k3[2];
sum2 += r4[3] * k3[3];
sum2 += r4[4] * k3[4];
sum2 += r5[0] * k4[0];
sum2 += r5[1] * k4[1];
sum2 += r5[2] * k4[2];
sum2 += r5[3] * k4[3];
sum2 += r5[4] * k4[4];
#endif // __ARM_NEON
*outptr += sum;
*outptr2 += sum2;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
outptr++;
outptr2++;
}
r0 += 4 + w;
r1 += 4 + w;
r2 += 4 + w;
r3 += 4 + w;
r4 += 4 + w;
r5 += 4 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw - (nn << 2);
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%1, #128] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld1 {v8.4s, v9.4s}, [%2] \n" // _r00 = vld1q_f32(r0+j);
"add %2, %2, #16 \n"
"0: \n"
"ld1 {v7.4s}, [%1] \n" // _sum = vld1q_f32(outptr+j);
"ext v10.16b, v8.16b, v9.16b, #4 \n" //_r01
"ext v11.16b, v8.16b, v9.16b, #8 \n" //_r02
"ext v12.16b, v8.16b, v9.16b, #12 \n" //_r03
"fmla v7.4s, v8.4s, %14.s[0] \n"
"fmul v13.4s, v10.4s, %14.s[1] \n"
"prfm pldl1keep, [%3, #256] \n"
"fmul v14.4s, v11.4s, %14.s[2] \n"
"fmul v15.4s, v12.4s, %14.s[3] \n"
"fmla v7.4s, v9.4s, %15.s[0] \n"
"ld1 {v8.4s, v9.4s}, [%3] \n"
"add %3, %3, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n" //_r11
"ext v11.16b, v8.16b, v9.16b, #8 \n" //_r12
"ext v12.16b, v8.16b, v9.16b, #12 \n" //_r13
"fmla v7.4s, v8.4s, %15.s[1] \n"
"fmla v13.4s, v10.4s, %15.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"fmla v14.4s, v11.4s, %15.s[3] \n"
"fmla v15.4s, v12.4s, %16.s[0] \n"
"fmla v7.4s, v9.4s, %16.s[1] \n"
"ld1 {v8.4s, v9.4s}, [%4] \n"
"add %4, %4, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n" //_r21
"ext v11.16b, v8.16b, v9.16b, #8 \n" //_r22
"ext v12.16b, v8.16b, v9.16b, #12 \n" //_r23
"fmla v7.4s, v8.4s, %16.s[2] \n"
"fmla v13.4s, v10.4s, %16.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"fmla v14.4s, v11.4s, %17.s[0] \n"
"fmla v15.4s, v12.4s, %17.s[1] \n"
"fmla v7.4s, v9.4s, %17.s[2] \n"
"ld1 {v8.4s, v9.4s}, [%5] \n"
"add %5, %5, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n" //_r31
"ext v11.16b, v8.16b, v9.16b, #8 \n" //_r32
"ext v12.16b, v8.16b, v9.16b, #12 \n" //_r33
"fmla v7.4s, v8.4s, %17.s[3] \n"
"fmla v13.4s, v10.4s, %18.s[0] \n"
"prfm pldl1keep, [%6, #256] \n"
"fmla v14.4s, v11.4s, %18.s[1] \n"
"fmla v15.4s, v12.4s, %18.s[2] \n"
"fmla v7.4s, v9.4s, %18.s[3] \n"
"ld1 {v8.4s, v9.4s}, [%6] \n"
"add %6, %6, #16 \n"
"ext v10.16b, v8.16b, v9.16b, #4 \n" //_r41
"ext v11.16b, v8.16b, v9.16b, #8 \n" //_r42
"ext v12.16b, v8.16b, v9.16b, #12 \n" //_r43
"fmla v7.4s, v8.4s, %19.s[0] \n"
"fmla v13.4s, v10.4s, %19.s[1] \n"
"fmla v14.4s, v11.4s, %19.s[2] \n"
"fmla v15.4s, v12.4s, %19.s[3] \n"
"fmla v7.4s, v9.4s, %20.s[0] \n"
"fadd v14.4s, v14.4s, v15.4s \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"prfm pldl1keep, [%2, #256] \n"
"fadd v7.4s, v7.4s, v14.4s \n"
"ld1 {v8.4s, v9.4s}, [%2] \n"
"add %2, %2, #16 \n"
"st1 {v7.4s}, [%1], #16 \n"
"prfm pldl1keep, [%1, #128] \n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
"sub %2, %2, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(r4) // %6
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"w"(_k0123), // %14
"w"(_k4567), // %15
"w"(_k891011), // %16
"w"(_k12131415), // %17
"w"(_k16171819), // %18
"w"(_k20212223), // %19
"w"(_k24242424) // %20
: "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
// "veor q15, q15 \n"// _sum3 = 0;
"pld [%1, #128] \n"
"pld [%2, #256] \n"
"vld1.f32 {d16-d19}, [%2] \n" // _r00 = vld1q_f32(r0+j);
"add %2, #16 \n"
"0: \n"
"vld1.f32 {d14-d15}, [%1] \n" // _sum = vld1q_f32(outptr+j);
// "veor q13, q13 \n"// _sum2 = 0;
// "veor q14, q14 \n"// _sum3 = 0;
"vext.32 q10, q8, q9, #1 \n" // _r01
"vext.32 q11, q8, q9, #2 \n" // _r02
"vext.32 q12, q8, q9, #3 \n" // _r03
"vmla.f32 q7, q8, %e14[0] \n"
"vmul.f32 q13, q10, %e14[1] \n"
"pld [%3, #256] \n"
"vmul.f32 q14, q11, %f14[0] \n"
"vmul.f32 q15, q12, %f14[1] \n"
"vmla.f32 q7, q9, %e15[0] \n"
"vld1.f32 {d16-d19}, [%3] \n"
"add %3, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vext.32 q12, q8, q9, #3 \n"
"vmla.f32 q7, q8, %e15[1] \n"
"vmla.f32 q13, q10, %f15[0] \n"
"pld [%4, #256] \n"
"vmla.f32 q14, q11, %f15[1] \n"
"vmla.f32 q15, q12, %e16[0] \n"
"vmla.f32 q7, q9, %e16[1] \n"
"vld1.f32 {d16-d19}, [%4] \n"
"add %4, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vext.32 q12, q8, q9, #3 \n"
"vmla.f32 q7, q8, %f16[0] \n"
"vmla.f32 q13, q10, %f16[1] \n"
"pld [%5, #256] \n"
"vmla.f32 q14, q11, %e17[0] \n"
"vmla.f32 q15, q12, %e17[1] \n"
"vmla.f32 q7, q9, %f17[0] \n"
"vld1.f32 {d16-d19}, [%5] \n"
"add %5, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vext.32 q12, q8, q9, #3 \n"
"vmla.f32 q7, q8, %f17[1] \n"
"vmla.f32 q13, q10, %e18[0] \n"
"pld [%6, #256] \n"
"vmla.f32 q14, q11, %e18[1] \n"
"vmla.f32 q15, q12, %f18[0] \n"
"vmla.f32 q7, q9, %f18[1] \n"
"vld1.f32 {d16-d19}, [%6] \n"
"add %6, #16 \n"
"vext.32 q10, q8, q9, #1 \n"
"vext.32 q11, q8, q9, #2 \n"
"vext.32 q12, q8, q9, #3 \n"
"vmla.f32 q7, q8, %e19[0] \n"
"vmla.f32 q13, q10, %e19[1] \n"
"vmla.f32 q14, q11, %f19[0] \n"
"vmla.f32 q15, q12, %f19[1] \n"
"vmla.f32 q7, q9, %e20[0] \n"
"vadd.f32 q14, q14, q15 \n"
"vadd.f32 q7, q7, q13 \n"
// "veor q15, q15 \n"// _sum3 = 0;
"pld [%2, #256] \n"
"vadd.f32 q7, q7, q14 \n"
"vld1.f32 {d16-d19}, [%2] \n" // _r00 = vld1q_f32(r0+j);
"add %2, #16 \n"
"vst1.f32 {d14-d15}, [%1]! \n"
"pld [%1, #128] \n"
"subs %0, #1 \n"
"bne 0b \n"
"sub %2, #16 \n"
: "=r"(nn), // %0
"=r"(outptr), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(r4) // %6
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"w"(_k0123), // %14
"w"(_k4567), // %15
"w"(_k891011), // %16
"w"(_k12131415), // %17
"w"(_k16171819), // %18
"w"(_k20212223), // %19
"w"(_k24242424) // %20
: "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
float sum = 0;
#if __ARM_NEON
float32x4_t _r0 = vld1q_f32(r0);
float32x4_t _sum = vmulq_f32(_r0, _k0123);
float32x4_t _r1 = vld1q_f32(r1);
_sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1));
float32x4_t _r2 = vld1q_f32(r2);
_sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2));
float32x4_t _r3 = vld1q_f32(r3);
_sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3));
float32x4_t _r4 = vld1q_f32(r4);
_sum = vmlaq_f32(_sum, _r4, _k20212223);
float32x4_t _k_t4 = {};
_k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0);
_k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1);
_k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2);
_k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3);
float32x4_t _r_t4 = {};
_r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0);
_r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1);
_r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2);
_r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3);
_sum = vmlaq_f32(_sum, _r_t4, _k_t4);
sum = r4[4] * k4[4];
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
_ss = vpadd_f32(_ss, _ss);
sum += vget_lane_f32(_ss, 0);
#else
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
#endif
*outptr += sum;
r0++;
r1++;
r2++;
r3++;
r4++;
outptr++;
}
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
}
}
}
}
static void conv5x5s2_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;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
for (int q = 0; q < inch; q++)
{
float* outptr = out;
const float* img0 = bottom_blob.channel(q);
const float* kernel0 = kernel + p * inch * 25 + q * 25;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* r4 = img0 + w * 4;
const float* k0 = kernel0;
const float* k1 = kernel0 + 5;
const float* k2 = kernel0 + 10;
const float* k3 = kernel0 + 15;
const float* k4 = kernel0 + 20;
#if __ARM_NEON
float32x4_t _k0123 = vld1q_f32(kernel0);
float32x4_t _k4567 = vld1q_f32(kernel0 + 4);
float32x4_t _k891011 = vld1q_f32(kernel0 + 8);
float32x4_t _k12131415 = vld1q_f32(kernel0 + 12);
float32x4_t _k16171819 = vld1q_f32(kernel0 + 16);
float32x4_t _k20212223 = vld1q_f32(kernel0 + 20);
float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]);
#endif // __ARM_NEON
for (int i = 0; i < outh; i++)
{
#if __ARM_NEON
int nn = outw >> 2;
int remain = outw - (nn << 2);
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
#if __aarch64__
if (nn > 0)
{
asm volatile(
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v8.4s, v9.4s}, [%2], #32 \n" // v8 = 0 2 4 6 q9 = 1 3 5 7
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v10.4s, v11.4s}, [%2] \n" // v10 = 8 10 12 14 v11 = 9 11 13 15
"prfm pldl1keep, [%1, #128] \n"
"0: \n"
"ld1 {v7.4s}, [%1] \n" // v7 = outptr
"ext v12.16b, v8.16b, v10.16b, #4 \n" // v12 = 2 4 6 8
"ext v11.16b, v9.16b, v11.16b, #4 \n" // v11 = 3 5 7 9
"ext v10.16b, v8.16b, v10.16b, #8 \n" // v10 = 4 6 8 10
"fmla v7.4s, v8.4s, %14.s[0] \n"
"fmul v13.4s, v9.4s, %14.s[1] \n"
"prfm pldl1keep, [%3, #256] \n"
"fmul v14.4s, v12.4s, %14.s[2] \n"
"fmul v15.4s, v11.4s, %14.s[3] \n"
"fmla v7.4s, v10.4s, %15.s[0] \n"
"ld2 {v8.4s, v9.4s}, [%3], #32 \n"
"prfm pldl1keep, [%3, #256] \n"
"ld2 {v10.4s, v11.4s}, [%3] \n"
"ext v12.16b, v8.16b, v10.16b, #4 \n"
"ext v11.16b, v9.16b, v11.16b, #4 \n"
"ext v10.16b, v8.16b, v10.16b, #8 \n"
"fmla v7.4s, v8.4s, %15.s[1] \n"
"fmla v13.4s, v9.4s, %15.s[2] \n"
"prfm pldl1keep, [%4, #256] \n"
"fmla v14.4s, v12.4s, %15.s[3] \n"
"fmla v15.4s, v11.4s, %16.s[0] \n"
"fmla v7.4s, v10.4s, %16.s[1] \n"
"ld2 {v8.4s, v9.4s}, [%4], #32 \n"
"prfm pldl1keep, [%4, #256] \n"
"ld2 {v10.4s, v11.4s}, [%4] \n"
"ext v12.16b, v8.16b, v10.16b, #4 \n"
"ext v11.16b, v9.16b, v11.16b, #4 \n"
"ext v10.16b, v8.16b, v10.16b, #8 \n"
"fmla v7.4s, v8.4s, %16.s[2] \n"
"fmla v13.4s, v9.4s, %16.s[3] \n"
"prfm pldl1keep, [%5, #256] \n"
"fmla v14.4s, v12.4s, %17.s[0] \n"
"fmla v15.4s, v11.4s, %17.s[1] \n"
"fmla v7.4s, v10.4s, %17.s[2] \n"
"ld2 {v8.4s, v9.4s}, [%5], #32 \n"
"prfm pldl1keep, [%5, #256] \n"
"ld2 {v10.4s, v11.4s}, [%5] \n"
"ext v12.16b, v8.16b, v10.16b, #4 \n"
"ext v11.16b, v9.16b, v11.16b, #4 \n"
"ext v10.16b, v8.16b, v10.16b, #8 \n"
"fmla v7.4s, v8.4s, %17.s[3] \n"
"fmla v13.4s, v9.4s, %18.s[0] \n"
"prfm pldl1keep, [%6, #256] \n"
"fmla v14.4s, v12.4s, %18.s[1] \n"
"fmla v15.4s, v11.4s, %18.s[2] \n"
"fmla v7.4s, v10.4s, %18.s[3] \n"
"ld2 {v8.4s, v9.4s}, [%6], #32 \n"
"prfm pldl1keep, [%6, #256] \n"
"ld2 {v10.4s, v11.4s}, [%6] \n"
"ext v12.16b, v8.16b, v10.16b, #4 \n"
"ext v11.16b, v9.16b, v11.16b, #4 \n"
"ext v10.16b, v8.16b, v10.16b, #8 \n"
"fmla v7.4s, v8.4s, %19.s[0] \n"
"fmla v13.4s, v9.4s, %19.s[1] \n"
"fmla v14.4s, v12.4s, %19.s[2] \n"
"fmla v15.4s, v11.4s, %19.s[3] \n"
"fmla v7.4s, v10.4s, %20.s[0] \n"
"prfm pldl1keep, [%2, #256] \n"
"ld2 {v8.4s, v9.4s}, [%2], #32 \n"
"fadd v14.4s, v14.4s, v15.4s \n"
"fadd v7.4s, v7.4s, v13.4s \n"
"prfm pldl1keep, [%2, #256] \n"
"fadd v7.4s, v7.4s, v14.4s \n"
"ld2 {v10.4s, v11.4s}, [%2] \n"
"st1 {v7.4s}, [%1], #16 \n"
"prfm pldl1keep, [%1, #128] \n"
"subs %w0, %w0, #1 \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
"=r"(r4) // %6
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"w"(_k0123), // %14
"w"(_k4567), // %15
"w"(_k891011), // %16
"w"(_k12131415), // %17
"w"(_k16171819), // %18
"w"(_k20212223), // %19
"w"(_k24242424) // %20
: "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15");
}
#else
if (nn > 0)
{
asm volatile(
// "veor q15, q15 \n"// _sump3 = 0;
// "veor q13, q13 \n"// _sump2 = 0;
// "veor q14, q14 \n"// _sump3 = 0;
"pld [%2, #256] \n"
"vld2.f32 {d16-d19}, [%2]! \n" // q8 = 0 2 4 6 q9 = 1 3 5 7
"pld [%2, #256] \n"
"vld2.f32 {d20-d23}, [%2] \n" // q10 = 8 10 12 14 q11 = 9 11 13 15
"pld [%1, #128] \n"
"0: \n"
"vld1.f32 {d14-d15}, [%1] \n" // q7 = outptr
"vext.32 q12, q8, q10, #1 \n" // q12 = 2 4 6 8
"vext.32 q11, q9, q11, #1 \n" // q11 = 3 5 7 9
"vext.32 q10, q8, q10, #2 \n" // q10 = 4 6 8 10
"vmla.f32 q7, q8, %e14[0] \n"
"vmul.f32 q13, q9, %e14[1] \n"
"pld [%3, #256] \n"
"vmul.f32 q14, q12, %f14[0] \n"
"vmul.f32 q15, q11, %f14[1] \n"
"vmla.f32 q7, q10, %e15[0] \n"
"vld2.f32 {d16-d19}, [%3]! \n"
"pld [%3, #256] \n"
"vld2.f32 {d20-d23}, [%3] \n"
"vext.32 q12, q8, q10, #1 \n"
"vext.32 q11, q9, q11, #1 \n"
"vext.32 q10, q8, q10, #2 \n"
"vmla.f32 q7, q8, %e15[1] \n"
"vmla.f32 q13, q9, %f15[0] \n"
"pld [%4, #256] \n"
"vmla.f32 q14, q12, %f15[1] \n"
"vmla.f32 q15, q11, %e16[0] \n"
"vmla.f32 q7, q10, %e16[1] \n"
"vld2.f32 {d16-d19}, [%4]! \n"
"pld [%4, #256] \n"
"vld2.f32 {d20-d23}, [%4] \n"
"vext.32 q12, q8, q10, #1 \n"
"vext.32 q11, q9, q11, #1 \n"
"vext.32 q10, q8, q10, #2 \n"
"vmla.f32 q7, q8, %f16[0] \n"
"vmla.f32 q13, q9, %f16[1] \n"
"pld [%5, #256] \n"
"vmla.f32 q14, q12, %e17[0] \n"
"vmla.f32 q15, q11, %e17[1] \n"
"vmla.f32 q7, q10, %f17[0] \n"
"vld2.f32 {d16-d19}, [%5]! \n"
"pld [%5, #256] \n"
"vld2.f32 {d20-d23}, [%5] \n"
"vext.32 q12, q8, q10, #1 \n"
"vext.32 q11, q9, q11, #1 \n"
"vext.32 q10, q8, q10, #2 \n"
"vmla.f32 q7, q8, %f17[1] \n"
"vmla.f32 q13, q9, %e18[0] \n"
"pld [%6, #256] \n"
"vmla.f32 q14, q12, %e18[1] \n"
"vmla.f32 q15, q11, %f18[0] \n"
"vmla.f32 q7, q10, %f18[1] \n"
"vld2.f32 {d16-d19}, [%6]! \n"
"pld [%6, #256] \n"
"vld2.f32 {d20-d23}, [%6] \n"
"vext.32 q12, q8, q10, #1 \n"
"vext.32 q11, q9, q11, #1 \n"
"vext.32 q10, q8, q10, #2 \n"
"vmla.f32 q7, q8, %e19[0] \n"
"vmla.f32 q13, q9, %e19[1] \n"
"vmla.f32 q14, q12, %f19[0] \n"
"vmla.f32 q15, q11, %f19[1] \n"
"vmla.f32 q7, q10, %e20[0] \n"
"pld [%2, #256] \n"
"vld2.f32 {d16-d19}, [%2]! \n" // q8 = 0 2 4 6 q9 = 1 3 5 7
"vadd.f32 q14, q14, q15 \n"
"vadd.f32 q7, q7, q13 \n"
// "veor q15, q15 \n"// _sump3 = 0;
// "veor q13, q13 \n"// _sump2 = 0;
"pld [%2, #256] \n"
"vadd.f32 q7, q7, q14 \n"
"vld2.f32 {d20-d23}, [%2] \n" // q10 = 8 10 12 14 q11 = 9 11 13 15
// "veor q14, q14 \n"// _sump3 = 0;
"vst1.f32 {d14-d15}, [%1]! \n"
"pld [%1, #128] \n"
"subs %0, #1 \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
"=r"(r4) // %6
: "0"(nn),
"1"(outptr),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(r4),
"w"(_k0123), // %14
"w"(_k4567), // %15
"w"(_k891011), // %16
"w"(_k12131415), // %17
"w"(_k16171819), // %18
"w"(_k20212223), // %19
"w"(_k24242424) // %20
: "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15");
}
#endif // __aarch64__
#endif // __ARM_NEON
for (; remain > 0; remain--)
{
float sum = 0;
#if __ARM_NEON
float32x4_t _r0 = vld1q_f32(r0);
float32x4_t _sum = vmulq_f32(_r0, _k0123);
float32x4_t _r1 = vld1q_f32(r1);
_sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1));
float32x4_t _r2 = vld1q_f32(r2);
_sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2));
float32x4_t _r3 = vld1q_f32(r3);
_sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3));
float32x4_t _r4 = vld1q_f32(r4);
_sum = vmlaq_f32(_sum, _r4, _k20212223);
sum += r0[4] * k0[4];
sum += r1[4] * k1[4];
sum += r2[4] * k2[4];
sum += r3[4] * k3[4];
sum += r4[4] * k4[4];
float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum));
_ss = vpadd_f32(_ss, _ss);
sum += vget_lane_f32(_ss, 0);
#else
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
#endif
*outptr += sum;
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
r4 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
}
}
}
}
|
transfer_utility.h | /*
==============================================================================
KratosIncompressibleFluidApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).
Copyright 2007
Pooyan Dadvand, Riccardo Rossi
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following condition:
Distribution of this code for any commercial purpose is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================
*/
//
// Project Name: Kratos
// Last Modified by: $Author: pbecker $
// Date: $Date: 2011-09-21 12:30:32 $
// Revision: $Revision: 1.0 $
//
//
#if !defined(KRATOS_MOVE_PART_UTILITY_FLUID_ONLY_DIFF2_INCLUDED )
#define KRATOS_MOVE_PART_UTILITY_FLUID_ONLY_DIFF2_INCLUDED
// System includes
#include <string>
#include <iostream>
#include <algorithm>
// External includes
// Project includes
#include "includes/define.h"
#include "includes/node.h"
///
#include "includes/dof.h"
#include "includes/variables.h"
#include "containers/array_1d.h"
#include "containers/data_value_container.h"
#include "includes/mesh.h"
#include "utilities/math_utils.h"
#include "processes/node_erase_process.h"
///
#include "utilities/geometry_utilities.h"
#include "includes/model_part.h"
#include "spatial_containers/spatial_containers.h"
#include "spatial_containers/cell.h"
#include "spatial_containers/bins_dynamic_objects.h"
#include "utilities/spatial_containers_configure.h"
#include "geometries/line_2d_2.h"
#include "geometries/triangle_2d_3.h"
#include "geometries/triangle_3d_3.h"
#include "geometries/point.h"
#include "pfem_2_application_variables.h"
#include "utilities/openmp_utils.h"
#include "time.h"
//#include "processes/process.h"
namespace Kratos
{
//this class is to be modified by the user to customize the interpolation process
template< unsigned int TDim>
class MoveParticleUtilityDiffFluidOnly
{
public:
typedef SpatialContainersConfigure<TDim> Configure;
typedef typename Configure::PointType PointType;
//typedef PointType::CoordinatesArrayType CoordinatesArrayType;
typedef typename Configure::ContainerType ContainerType;
//typedef Configure::PointerType PointerType;
typedef typename Configure::IteratorType IteratorType;
typedef typename Configure::ResultContainerType ResultContainerType;
//typedef Configure::ResultPointerType ResultPointerType;
typedef typename Configure::ResultIteratorType ResultIteratorType;
//typedef Configure::ContactPairType ContactPairType;
//typedef Configure::ContainerContactType ContainerContactType;
//typedef Configure::IteratorContactType IteratorContactType;
//typedef Configure::PointerContactType PointerContactType;
//typedef Configure::PointerTypeIterator PointerTypeIterator;
KRATOS_CLASS_POINTER_DEFINITION(TransferUtility);
//template<unsigned int TDim>
TransferUtility(ModelPart& calculation_model_part, ModelPart& topographic_model_part)
: mcalculation_model_part(calculation_model_part) , mtopographic_model_part(topographic_model_part)
{
KRATOS_WATCH("initializing transfer utility")
ProcessInfo& CurrentProcessInfo = mcalculation_model_part.GetProcessInfo();
//loop in elements to change their ID to their position in the array. Easier to get information later.
//DO NOT PARALELIZE THIS! IT MUST BE SERIAL!!!!!!!!!!!!!!!!!!!!!!
/*
ModelPart::ElementsContainerType::iterator ielembegin = mcalculation_model_part.ElementsBegin();
for(unsigned int ii=0; ii<mr_model_part.Elements().size(); ii++)
{
ModelPart::ElementsContainerType::iterator ielem = ielembegin+ii;
ielem->SetId(ii+1);
}
mlast_elem_id= (mr_model_part.ElementsEnd()-1)->Id();
*/
//CONSTRUCTING BIN STRUCTURE
ContainerType& rElements = mtopographic_model_part.ElementsArray();
IteratorType it_begin = rElements.begin();
IteratorType it_end = rElements.end();
//const int number_of_elem = rElements.size();
typename BinsObjectDynamic<Configure>::Pointer paux = typename BinsObjectDynamic<Configure>::Pointer(new BinsObjectDynamic<Configure>(it_begin, it_end ) );
paux.swap(mpBinsObjectDynamic);
}
~TransferUtility()
{}
void GatherInformationFromTopographicDomain()
{
KRATOS_TRY
KRATOS_WATCH("Gathering Information From Topographic Domain ")
ProcessInfo& CurrentProcessInfo = mcalculation_model_part.GetProcessInfo();
double delta_t = CurrentProcessInfo[DELTA_TIME];
array_1d<double,3> & gravity= CurrentProcessInfo[GRAVITY];
const unsigned int max_results = 1000;
//array_1d<double,TDim+1> N;
//const int max_results = 1000;
ModelPart::NodesContainerType::iterator inodebegin = mcalculation_model_part.NodesBegin();
vector<unsigned int> node_partition;
#ifdef _OPENMP
int number_of_threads = omp_get_max_threads();
#else
int number_of_threads = 1;
#endif
OpenMPUtils::CreatePartition(number_of_threads, mcalculation_model_part.Nodes().size(), node_partition);
//before doing anything we must reset the vector of nodes contained by each element (particles that are inside each element.
#pragma omp parallel for
for(int kkk=0; kkk<number_of_threads; kkk++)
{
array_1d<double,TDim+1> N;
ResultContainerType results(max_results);
ResultIteratorType result_begin = results.begin();
for(unsigned int ii=node_partition[kkk]; ii<node_partition[kkk+1]; ii++)
{
if ( (results.size()) !=max_results)
results.resize(max_results);
//const int & elem_id = ielem->Id();
ModelPart::NodesContainerType::iterator inode = inodebegin+ii;
Element::Pointer pelement(*ielem.base());
Geometry<Node<3> >& geom = ielem->GetGeometry();
ParticlePointerVector& element_particle_pointers = (ielem->GetValue(FLUID_PARTICLE_POINTERS));
int & number_of_particles_in_elem=ielem->GetValue(NUMBER_OF_PARTICLES);
//std::cout << "elem " << ii << " with " << (unsigned int)number_of_particles_in_elem << " particles" << std::endl;
is_found = FindNodeOnMesh(position, N ,pelement,result_begin,MaxNumberOfResults); //good, now we know where this point is:
}
}
}
KRATOS_CATCH("")
}
protected:
private:
///this function should find the element into which a given node is located
///and return a pointer to the element and the vector containing the
///shape functions that define the postion within the element
///if "false" is devolved the element is not found
bool FindNodeOnMesh( //int last_element,
array_1d<double,3>& position,
array_1d<double,TDim+1>& N,
//Element::Pointer pelement,
Element::Pointer & pelement,
ResultIteratorType result_begin,
const unsigned int MaxNumberOfResults)
{
typedef std::size_t SizeType;
const array_1d<double,3>& coords = position;
array_1d<double,TDim+1> aux_N;
//before using the bin to search for possible elements we check first the last element in which the particle was.
//ModelPart::ElementsContainerType::iterator i = mr_model_part.ElementsBegin()+last_element;
Geometry<Node<3> >& geom_default = pelement->GetGeometry(); //(*(i))->GetGeometry();
bool is_found_1 = CalculatePosition(geom_default,coords[0],coords[1],coords[2],N);
if(is_found_1 == true)
{
//pelement = (*(i));
return true;
}
//KRATOS_WATCH("will look in another element")
//KRATOS_WATCH(TDim)
//to begin with we check the neighbour elements:
GlobalPointersVector< Element >& neighb_elems = pelement->GetValue(NEIGHBOUR_ELEMENTS);
//the first we check is the one that has negative shape function, because it means it went outside in this direction:
/*
unsigned int checked_element=0;
for (unsigned int i=0;i!=(TDim+1);i++)
{
if (N[i]<0.0)
{
checked_element=i;
Geometry<Node<3> >& geom = neighb_elems[i].GetGeometry();
bool is_found_2 = CalculatePosition(geom,coords[0],coords[1],coords[2],aux_N);
if (is_found_2)
{
pelement=Element::Pointer(((neighb_elems(i))));
N=aux_N;
return true;
}
break;
}
}
*/
for (unsigned int i=0;i!=(neighb_elems.size());i++)
{
Geometry<Node<3> >& geom = neighb_elems[i].GetGeometry();
bool is_found_2 = CalculatePosition(geom,coords[0],coords[1],coords[2],N);
if (is_found_2)
{
pelement=Element::Pointer(((neighb_elems(i))));
return true;
}
}
//ask to the container for the list of candidate elements
SizeType results_found = mpBinsObjectDynamic->SearchObjectsInCell(coords, result_begin, MaxNumberOfResults );
//KRATOS_WATCH(results_found)
if(results_found>0){
//loop over the candidate elements and check if the particle falls within
for(SizeType i = 0; i< results_found; i++)
{
//std::cout<< "KIIIIIIIIIIIIII" << std::endl;
//KRATOS_WATCH((*(result_begin+i))->Id());
Geometry<Node<3> >& geom = (*(result_begin+i))->GetGeometry();
//find local position
bool is_found = CalculatePosition(geom,coords[0],coords[1],coords[2],N);
//KRATOS_WATCH("ln243");
//KRATOS_WATCH(N);
if(is_found == true)
{
//pelement.clear();
//pelement.push_back( Element::WeakPointer((*(result_begin+i).base())));
pelement=Element::Pointer((*(result_begin+i).base()));
return true;
}
}
}
//not found case
return false;
}
//***************************************
//***************************************
inline bool CalculatePosition(Geometry<Node < 3 > >&geom,
const double xc, const double yc, const double zc,
array_1d<double, 3 > & N
)
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double area = CalculateVol(x0, y0, x1, y1, x2, y2);
double inv_area = 0.0;
if (area == 0.0)
{
KRATOS_THROW_ERROR(std::logic_error, "element with zero area found", "");
} else
{
inv_area = 1.0 / area;
}
N[0] = CalculateVol(x1, y1, x2, y2, xc, yc) * inv_area;
N[1] = CalculateVol(x2, y2, x0, y0, xc, yc) * inv_area;
N[2] = CalculateVol(x0, y0, x1, y1, xc, yc) * inv_area;
//KRATOS_WATCH(N);
if (N[0] >= 0.0 && N[1] >= 0.0 && N[2] >= 0.0 && N[0] <= 1.0 && N[1] <= 1.0 && N[2] <= 1.0) //if the xc yc is inside the triangle return true
return true;
return false;
}
//***************************************
//***************************************
inline bool CalculatePosition(Geometry<Node < 3 > >&geom,
const double xc, const double yc, const double zc,
array_1d<double, 4 > & N
)
{
double x0 = geom[0].X();
double y0 = geom[0].Y();
double z0 = geom[0].Z();
double x1 = geom[1].X();
double y1 = geom[1].Y();
double z1 = geom[1].Z();
double x2 = geom[2].X();
double y2 = geom[2].Y();
double z2 = geom[2].Z();
double x3 = geom[3].X();
double y3 = geom[3].Y();
double z3 = geom[3].Z();
double vol = CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3);
double inv_vol = 0.0;
if (vol < 0.0000000000001)
{
KRATOS_THROW_ERROR(std::logic_error, "element with zero vol found", "");
} else
{
inv_vol = 1.0 / vol;
}
N[0] = CalculateVol(x1, y1, z1, x3, y3, z3, x2, y2, z2, xc, yc, zc) * inv_vol;
N[1] = CalculateVol(x0, y0, z0, x1, y1, z1, x2, y2, z2, xc, yc, zc) * inv_vol;
N[2] = CalculateVol(x3, y3, z3, x1, y1, z1, x0, y0, z0, xc, yc, zc) * inv_vol;
N[3] = CalculateVol(x3, y3, z3, x0, y0, z0, x2, y2, z2, xc, yc, zc) * inv_vol;
if (N[0] >= 0.0 && N[1] >= 0.0 && N[2] >= 0.0 && N[3] >= 0.0 &&
N[0] <= 1.0 && N[1] <= 1.0 && N[2] <= 1.0 && N[3] <= 1.0)
//if the xc yc zc is inside the tetrahedron return true
return true;
return false;
}
inline double CalculateVol(const double x0, const double y0,
const double x1, const double y1,
const double x2, const double y2
)
{
return 0.5 * ((x1 - x0)*(y2 - y0)- (y1 - y0)*(x2 - x0));
}
//***************************************
//***************************************
inline double CalculateVol(const double x0, const double y0, const double z0,
const double x1, const double y1, const double z1,
const double x2, const double y2, const double z2,
const double x3, const double y3, const double z3
)
{
double x10 = x1 - x0;
double y10 = y1 - y0;
double z10 = z1 - z0;
double x20 = x2 - x0;
double y20 = y2 - y0;
double z20 = z2 - z0;
double x30 = x3 - x0;
double y30 = y3 - y0;
double z30 = z3 - z0;
double detJ = x10 * y20 * z30 - x10 * y30 * z20 + y10 * z20 * x30 - y10 * x20 * z30 + z10 * x20 * y30 - z10 * y20 * x30;
return detJ * 0.1666666666666666666667;
}
ModelPart& mcalculation_model_part;
ModelPart& mtopographic_model_part;
typename BinsObjectDynamic<Configure>::Pointer mpBinsObjectDynamic;
};
} // namespace Kratos.
#endif // KRATOS_MOVE_PART_UTILITY_DIFF2_INCLUDED defined
|
cgeswp.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zgeswp.c, normal z -> c, Fri Sep 28 17:38:06 2018
*
**/
#include "plasma.h"
#include "plasma_async.h"
#include "plasma_context.h"
#include "plasma_descriptor.h"
#include "plasma_internal.h"
#include "plasma_tuning.h"
#include "plasma_types.h"
/******************************************************************************/
int plasma_cgeswp(plasma_enum_t colrow,
int m, int n,
plasma_complex32_t *pA, int lda, int *ipiv, int incx)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
return PlasmaErrorNotInitialized;
}
// Check input arguments.
if ((colrow != PlasmaColumnwise) &&
(colrow != PlasmaRowwise)) {
plasma_error("illegal value of colrow");
return -1;
}
if (m < 0) {
plasma_error("illegal value of m");
return -2;
}
if (n < 0) {
plasma_error("illegal value of n");
return -3;
}
if (lda < imax(1, m)) {
plasma_error("illegal value of lda");
return -5;
}
// quick return
if (imin(n, m) == 0)
return PlasmaSuccess;
// Tune parameters.
if (plasma->tuning)
plasma_tune_geswp(plasma, PlasmaComplexFloat, m, n);
// Set tiling parameters.
int nb = plasma->nb;
// Create tile matrices.
plasma_desc_t A;
int retval;
retval = plasma_desc_general_create(PlasmaComplexFloat, nb, nb,
m, n, 0, 0, m, n, &A);
if (retval != PlasmaSuccess) {
plasma_error("plasma_general_desc_create() failed");
return retval;
}
// Initialize sequence.
plasma_sequence_t sequence;
retval = plasma_sequence_init(&sequence);
// Initialize request.
plasma_request_t request;
retval = plasma_request_init(&request);
// asynchronous block
#pragma omp parallel
#pragma omp master
{
// Translate to tile layout.
plasma_omp_cge2desc(pA, lda, A, &sequence, &request);
// Call tile async function.
plasma_omp_cgeswp(colrow, A, ipiv, incx, &sequence, &request);
// Translate back to LAPACK layout.
plasma_omp_cdesc2ge(A, pA, lda, &sequence, &request);
}
// implicit synchronization
// Free matrices in tile layout.
plasma_desc_destroy(&A);
// Return status.
int status = sequence.status;
return status;
}
/******************************************************************************/
void plasma_omp_cgeswp(plasma_enum_t colrow,
plasma_desc_t A, int *ipiv, int incx,
plasma_sequence_t *sequence, plasma_request_t *request)
{
// Get PLASMA context.
plasma_context_t *plasma = plasma_context_self();
if (plasma == NULL) {
plasma_error("PLASMA not initialized");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// Check input arguments.
if ((colrow != PlasmaColumnwise) &&
(colrow != PlasmaRowwise)) {
plasma_error("illegal value of colrow");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (plasma_desc_check(A) != PlasmaSuccess) {
plasma_error("invalid A");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (sequence == NULL) {
plasma_error("NULL sequence");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
if (request == NULL) {
plasma_error("NULL request");
plasma_request_fail(sequence, request, PlasmaErrorIllegalValue);
return;
}
// quick return
if (imin(A.m, A.n) == 0)
return;
// Call the parallel function.
plasma_pcgeswp(colrow, A, ipiv, incx, sequence, request);
}
|
GB_subassign_14.c | //------------------------------------------------------------------------------
// GB_subassign_14: C(I,J)<!M> = A ; using S
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// Method 14: C(I,J)<!M> = A ; using S
// M: present
// Mask_comp: true
// C_replace: false
// accum: NULL
// A: matrix
// S: constructed
#define GB_FREE_WORK GB_FREE_TWO_SLICE
#include "GB_subassign_methods.h"
GrB_Info GB_subassign_14
(
GrB_Matrix C,
// input:
const GrB_Index *I,
const int64_t nI,
const int Ikind,
const int64_t Icolon [3],
const GrB_Index *J,
const int64_t nJ,
const int Jkind,
const int64_t Jcolon [3],
const GrB_Matrix M,
const GrB_Matrix A,
const GrB_Matrix S,
GB_Context Context
)
{
//--------------------------------------------------------------------------
// get inputs
//--------------------------------------------------------------------------
GB_GET_C ;
GB_GET_MASK ;
const bool M_is_hyper = M->is_hyper ;
const int64_t Mnvec = M->nvec ;
GB_GET_A ;
GB_GET_S ;
GrB_BinaryOp accum = NULL ;
//--------------------------------------------------------------------------
// Method 14: C(I,J)<!M> = A ; using S
//--------------------------------------------------------------------------
// Time: Close to optimal. Omega(nnz(S)+nnz(A)) is required, and the
// sparsity of !M cannot be exploited. The time taken is
// O((nnz(A)+nnz(S))*log(m)) where m is the # of entries in a vector of M.
// Method 06s and 14 are very similar.
//--------------------------------------------------------------------------
// Parallel: Z=A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20)
//--------------------------------------------------------------------------
GB_SUBASSIGN_TWO_SLICE (A, S) ;
//--------------------------------------------------------------------------
// phase 1: create zombies, update entries, and count pending tuples
//--------------------------------------------------------------------------
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(+:nzombies)
for (int taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE1 ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get A(:,j) and S(:,j)
//------------------------------------------------------------------
int64_t j = (Zh == NULL) ? k : Zh [k] ;
GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ;
GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ;
//------------------------------------------------------------------
// get M(:,j)
//------------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
//------------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//------------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
// int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = Si [pS] ;
int64_t iA = Ai [pA] ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
GB_MIJ_BINARY_SEARCH (iS) ;
mij = !mij ;
if (mij)
{
// ----[C . 1] or [X . 1]-------------------------------
// [C . 1]: action: ( delete ): becomes zombie
// [X . 1]: action: ( X ): still zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH (iA) ;
mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_MIJ_BINARY_SEARCH (iA) ;
mij = !mij ;
if (mij)
{
// ----[C A 1] or [X A 1]-------------------------------
// [C A 1]: action: ( =A ): A to C no accum
// [X A 1]: action: ( undelete ): zombie lives
GB_C_S_LOOKUP ;
GB_noaccum_C_A_1_matrix ;
}
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// while list S (:,j) has entries. List A (:,j) exhausted
while (pS < pS_end)
{
// S (i,j) is present but A (i,j) is not
int64_t iS = Si [pS] ;
GB_MIJ_BINARY_SEARCH (iS) ;
mij = !mij ;
if (mij)
{
// ----[C . 1] or [X . 1]-----------------------------------
// [C . 1]: action: ( delete ): becomes zombie
// [X . 1]: action: ( X ): still zombie
GB_C_S_LOOKUP ;
GB_DELETE_ENTRY ;
}
GB_NEXT (S) ;
}
// while list A (:,j) has entries. List S (:,j) exhausted
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = Ai [pA] ;
GB_MIJ_BINARY_SEARCH (iA) ;
mij = !mij ;
if (mij)
{
// ----[. A 1]----------------------------------------------
// [. A 1]: action: ( insert )
task_pending++ ;
}
GB_NEXT (A) ;
}
}
GB_PHASE1_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// phase 2: insert pending tuples
//--------------------------------------------------------------------------
GB_PENDING_CUMSUM ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(&&:pending_sorted)
for (int taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
GB_GET_TASK_DESCRIPTOR_PHASE2 ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get A(:,j) and S(:,j)
//------------------------------------------------------------------
int64_t j = (Zh == NULL) ? k : Zh [k] ;
GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ;
GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ;
//------------------------------------------------------------------
// get M(:,j)
//------------------------------------------------------------------
int64_t pM_start, pM_end ;
GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ;
//------------------------------------------------------------------
// do a 2-way merge of S(:,j) and A(:,j)
//------------------------------------------------------------------
// jC = J [j] ; or J is a colon expression
int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ;
// while both list S (:,j) and A (:,j) have entries
while (pS < pS_end && pA < pA_end)
{
int64_t iS = Si [pS] ;
int64_t iA = Ai [pA] ;
if (iS < iA)
{
// S (i,j) is present but A (i,j) is not
GB_NEXT (S) ;
}
else if (iA < iS)
{
// S (i,j) is not present, A (i,j) is present
GB_MIJ_BINARY_SEARCH (iA) ;
mij = !mij ;
if (mij)
{
// ----[. A 1]------------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
}
GB_NEXT (A) ;
}
else
{
// both S (i,j) and A (i,j) present
GB_NEXT (S) ;
GB_NEXT (A) ;
}
}
// while list A (:,j) has entries. List S (:,j) exhausted
while (pA < pA_end)
{
// S (i,j) is not present, A (i,j) is present
int64_t iA = Ai [pA] ;
GB_MIJ_BINARY_SEARCH (iA) ;
mij = !mij ;
if (mij)
{
// ----[. A 1]----------------------------------------------
// [. A 1]: action: ( insert )
int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ;
GB_PENDING_INSERT (Ax +(pA*asize)) ;
}
GB_NEXT (A) ;
}
}
GB_PHASE2_TASK_WRAPUP ;
}
//--------------------------------------------------------------------------
// finalize the matrix and return result
//--------------------------------------------------------------------------
GB_SUBASSIGN_WRAPUP ;
}
|
GB_binop__isge_fp64.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__isge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_08__isge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_02__isge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_04__isge_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_fp64)
// A*D function (colscale): GB (_AxD__isge_fp64)
// D*A function (rowscale): GB (_DxB__isge_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__isge_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__isge_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_fp64)
// C=scalar+B GB (_bind1st__isge_fp64)
// C=scalar+B' GB (_bind1st_tran__isge_fp64)
// C=A+scalar GB (_bind2nd__isge_fp64)
// C=A'+scalar GB (_bind2nd_tran__isge_fp64)
// C type: double
// A type: double
// A pattern? 0
// B type: double
// B pattern? 0
// BinaryOp: cij = (aij >= bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// 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) \
double 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) \
double 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) \
double 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_ISGE || GxB_NO_FP64 || GxB_NO_ISGE_FP64)
//------------------------------------------------------------------------------
// 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__isge_fp64)
(
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__isge_fp64)
(
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__isge_fp64)
(
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 double
double bwork = (*((double *) 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__isge_fp64)
(
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
double *restrict Cx = (double *) 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__isge_fp64)
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) 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__isge_fp64)
(
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) ;
double alpha_scalar ;
double beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((double *) alpha_scalar_in)) ;
beta_scalar = (*((double *) 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__isge_fp64)
(
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__isge_fp64)
(
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__isge_fp64)
(
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__isge_fp64)
(
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__isge_fp64)
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
double 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__isge_fp64)
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x >= aij) ; \
}
GrB_Info GB (_bind1st_tran__isge_fp64)
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// 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) \
{ \
double aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij >= y) ; \
}
GrB_Info GB (_bind2nd_tran__isge_fp64)
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
jacobi-block-for.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
}
# include "poisson.h"
/* #pragma omp task/taskwait version of SWEEP. */
void sweep (int nx, int ny, double dx, double dy, double *f_,
int itold, int itnew, double *u_, double *unew_, int block_size)
{
int it;
int block_x, block_y;
if (block_size == 0)
block_size = nx;
int max_blocks_x = (nx / block_size);
int max_blocks_y = (ny / block_size);
for (it = itold + 1; it <= itnew; it++)
{
// Save the current estimate.
{ const unsigned long long parallel_for_start = current_time_ns();
#pragma omp parallel for shared(u_, unew_, f_, max_blocks_x, max_blocks_y, nx, ny, dx, dy, itold, itnew, block_size) private(it, block_x, block_y) collapse(2)
for (block_x = 0; block_x < max_blocks_x; block_x++)
for (block_y = 0; block_y < max_blocks_y; block_y++)
copy_block(nx, ny, block_x, block_y, u_, unew_, block_size) ;
const unsigned long long parallel_for_end = current_time_ns();
printf("pragma21_omp_parallel %llu ns\n", parallel_for_end - parallel_for_start); }
;
{ const unsigned long long parallel_for_start = current_time_ns();
#pragma omp parallel for shared(u_, unew_, f_, max_blocks_x, max_blocks_y, nx, ny, dx, dy, itold, itnew, block_size) private(it, block_x, block_y) collapse(2)
for (block_x = 0; block_x < max_blocks_x; block_x++)
for (block_y = 0; block_y < max_blocks_y; block_y++)
compute_estimate(block_x, block_y, u_, unew_, f_, dx, dy,
nx, ny, block_size) ;
const unsigned long long parallel_for_end = current_time_ns();
printf("pragma28_omp_parallel %llu ns\n", parallel_for_end - parallel_for_start); }
;
}
}
|
noble_1962.c | #include "noble_1962.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Original: -87,0.01,0.8,0.01
// Mestrado Lucas: -75.5344986658,0.0605467272,0.7259001355,0.4709239708
// 500ms pacing steady state: -76.1302f, 0.0586201f, 0.741082f, 0.475923f
// 450ms pacing steady-state: -78.8607f, 0.050476f, 0.806294f, 0.518928f
sv[0] = -75.5344986658f; // V millivolt
sv[1] = 0.0605467272f; // m dimensionless
sv[2] = 0.7259001355f; // h dimensionless
sv[3] = 0.4709239708f; // n dimensionless
}
SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) {
uint32_t sv_id;
int i;
#pragma omp parallel for private(sv_id)
for (i = 0; i < num_cells_to_solve; i++)
{
if(cells_to_solve)
sv_id = cells_to_solve[i];
else
sv_id = i;
for (int j = 0; j < num_steps; ++j) {
solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]);
}
}
}
void solve_model_ode_cpu(real dt, real *sv, real stim_current) {
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(dt, rY, rDY, stim_current);
// Explicit Euler
for(int i = 0; i < NEQ; i++)
sv[i] = dt*rDY[i] + rY[i];
}
void RHS_cpu(const real dt, const real *sv, real *rDY_, real stim_current) {
//State variables
const real V_old_ = sv[0];
const real m_old_ = sv[1];
const real h_old_ = sv[2];
const real n_old_ = sv[3];
//___________________________________________________________________________
//Parameters (miliseconds)
const real Cm = 12.0f; // (microF)
const real g_na_max = 400.0f; // (microS)
const real E_na = 40.0f; // (millivolt)
const real g_L = 0.075f; // (microS)
const real E_L = -60.0f; // (millivolt)
real calc_I_stim = stim_current;
// Algebraics
real g_na = pow(m_old_, 3.00000)*h_old_*g_na_max;
real alpha_m = (((1.0e-01*((-V_old_)-4.8e+01))/(exp((((-V_old_)-4.8e+01)/1.5e+01))-1.0e+00)));
real alpha_h = ((1.7e-01*exp((((-V_old_)-9.0e+01)/2.0e+01))));
real alpha_n = (((1.0e-04*((-V_old_)-5.0e+01))/(exp((((-V_old_)-5.0e+01)/1.0e+01))-1.0e+00)));
real i_na = (g_na+1.4e-01)*(V_old_ - E_na);
//real i_na_no_oscilation = (g_na+122.500)*(V_old_ - E_na);
real beta_m = (((1.2e-01*(V_old_+8.0e+00))/(exp(((V_old_+8.0e+00)/5.0e+00))-1.0e+00)));
real beta_h = ((1.0/(1.0e+00+exp((((-V_old_)-4.2e+01)/1.0e+01)))));
real beta_n = ((2.0e-03*exp((((-V_old_)-9.0e+01)/8.0e+01))));
//real g_K1 = 1.3f*exp((- V_old_ - 90.0000)/50.0000)+ 0.015f*exp((V_old_+90.0000)/60.0000);
real g_K1 = (((1.2*exp((((-V_old_)-9.0e+01)/5.0e+01)))+(1.5e-02*exp(((V_old_+9.0e+01)/6.0e+01)))));
real g_K2 = 1.2f*pow(n_old_, 4.00000);
real i_k = (g_K1+g_K2)*(V_old_+100.000);
real i_leak = g_L*(V_old_ - E_L);
// Rates
rDY_[0] = ( - (i_na + i_k + i_leak + calc_I_stim)) / Cm;
//rDY_[0] = (- (i_na_no_oscilation + i_k + i_leak + calc_I_stim)/Cm) * 1.0E-03;
// Rush-Larsen
//real m_inf = alpha_m / (alpha_m + beta_m);
//real tau_m = 1.0 / (alpha_m + beta_m);
//rDY_[1] = m_inf + ((m_old_ - m_inf)*exp(-dt/tau_m));
//real h_inf = alpha_h / (alpha_h + beta_h);
//real tau_h = 1.0 / (alpha_h + beta_h);
//rDY_[2] = h_inf + ((h_old_ - h_inf)*exp(-dt/tau_h));
//real n_inf = alpha_n / (alpha_n + beta_n);
//real tau_n = 1.0 / (alpha_n + beta_n);
//rDY_[3] = n_inf + ((n_old_ - n_inf)*exp(-dt/tau_n));
// Old Euler code ...
rDY_[1] = (alpha_m*(1.00000 - m_old_) - (beta_m*m_old_) );
rDY_[2] = (alpha_h*(1.00000 - h_old_) - (beta_h*h_old_) );
rDY_[3] = (alpha_n*(1.00000 - n_old_) - (beta_n*n_old_) );
} |
original.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "3mm.h"
/* Array initialization. */
static
void init_array(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nk; j++)
A[i][j] = ((DATA_TYPE) i*j) / ni;
for (i = 0; i < nk; i++)
for (j = 0; j < nj; j++)
B[i][j] = ((DATA_TYPE) i*(j+1)) / nj;
for (i = 0; i < nj; i++)
for (j = 0; j < nm; j++)
C[i][j] = ((DATA_TYPE) i*(j+3)) / nl;
for (i = 0; i < nm; i++)
for (j = 0; j < nl; j++)
D[i][j] = ((DATA_TYPE) i*(j+2)) / nk;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nl,
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nl; j++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, G[i][j]);
if ((i * ni + j) % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_3mm(int ni, int nj, int nk, int nl, int nm,
DATA_TYPE POLYBENCH_2D(E,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(A,NI,NK,ni,nk),
DATA_TYPE POLYBENCH_2D(B,NK,NJ,nk,nj),
DATA_TYPE POLYBENCH_2D(F,NJ,NL,nj,nl),
DATA_TYPE POLYBENCH_2D(C,NJ,NM,nj,nm),
DATA_TYPE POLYBENCH_2D(D,NM,NL,nm,nl),
DATA_TYPE POLYBENCH_2D(G,NI,NL,ni,nl))
{
int i, j, k;
#pragma scop
#pragma omp parallel private (j, k)
{
/* E := A*B */
#pragma omp for
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NJ; j++)
{
E[i][j] = 0;
for (k = 0; k < _PB_NK; ++k)
E[i][j] += A[i][k] * B[k][j];
}
/* F := C*D */
#pragma omp for
for (i = 0; i < _PB_NJ; i++)
for (j = 0; j < _PB_NL; j++)
{
F[i][j] = 0;
for (k = 0; k < _PB_NM; ++k)
F[i][j] += C[i][k] * D[k][j];
}
/* G := E*F */
#pragma omp for
for (i = 0; i < _PB_NI; i++)
for (j = 0; j < _PB_NL; j++)
{
G[i][j] = 0;
for (k = 0; k < _PB_NJ; ++k)
G[i][j] += E[i][k] * F[k][j];
}
}
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
int nk = NK;
int nl = NL;
int nm = NM;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(E, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NK, ni, nk);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NK, NJ, nk, nj);
POLYBENCH_2D_ARRAY_DECL(F, DATA_TYPE, NJ, NL, nj, nl);
POLYBENCH_2D_ARRAY_DECL(C, DATA_TYPE, NJ, NM, nj, nm);
POLYBENCH_2D_ARRAY_DECL(D, DATA_TYPE, NM, NL, nm, nl);
POLYBENCH_2D_ARRAY_DECL(G, DATA_TYPE, NI, NL, ni, nl);
/* Initialize array(s). */
init_array (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_3mm (ni, nj, nk, nl, nm,
POLYBENCH_ARRAY(E),
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(B),
POLYBENCH_ARRAY(F),
POLYBENCH_ARRAY(C),
POLYBENCH_ARRAY(D),
POLYBENCH_ARRAY(G));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nl, POLYBENCH_ARRAY(G)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(E);
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
POLYBENCH_FREE_ARRAY(F);
POLYBENCH_FREE_ARRAY(C);
POLYBENCH_FREE_ARRAY(D);
POLYBENCH_FREE_ARRAY(G);
return 0;
}
|
11_soma_vetor.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
void inicializa(int **v, int size) {
(*v) = (int *) malloc(sizeof(int) * size);
for (int i = 0; i < size; i++) {
(*v)[i] = 1;
}
}
int main(int argc, char **argv) {
int *vetor;
int size = 1000000;
inicializa(&vetor, size);
unsigned long acc = 0;
//#pragma omp parallel for
for (int i = 0; i < size; i++) {
acc += vetor[i];
}
printf("Resultado: %lu\n", acc);
return 0;
}
|
st_up.c | #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include "mypng.h"
/**
* A transform finding the gradient of the steepest upwards tangent at each pixel.
* <p>
* CODER WARNING: Many of the internal methods use the square of the slope.
*/
double* inGrey ;
int fullWidth ;
int fullHeight ;
double** mins ;
double** maxs ;
int* widths ;
int* heights ;
int* quadLengths ;
int layerCount ;
double getPixel(double* pixels, int x, int y, int width) {
return pixels[x+y*width] ;
}
void setPixel(double* pixels, int x, int y, double value, int width) {
pixels[x+y*width] = value ;
}
double searchWholeQuad(int inX, int inY, double inValue, int quadX, int quadY, int depth, double steepestYet);
/**
* Returns the least possible distance (along one axis) from a pixel in the finest-grained image to any pixel in the given quad.
* @param inCoord Coordinate of source pixel in finest-grained image.
* @param otherLayerCoord Coordinate of other 'pixel' in the layer-image.
*/
int minCoordDistance(int inCoord, int otherLayerCoord, int quadLength) {
/* Note: we can never be to the right of a truncated-width quad. */
int otherFinestLowCoord = otherLayerCoord * quadLength ;
int otherFinestHighCoord = otherFinestLowCoord + quadLength - 1 ; // Inside the quad, not immediately-after.
if (inCoord<otherFinestLowCoord) return otherFinestLowCoord - inCoord ;
if (inCoord>otherFinestHighCoord) return inCoord - otherFinestHighCoord ;
return 0 ;
}
double computeSteepestPossibleSlopeToOther(int inX, int inY, double inValue, int quadX, int quadY, int depth, int quadLength) {
int layerWidth = widths[depth] ;
int minDistanceX = minCoordDistance(inX, quadX, quadLength);
int minDistanceY = minCoordDistance(inY, quadY, quadLength);
int minDistanceSqr = minDistanceX*minDistanceX+minDistanceY*minDistanceY;
double maxQuadValue = getPixel(maxs[depth], quadX, quadY, layerWidth);
double valueDiff = maxQuadValue-inValue;
double steepestPossibleSlopeSqr = valueDiff*fabs(valueDiff) / minDistanceSqr ;
return steepestPossibleSlopeSqr ;
}
/**
* Returns the delta to the sibling quad along this axis.
* <p>
* Each quad has three siblings in the one-coarser quad.
* This method returns <code>-1</code> or <code>1</code>, according to whether the neighbour along this axis is to the right or left of this <code>coord</code>.
* If there is no neighbour (ie, we're in a truncated quad), <code>zero</code> is returned.
*/
int getDeltaCoord(int coord, int layerLength) {
int/*boolean*/ isOdd = (coord%2) == 1 ;
if (isOdd) {
/* Here we know: we are in the right half of the quad. */
return -1 ;
} else {
/* Here we know: we are in the left half of the quad. */
if (coord==layerLength-1) {
/* Here we know: this is the last coordinate. There is no sibling along this axis. */
return 0 ;
} else {
return 1 ;
}
}
}
/**
* Returns the coordinate the quad in the next coarser layer, that holds this coordinate in this layer.
*/
int toCoarserCoord(int coord) {
return coord / 2 ;
}
int imin(int i, int j) {
if (i<j) return i ; else return j ;
}
int toCoarserLength(int length) {
return (length+1)/2;
}
int getQuadDepth_n(int length) {
if (length==1) return 1 ; else return getQuadDepth_n(toCoarserLength(length)) + 1 ;
}
int getQuadDepth(int fullWidth, int fullHeight) {
return getQuadDepth_n(imin(fullWidth, fullHeight));
}
double* makeDoubles(int width, int height) {
return (double*)calloc(width*height, sizeof(double)) ;
}
/**
* Fills the quad image, and related fields, for the given depth.
* <p>
* This is an initialization method.
*/
void fillQuadDepth(int targetDepth) {
int sourceDepth = targetDepth - 1 ;
double* sourceMins = mins[sourceDepth] ;
double* sourceMaxs = maxs[sourceDepth] ;
int sourceWidth = widths[sourceDepth] ;
int sourceHeight = heights[sourceDepth] ;
int sourceLength = quadLengths[sourceDepth] ;
int targetWidth = toCoarserLength(sourceWidth) ;
int targetHeight = toCoarserLength(sourceHeight) ;
int targetLength = 2 * sourceLength ;
double* targetMins = makeDoubles(targetWidth, targetHeight);
double* targetMaxs = makeDoubles(targetWidth, targetHeight);
mins[targetDepth] = targetMins ;
maxs[targetDepth] = targetMaxs ;
widths[targetDepth] = targetWidth ;
heights[targetDepth] = targetHeight ;
quadLengths[targetDepth] = targetLength ;
/************* OMP ***************/
#pragma omp parallel for collapse(2)
for (int targetY=0 ; targetY<targetHeight ; targetY++) {
for (int targetX=0 ; targetX<targetWidth ; targetX++) {
int sourceYStart = targetY * 2 ;
int sourceYFinish = fmin(sourceYStart+sourceLength+1, sourceHeight);
// TODO We're extracting min & max from 2x2, 2x1 or 1x1 squares here. It could be more efficient!
int sourceXStart = targetX * 2 ;
int sourceXFinish = fmin(sourceXStart+sourceLength+1, sourceWidth);
double quadMin = getPixel(sourceMins, sourceXStart, sourceYStart, sourceWidth); // ->pixels[sourceYStart][sourceXStart] ;
double quadMax = getPixel(sourceMaxs, sourceXStart, sourceYStart, sourceWidth); // ->pixels[sourceYStart][sourceXStart] ;
for (int sourceY=sourceYStart ; sourceY<sourceYFinish ; sourceY++) {
for (int sourceX=sourceXStart ; sourceX<sourceXFinish ; sourceX++) {
quadMin = fmin(quadMin, getPixel(sourceMins, sourceX, sourceY, sourceWidth)) ;
quadMax = fmax(quadMax, getPixel(sourceMaxs, sourceX, sourceY, sourceWidth)) ;
}
}
setPixel(targetMins, targetX, targetY, quadMin, targetWidth);
setPixel(targetMaxs, targetX, targetY, quadMax, targetWidth);
}
}
}
/**
* Searches a sibling quad for the steepest slope.
* <p>
* <em>Assumes</em>: The pixel <code>inX,inY</code> is in the finest-grain image (ie, <code>inGrey</code>),
* and the quad <code>baseQuadX,baseQuadY</code> at layer <code>depth</code> contains that pixel.
*
* @param deltaX X-delta to a sibling quad.
* @param deltaY Y-delta to a sibling quad.
* @return The steepest slope found within the sibling quad, or <code>steepestYet</code>, which ever is steeper.
*/
double searchSibling(int inX, int inY, double inValue, int baseQuadX, int baseQuadY, int depth, int quadLength, int deltaX, int deltaY, double steepestYet) {
int quadX = baseQuadX + deltaX ;
int quadY = baseQuadY + deltaY ;
double steepestPossibleSlope = computeSteepestPossibleSlopeToOther(inX, inY, inValue, quadX, quadY, depth, quadLength);
if (steepestPossibleSlope>steepestYet) {
steepestYet = searchWholeQuad(inX, inY, inValue, quadX, quadY, depth, steepestYet);
}
return steepestYet ;
}
/**
* Recursively searches for the (square of) steepest slope from pixel <code>inX,inY</code> to any other pixel.
* The arguments specify a quad that has already been searched.
* This method will search the three sibling quads at this level, then search the coarser levels.
*
* @param inX x-coordinate of source pixel in the finest-grained image (ie, the <code>inGrey</code> image).
* @param inY y-coordinate of source pixel in the finest-grained image (ie, the <code>inGrey</code> image).
* @param inValue the pixel value of the source pixel.
* @param layerX x-coordinate of quad that has been explored so far. It should contain the fine-grain pixel <code>inX,inY</code>.
* @param layerY y-coordinate of quad that has been explored so far. It should contain the fine-grain pixel <code>inX,inY</code>.
* @param depth depth of quad that has been explored so far.
* @param steepestYet
* @return
*/
double searchSiblingAndCoarserQuads(int inX, int inY, double inValue, int layerX, int layerY, int depth, double steepestYet) {
if (depth==layerCount) return steepestYet ;
int layerWidth = widths[depth] ;
int layerHeight = heights[depth] ;
int quadLength = quadLengths[depth] ;
int deltaX = getDeltaCoord(layerX, layerWidth);
int deltaY = getDeltaCoord(layerY, layerHeight);
////// Explore the three sibling quads at this level.
if (deltaX!=0) {
if (deltaY!=0) {
steepestYet = fmax(steepestYet, searchSibling(inX, inY, inValue, layerX, layerY, depth, quadLength, 0, deltaY, steepestYet));
steepestYet = fmax(steepestYet, searchSibling(inX, inY, inValue, layerX, layerY, depth, quadLength, deltaX, 0, steepestYet));
steepestYet = fmax(steepestYet, searchSibling(inX, inY, inValue, layerX, layerY, depth, quadLength, deltaX, deltaY, steepestYet));
} else {
steepestYet = fmax(steepestYet, searchSibling(inX, inY, inValue, layerX, layerY, depth, quadLength, deltaX, 0, steepestYet));
}
} else {
if (deltaY!=0) {
steepestYet = fmax(steepestYet, searchSibling(inX, inY, inValue, layerX, layerY, depth, quadLength, 0, deltaY, steepestYet));
} else {
// Nothing required.
}
}
/* Here we know: The quad at the next coarsest layer, that contains this pixel, has been fully searched. */
////// Explore the coarser levels.
steepestYet = searchSiblingAndCoarserQuads(inX, inY, inValue, toCoarserCoord(layerX), toCoarserCoord(layerY), depth+1, steepestYet);
/* Here we know: The entire image has been searched. */
////// Bye bye
return steepestYet ;
}
/**
* Searches all pixels in a quad for a steep slope to the finest-grain pixel <code>inX,inY</code>.
* The pixel <code>inX,inY</code> must be outside the quad.
*
* @return The steepest slope (squared) found within the quad, or <code>steepestYet</code>, which ever is steeper.
*/
double searchWholeQuad(int inX, int inY, double inValue, int quadX, int quadY, int depth, double steepestYet) {
//double* minValues = mins[depth] ;
if (depth>0) {
/* Here we know: We're checking a summary-layer image. */
int quadLength = quadLengths[depth];
////// Check quad as a whole
double steepestPossibleWholeQuad = computeSteepestPossibleSlopeToOther(inX, inY, inValue, quadX, quadY, depth, quadLength);
if (steepestYet>steepestPossibleWholeQuad) return steepestYet ;
////// Check sub-quads
int fineDepth = depth - 1 ;
int fineWidth = widths[fineDepth];
int fineHeight = heights[fineDepth];
int fineX0 = quadX * 2 ;
int fineY0 = quadY * 2 ;
/* Implementation note: the code would run faster if the quads nearest inX,inY were searched first.
However, the code is clearer as it is below. */
if (fineX0+1<fineWidth) {
if (fineY0+1<fineHeight) {
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0, fineDepth, steepestYet);
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0+1, fineY0, fineDepth, steepestYet);
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0+1, fineDepth, steepestYet);
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0+1, fineY0+1, fineDepth, steepestYet);
} else {
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0, fineDepth, steepestYet);
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0+1, fineY0, fineDepth, steepestYet);
}
} else {
if (fineY0+1<fineHeight) {
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0, fineDepth, steepestYet);
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0+1, fineDepth, steepestYet);
} else {
steepestYet = searchWholeQuad(inX, inY, inValue, fineX0, fineY0, fineDepth, steepestYet);
}
}
return steepestYet ;
} else {
/* Here we know: We've reached the finest-grained image, ie, the inGrey image. */
int distanceX = inX - quadX ; // Might be negative
int distanceY = inY - quadY ; // Might be negative
double distanceSqr = distanceX*distanceX + distanceY*distanceY ;
double otherValue = getPixel(inGrey, quadX, quadY, fullWidth);
double valueDiff = otherValue - inValue;
double slopeSqr = valueDiff*fabs(valueDiff) / distanceSqr ;
return fmax(steepestYet, slopeSqr);
}
}
double computeNaiveSqrSlope(int x, int y) {
double maxSqrSlope = 0 ;
double value = getPixel(inGrey, x, y, fullWidth);
for (int y1=0 ; y1<fullHeight ; y1++) {
for (int x1=0 ; x1<fullWidth ; x1++) {
double value1 = getPixel(inGrey, x1, y1, fullWidth);
double valueDiff = value1 - value ;
if (valueDiff<=0) continue ;
double sqrDist = (y1-y)*(y1-y) + (x1-x)*(x1-x) ;
double sqrSlope = valueDiff * valueDiff / sqrDist ;
if (sqrSlope > maxSqrSlope) maxSqrSlope = sqrSlope ;
}
}
return maxSqrSlope ;
}
double* runSteepestTangent(double* inGrey_arg, int width, int height) {
inGrey = inGrey_arg ;
fullWidth = width ;
fullHeight = height ;
double* slopes = makeDoubles(fullWidth, fullHeight);
////// Compute quad images
layerCount = getQuadDepth(fullWidth, fullHeight);
mins = (double**)calloc(layerCount, sizeof(double*));
maxs = (double**)calloc(layerCount, sizeof(double*));
widths = (int*)calloc(layerCount, sizeof(int));
heights = (int*)calloc(layerCount, sizeof(int));
quadLengths = (int*)calloc(layerCount, sizeof(int));
mins[0] = inGrey_arg ;
maxs[0] = inGrey_arg ;
widths[0] = fullWidth ;
heights[0] = fullHeight ;
quadLengths[0] = 1 ;
for (int depth=1 ; depth<layerCount ; depth++) {
fillQuadDepth(depth); /* OMP speedup is put inside this function */
}
/* Here we know: The 'mins' and 'maxs' quad images are filled with the minimum and maximum pixel values
from the area in inGrey they cover. */
////// Find steepest (up) slopes
/************* OMP ***************/
#pragma omp parallel for collapse(2)
for (int y=0 ; y<fullHeight ; y++) {
for (int x=0 ; x<fullWidth ; x++) {
double sqrSlope = searchSiblingAndCoarserQuads(x, y, getPixel(inGrey, x, y, fullWidth), x, y, 0, 0.0f);
setPixel(slopes, x, y, sqrt(sqrSlope), fullWidth);
}
}
////// Free allocated memory
for (int depth=1 ; depth<layerCount ; depth++) {
free(mins[depth]);
free(maxs[depth]);
}
free(mins);
free(maxs);
free(widths);
free(heights);
free(quadLengths);
////// Bye bye
return slopes ;
}
/***********************************************************************/
double* SteepestTangent(const uint8 *Image, const size_t Nr, const size_t Nc) {
/*
This implements the recursive Steepest Tangent Alg, as described in the DICTA-18 paper.
*/
/***********************************************************************/
size_t N = Nr*Nc; /* total number of pixels */
double* grey = makeDoubles(Nc, Nr);
for (int i=0 ; i<N ; i++) grey[i] = Image[i] ;
double* slopes = runSteepestTangent(grey, Nc, Nr);
free(grey);
return slopes ;
} /* SteepestTangent() */
|
exercice3.c | #include <stdio.h>
int main(void){
int total = 0;
#pragma omp parallel for reduction(+:total)
for (int i = 0; i < 100; i++){
total += i;
}
printf("total : %d", total);
}
|
rhombus_averaging.c | /*
This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license.
Github repository: https://github.com/OpenNWP/GAME
*/
/*
In this file, remapping indices and weights to rhombi are computed.
*/
#include <stdlib.h>
#include <stdio.h>
#include <geos95.h>
#include "../../src/game_types.h"
#include "../../src/game_constants.h"
#include "include.h"
int rhombus_averaging(int vorticity_indices_triangles[], int vorticity_signs_triangles[], int from_index_dual[], int to_index_dual[], int vorticity_indices_rhombi[], int density_to_rhombus_indices[], int from_index[], int to_index[], double area_dual[], double z_vector[], double latitude_scalar_dual[], double longitude_scalar_dual[], double density_to_rhombus_weights[], double latitude_vector[], double longitude_vector[], double latitude_scalar[], double longitude_scalar[], double TOA)
{
/*
This function implements the averaging of scalar quantities to rhombi. Indices and weights are computed here for the highest layer but remain unchanged elsewhere.
*/
int counter;
int indices_list_pre[6];
int indices_list[4];
int double_indices[2];
int density_to_rhombus_indices_pre[4];
int density_to_rhombus_index_candidate, check_counter, dual_scalar_h_index_0, dual_scalar_h_index_1, vector_h_index_0, vector_h_index_1, vector_h_index_0_found, vector_h_index_1_found, k, which_vertex_check_result, first_case_counter, second_case_counter;
double triangle_0, triangle_1, triangle_2, triangle_3, rhombus_area, check_sum;
#pragma omp parallel for private(counter, indices_list_pre, indices_list, double_indices, density_to_rhombus_indices_pre, density_to_rhombus_index_candidate, check_counter, dual_scalar_h_index_0, dual_scalar_h_index_1, vector_h_index_0, vector_h_index_1, vector_h_index_0_found, vector_h_index_1_found, k, which_vertex_check_result, first_case_counter, second_case_counter, triangle_0, triangle_1, triangle_2, triangle_3, rhombus_area, check_sum)
for (int i = 0; i < NO_OF_VECTORS_H; ++i)
{
double_indices[0] = -1;
double_indices[1] = -1;
for (int j = 0; j < 3; ++j)
{
indices_list_pre[j] = vorticity_indices_triangles[3*to_index_dual[i] + j];
}
for (int j = 0; j < 3; ++j)
{
indices_list_pre[3 + j] = vorticity_indices_triangles[3*from_index_dual[i] + j];
}
for (int j = 0; j < 6; ++j)
{
for (int k = j + 1; k < 6; ++k)
{
if (indices_list_pre[j] == indices_list_pre[k])
{
double_indices[0] = j;
double_indices[1] = k;
}
}
}
counter = 0;
for (int j = 0; j < 6; ++j)
{
if (j != double_indices[0] && j != double_indices[1])
{
indices_list[counter] = indices_list_pre[j];
counter++;
}
}
if (counter != 4)
{
printf("Error in vorticity_indices_rhombi and vortictiy_signs creation from vorticity_indices_triangles and vortictiy_signs_pre, position 1.\n");
exit(1);
}
for (int j = 0; j < 4; ++j)
{
vorticity_indices_rhombi[4*i + j] = indices_list[j];
if (vorticity_indices_rhombi[4*i + j] >= NO_OF_VECTORS_H || vorticity_indices_rhombi[4*i + j] < 0)
{
printf("Error in vorticity_indices_rhombi and vortictiy_signs creation from vorticity_indices_triangles and vortictiy_signs_pre, position 3.");
exit(1);
}
}
// Now comes the density interpolation to rhombi. First the indices.
for (int j = 0; j < 4; ++j)
{
density_to_rhombus_indices_pre[j] = -1;
}
check_counter = 0;
for (int j = 0; j < 4; ++j)
{
density_to_rhombus_index_candidate = from_index[vorticity_indices_rhombi[4*i + j]];
if (in_bool_calculator(density_to_rhombus_index_candidate, density_to_rhombus_indices_pre, 4) == 0)
{
density_to_rhombus_indices_pre[check_counter] = density_to_rhombus_index_candidate;
++check_counter;
}
density_to_rhombus_index_candidate = to_index[vorticity_indices_rhombi[4*i + j]];
if (in_bool_calculator(density_to_rhombus_index_candidate, density_to_rhombus_indices_pre, 4) == 0)
{
density_to_rhombus_indices_pre[check_counter] = density_to_rhombus_index_candidate;
++check_counter;
}
}
if (check_counter != 4)
{
printf("Error in density_to_rhombus_indices calculation.\n");
exit(1);
}
for (int j = 0; j < 4; ++j)
{
density_to_rhombus_indices[4*i + j] = density_to_rhombus_indices_pre[j];
}
// now the weights
rhombus_area = area_dual[NO_OF_VECTORS_H + from_index_dual[i]] + area_dual[NO_OF_VECTORS_H + to_index_dual[i]];
// This is a sum over the four primal cells which are needed for the density interpolation.
first_case_counter = 0;
second_case_counter = 0;
for (int j = 0; j < 4; ++j)
{
if (density_to_rhombus_indices[4*i + j] == from_index[i] || density_to_rhombus_indices[4*i + j] == to_index[i])
{
// In this case, four triangles need to be summed up.
first_case_counter++;
vector_h_index_0_found = 0;
k = 0;
while (vector_h_index_0_found == 0)
{
if (from_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j] || to_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j])
{
vector_h_index_0_found = 1;
vector_h_index_0 = vorticity_indices_rhombi[4*i + k];
}
else
{
++k;
}
}
dual_scalar_h_index_0 = from_index_dual[vector_h_index_0];
which_vertex_check_result = 1;
for (int l = 0; l < 4; ++l)
{
if (l != k)
{
if (from_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_0 || to_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_0)
{
which_vertex_check_result = 0;
}
}
}
if (which_vertex_check_result == 1)
{
dual_scalar_h_index_0 = to_index_dual[vector_h_index_0];
}
triangle_0 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_0], longitude_scalar_dual[dual_scalar_h_index_0], latitude_vector[vector_h_index_0], longitude_vector[vector_h_index_0]);
triangle_1 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_0], longitude_scalar_dual[dual_scalar_h_index_0], latitude_vector[i], longitude_vector[i]);
vector_h_index_1_found = 0;
k = 0;
while (vector_h_index_1_found == 0)
{
if ((from_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j] || to_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j]) && vorticity_indices_rhombi[4*i + k] != vector_h_index_0)
{
vector_h_index_1_found = 1;
vector_h_index_1 = vorticity_indices_rhombi[4*i + k];
}
else
{
++k;
}
}
dual_scalar_h_index_1 = from_index_dual[vector_h_index_1];
which_vertex_check_result = 1;
for (int l = 0; l < 4; ++l)
{
if (l != k)
{
if (from_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_1 || to_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_1)
{
which_vertex_check_result = 0;
}
}
}
if (which_vertex_check_result == 1)
{
dual_scalar_h_index_1 = to_index_dual[vector_h_index_1];
}
triangle_2 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_1], longitude_scalar_dual[dual_scalar_h_index_1], latitude_vector[i], longitude_vector[i]);
triangle_3 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_1], longitude_scalar_dual[dual_scalar_h_index_1], latitude_vector[vector_h_index_1], longitude_vector[vector_h_index_1]);
density_to_rhombus_weights[4*i + j] = pow(RADIUS + z_vector[NO_OF_SCALARS_H], 2)*(triangle_0 + triangle_1 + triangle_2 + triangle_3)/rhombus_area;
}
else
{
// In this case, only two triangles need to be summed up.
second_case_counter++;
vector_h_index_0_found = 0;
k = 0;
while (vector_h_index_0_found == 0)
{
if (from_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j] || to_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j])
{
vector_h_index_0_found = 1;
vector_h_index_0 = vorticity_indices_rhombi[4*i + k];
}
else
{
++k;
}
}
dual_scalar_h_index_0 = from_index_dual[vector_h_index_0];
which_vertex_check_result = 1;
for (int l = 0; l < 4; ++l)
{
if (l != k)
{
if (from_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_0 || to_index_dual[vorticity_indices_rhombi[4*i + l]] == dual_scalar_h_index_0)
{
which_vertex_check_result = 0;
}
}
}
if (which_vertex_check_result == 1)
{
dual_scalar_h_index_0 = to_index_dual[vector_h_index_0];
}
triangle_0 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_0], longitude_scalar_dual[dual_scalar_h_index_0], latitude_vector[vector_h_index_0], longitude_vector[vector_h_index_0]);
vector_h_index_1_found = 0;
k = 0;
while (vector_h_index_1_found == 0)
{
if ((from_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j] || to_index[vorticity_indices_rhombi[4*i + k]] == density_to_rhombus_indices[4*i + j]) && vorticity_indices_rhombi[4*i + k] != vector_h_index_0)
{
vector_h_index_1_found = 1;
vector_h_index_1 = vorticity_indices_rhombi[4*i + k];
}
else
{
++k;
}
}
triangle_1 = calc_triangle_area(latitude_scalar[density_to_rhombus_indices[4*i + j]], longitude_scalar[density_to_rhombus_indices[4*i + j]],
latitude_scalar_dual[dual_scalar_h_index_0], longitude_scalar_dual[dual_scalar_h_index_0], latitude_vector[vector_h_index_1], longitude_vector[vector_h_index_1]);
density_to_rhombus_weights[4*i + j] = pow(RADIUS + z_vector[NO_OF_SCALARS_H], 2)*(triangle_0 + triangle_1)/rhombus_area;
}
}
if (first_case_counter != 2)
{
printf("Error in density_to_rhombus_weights. It is first_case_counter != 2.\n");
exit(1);
}
if (second_case_counter != 2)
{
printf("Error in density_to_rhombus_weights. It is second_case_counter != 2.\n");
exit(1);
}
check_sum = 0;
for (int j = 0; j < 4; ++j)
{
check_sum += density_to_rhombus_weights[4*i + j];
if (density_to_rhombus_weights[4*i + j] <= 0 || density_to_rhombus_weights[4*i + j] >= 1)
{
printf("Error in density_to_rhombus_weights, position 1.\n");
exit(1);
}
}
if (fabs(check_sum - 1) > EPSILON_SECURITY)
{
printf("Error in density_to_rhombus_weights, position 0. Coefficient which should be one has value %lf.\n", check_sum);
exit(1);
}
}
return 0;
}
|
DRACC_OMP_015_Counter_wrong_lock_yes.c | /*
Concurrent access on a counter with the wrong lock, by utilising OpenMP Lock Routines. Atomicity Violation.
Two locks are used to ensure that addition and substraction cannot be interrupted by themselfes on other teams.
Although they are able to interrupt eachother leading to a wrong result. Intra and Inter Region.
*/
#include <omp.h>
#include <stdio.h>
#define N 100
int countervar = 0;
#pragma omp declare target
omp_lock_t addlock;
omp_lock_t sublock;
#pragma omp end declare target
int count(){
#pragma omp target map(tofrom:countervar) device(0)
#pragma omp teams
{
omp_init_lock(&addlock);
omp_init_lock(&sublock);
#pragma omp distribute parallel for
for(int i=0; i<N; i++){
omp_set_lock(&addlock);
countervar++;
omp_unset_lock(&addlock);
omp_set_lock(&sublock);
countervar -= 2;
omp_unset_lock(&sublock);
}
omp_destroy_lock(&addlock);
omp_destroy_lock(&sublock);
}
return 0;
}
int main(){
count();
printf("counter: %i expected: -%i\n ",countervar,N);
return 0;
} |
spgsolver.h | /*
Algorithm for Steiner Problem in Graphs
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
#include "binheap.h"
#include "graph.h"
#include "solution.h"
#include "rfw_timer.h"
#include "uf.h"
#include "uset.h"
#include "voronoi.h"
#include "rfw_random.h"
#include "rfw_stack.h"
#include "drawer.h"
#include "dual.h"
#include "stedgelinear.h"
#include "pairheap.h"
#include "buckets.h"
#include <cstring>
#include <cmath>
#include "elite.h"
#include "spgconfig.h"
#include <omp.h>
#include "constructive.h"
#include "execution_log.h"
#include "LSVertexInsertion.h"
#include "LSVertexElimination.h"
#include "LSBasics.h"
#include "LSKeyPath.h"
#include "BranchBound.h"
#include "perturbation.h"
#include "preprocess.h"
using namespace std;
class SPGSolver {
private:
static void fatal (const string &msg) {
fprintf (stdout, "ERROR: %s.\n", msg.c_str());
fflush(stdout);
exit(-1);
}
static void warning (const string &msg) {
fprintf (stdout, "%s", msg.c_str());
fflush(stdout);
}
/*
static void ShowUsage() {
fprintf (stdout, "Usage: steiner <filename> <upper bound> [-prep 1] [-seed <s>]\n");
}*/
static void ExtractFilename (char *filename, char *name) {
strcpy (name, filename);
//fprintf (stdout, "<%s> ", name);
//exit(-1);
char *lastsep = NULL;
char *lastdot = NULL;
char *end = &name[strlen(name)];
char *p = name;
for (p=name; p<=end; p++) {
if (*p=='/' || *p=='\\') lastsep = p;
if (*p=='.') lastdot = p;
}
if (lastsep == NULL) {
lastsep = name;
} else {
lastsep ++;
}
if (lastdot == NULL) {
lastdot = end;
}
// avoid weird cases
if (lastdot <= lastsep) {
lastdot = end;
lastsep = name;
}
*lastdot = 0;
int i = 0;
while (1) {
name[i] = *lastsep;
if (name[i] == 0) break;
i++;
lastsep ++;
}
//fprintf (file, "graph %s\n", lastsep);
//fprintf (file, "graph %s\n", name);
//delete [] name;
}
static void OutputGraphStats (FILE *file, Graph &g, char *filename) {
fprintf (file, "file %s\n", filename);
fprintf (file, "nvertices %d\n", g.VertexCount());
fprintf (file, "nedges %d\n", g.EdgeCount());
fprintf (file, "nterminals %d\n", g.TerminalCount());
}
public:
static EdgeCost ReadBound(FILE *logfile, char *graphname) {
EdgeCost answer = -1;
FILE *file = fopen ("bounds.txt", "r");
if (!file) {
fprintf (stdout, "Could not find bounds file.\n");
fflush (stdout);
return answer;
}
fprintf (stdout, "Reading bounds file... ");
fflush (stdout);
double solution;
const int BUFSIZE = 65534; //1048574;
char buffer [BUFSIZE+2];
char bufseries [BUFSIZE+2];
char bufclass [BUFSIZE+2];
char bufinstance [BUFSIZE+2];
sprintf (bufseries, "undefined");
sprintf (bufclass, "undefined");
while (fgets(buffer, BUFSIZE, file)!=0) {
//fprintf (stdout, "<%s> ", buffer);
if (sscanf (buffer, "#series %s", bufseries) > 0) {
continue;
}
if (sscanf (buffer, "#class %s", bufclass) > 0) {
continue;
}
if (sscanf (buffer, "%s %lg", bufinstance, &solution)>0) {
if (strcmp (bufinstance, graphname) == 0) {
answer = (EdgeCost)solution;
fprintf (logfile, "instance %s\n", graphname);
fprintf (logfile, "series %s\n", bufseries);
fprintf (logfile, "class %s\n", bufclass);
fprintf (logfile, "bestknown %.20f\n", (double)solution);
}
}
}
fclose(file);
//fprintf (stdout, "done (solution is %.0f).\n", (double)answer);
//fflush (stdout);
return answer;
}
typedef enum { MS_PLAIN, MS_COMBINATION, MS_BINARY, MS_MULTILEVEL, MS_TIMEBOUNDEDCOMBINATION, MS_TIMEBOUNDEDMULTILEVEL, MS_TIMEBOUNDEDADAPTIVE, MS_NUMBER } MSType;
static void ShowUsage () {
fprintf (stdout, "Usage: steiner <stp_file> [-bb] [-ub] [-prep] [-msit] [-seed] [-mstype]\n");
fprintf (stdout, "Valid types: plain(%d) combination(%d) binary(%d) multilevel(%d)\n", MS_PLAIN, MS_COMBINATION, MS_BINARY, MS_MULTILEVEL);
exit (-1);
}
static void RunMultistart(Graph &g, int mstype, int msit, EdgeCost &gbestfound, EdgeCost &bestknown, SteinerConfig &config, char *name, GlobalInfo *ginfo, ExecutionLog *executionLogPtr, SteinerSolution *outSolution) {
double mstime = 0;
EdgeCost mscost = g.GetFixedCost();
int elite = -1;
EdgeCost bestfound = gbestfound;
if (g.EdgeCount()>0 && g.TerminalCount()>1) {
fprintf(stdout, "MULTISTARTING WITH %d\n", mstype);
mscost = INFINITE_COST;
// If the multistart type is the time bounded combination multistart type, do not do the
// incremental number of iterations.
if (mstype == MS_TIMEBOUNDEDCOMBINATION || mstype == MS_TIMEBOUNDEDMULTILEVEL || mstype == MS_TIMEBOUNDEDADAPTIVE) {
SteinerSolution solution(&g);
RFWTimer mstimer(true);
TimeBoundedMultistart(solution, mstype, msit, config.OUTPUT_INCUMBENT ? name : NULL, -1, &config, ginfo, executionLogPtr);
mstime = mstimer.getTime();
if (outSolution != nullptr) {
outSolution->CopyFrom(&solution);
mscost = solution.GetCost();
}
}
else {
int doneit = 0;
for (int maxit = (config.TIME_LIMIT <= 0 ? (msit <= 0 ? 2 : msit) : 2);
(msit <= 0 || doneit < msit) && (config.TIME_LIMIT <= 0 || executionLogPtr->timerPtr->getTime() < config.TIME_LIMIT);
maxit *= 2)
{
SteinerSolution solution(&g);
int curit = maxit;
if (msit > 0 && doneit + maxit > msit)
curit = msit - doneit;
fprintf(stdout, "RUNNING %d ITERATIONS (%d ALREADY DONE IN %.2f SEC).\n", curit, doneit, executionLogPtr->timerPtr->getTime());
RFWTimer mstimer(true);
switch (mstype) {
case MS_PLAIN: PlainMultistart(solution, curit, -1, &config); break;
case MS_COMBINATION: CombinationMultistart(solution, curit, elite, config.OUTPUT_INCUMBENT ? name : NULL, -1, &config, ginfo, executionLogPtr); break;
case MS_BINARY: BinaryMultistart(solution, curit, name, &config); break;
case MS_MULTILEVEL: MultilevelMultistart(solution, curit, curit, elite, config.OUTPUT_INCUMBENT ? name : NULL, -1, &config); break;
};
doneit += curit;
mstime += mstimer.getTime();
if (solution.GetCost() < mscost) {
fprintf(stdout, "FOUND BETTER SOLUTION. IMPROVING COST FROM %.0f TO %.0f.\n", mscost, solution.GetCost());
mscost = solution.GetCost();
if (outSolution != nullptr && (outSolution->GetCost() > solution.GetCost() || outSolution->EdgeCount() == 0)) {
outSolution->CopyFrom(&solution);
}
}
//if (outSolution != nullptr && (outSolution->GetCost() > solution.GetCost() || outSolution->EdgeCount() == 0)) {
// outSolution->CopyFrom(&solution);
// fprintf(stdout, "FOUND BETTER SOLUTION. IMPROVING COST FROM %.0f TO %.0f.\n", mscost, solution.GetCost());
// mscost = solution.GetCost();
//}
}
}
}
if (mscost < bestfound) bestfound = mscost;
fprintf (stdout, "Solution is %.12f.\n", (double)mscost);
/*
double ratio = (double)mscost / (double)bestknown;
double error = ratio - 1;
fprintf (stdout, "ratio %.12f\n", ratio);
fprintf (stdout, "error %.12f\n", error);
fprintf (stdout, "pcterror %.12f\n", 100.0 * error);
*/
Basics::ReportResults(stdout, "ms", mstime, mscost, bestknown);
fprintf (stdout, "msiterations %d\n", msit);
fprintf(stdout, "mstype %d\n", mstype);
//fprintf (stdout, "mssolution %.0f\n", mscost);
//fprintf (stdout, "mstimeseconds %.12f\n", mstime);
gbestfound = bestfound;
}
static void Solve (int argc, char **argv) {
const uint64_t version = 201706010852;
cout << "version " << version << endl
<< "precision " << fixed << setprecision(20) << EDGE_COST_PRECISION << endl;
if (argc < 2) ShowUsage();
Graph g;
g.ReadSTP(argv[1]);
char *filename = argv[1];
char *name = new char[strlen(filename)+1];
ExtractFilename(filename, name);
OutputGraphStats (stdout, g, argv[1]);
fprintf (stdout, "graph %s\n", name);
EdgeCost bestknown = ReadBound(stdout, name);
EdgeCost bestfound = INFINITE_COST;
//ReadBound("bounds.txt", );
EdgeCost solcost = 0;
bool MSTPRUNE = false;
bool PREPROCESS = false;
bool SAFE_PREPROCESS = false;
bool DUALASCENT = false;
bool BRANCHBOUND = false;
bool LOCALSEARCH = false;
bool MULTISTART = false;
bool BINARYMULTISTART = true;
int mstype = MS_COMBINATION;
int msit = 0;
int seed = 17;
EdgeCost primal = INFINITE_COST;
//fprintf (stdout, "ARGC is %d\n", argc);
SteinerConfig config;
for (int i=2; i<argc; i+=2) {
if (i == argc-1) ShowUsage();
if (strcmp(argv[i], "-ub")==0) {
primal = atoi(argv[i+1]);
fprintf (stdout, "Setting upper bound to %.0f.\n", primal);
continue;
}
if (strcmp(argv[i], "-bb")==0) {
if (atoi(argv[i+1])==0) {
BRANCHBOUND = false;
} else {
BRANCHBOUND = true;
}
continue;
}
if (strcmp(argv[i], "-prep")==0) {
if (atoi(argv[i+1])!=0) {
fprintf (stdout, "Will do preprocessing.\n");
PREPROCESS = true;
if (atoi(argv[i + 1]) > 1)
SAFE_PREPROCESS = true;
}
continue;
}
if (strcmp(argv[i], "-ls")==0) {
if (atoi(argv[i+1])!=0) {
fprintf (stdout, "Will do localsearch.\n");
LOCALSEARCH = true;
}
continue;
}
if (strcmp(argv[i], "-bms")==0) {
if (atoi(argv[i+1])!=0) {
fprintf (stdout, "Will do binary.\n");
BINARYMULTISTART = true;
}
continue;
}
if (strcmp(argv[i], "-msit")==0) {
msit = (atoi(argv[i+1]));
fprintf (stdout, "Will run %d multistart iterations.\n", msit);
continue;
}
if (strcmp(argv[i], "-mstype")==0) {
mstype = (atoi(argv[i+1]));
fprintf (stdout, "Will run multistart type %d.\n", mstype);
assert(mstype != 14); // This is corrupt (BB with TimeBoundedMultistart)
continue;
}
if (strcmp(argv[i], "-seed")==0) {
seed = atoi(argv[i+1]);
fprintf (stdout, "Set seed to %d.\n", seed);
continue;
}
//maybe config knows what to do with this parameter
config.ReadParameter (argv[i], argv[i+1]);
}
fflush (stdout);
if (config.EARLY_STOP_BOUND < 0) {config.EARLY_STOP_BOUND = bestknown;}
bestfound = primal;
config.Output(stdout);
fprintf (stdout, "seed %d\n", seed);
// if there is a best known solution, output it whenever we find it
if (config.OUTPUT_THRESHOLD<0 && bestknown>=0) {
config.OUTPUT_THRESHOLD = bestknown;
}
RFWTimer timer(true);
// solution cost log.
ExecutionLog executionLog(&g, &timer, config.TIME_LIMIT);
MULTISTART = (msit != 0);
RFWRandom::randomize(seed);
bool APPLY_PERTURBATION = false;
if (APPLY_PERTURBATION) {
fprintf (stdout, "Applying perturbation... ");
int m = g.EdgeCount();
vector<EdgeCost> pertcost (m+1,-1);
RFWLocalRandom random(seed+17);
PerturbationTools::ApplyPerturbation(g, pertcost, random, 1, 1.0001);
g.ApplyCosts(pertcost);
for (int i=1; i<std::min(10, m); i++) {
fprintf (stdout, "%.5f ", (double)g.GetCost(i));
}
fprintf (stdout, "done.\n");
}
if (PREPROCESS) {
fprintf (stdout, "Should be preprocessing.\n");
RFWTimer preptime(true);
Preprocessing::RunPreprocessing(g, !SAFE_PREPROCESS);
fprintf (stdout, "preptime %.6f\n", preptime.getTime());
fprintf (stdout, "prepfixed %.6f\n", g.GetFixedCost());
//PrepBottleneck(g);
//exit(-1);
}
bool GUARDED_MULTISTART = false;
if (mstype > MS_NUMBER) {
GUARDED_MULTISTART = true;
mstype = mstype % 10;
fprintf (stdout, "Will run guarded mode %d.\n", mstype);
}
double second_time = 0;
double first_time;
SteinerSolution bestSolution(&g);
if (MULTISTART && GUARDED_MULTISTART) {
fprintf (stdout, "There are %d threads, %d processes.\n", omp_get_max_threads(), omp_get_num_procs());
GlobalInfo ginfo;
ginfo.fixed = g.GetFixedCost();
config.DEPTH_LIMIT = 128;
fprintf (stdout, "Setting depth limit to %d.\n", config.DEPTH_LIMIT);
omp_set_num_threads(2);
RFWTimer ftimer(true);
#pragma omp parallel
{
Graph thread_g = g;
EdgeCost thread_bestfound = bestfound;
fprintf (stdout, "<%d> ", omp_get_thread_num());
if (omp_get_thread_num() == 0) {
RunMultistart(thread_g, mstype, msit, thread_bestfound, bestknown, config, name, &ginfo, &executionLog, nullptr);
fprintf (stdout, "DONE RUNNING MULTISTART AND FOUND %.3f\n", thread_bestfound);
ginfo.MakeSolved();
} else if (omp_get_thread_num() == 1) {
RFWTimer stimer(true);
fprintf (stdout, "Should be running something smarter here.\n");
int bbseed = seed;
if (bbseed > 0) bbseed = -bbseed;
BranchBound::RunBranchAndBound(thread_g, bbseed, thread_bestfound, thread_bestfound, bestknown, config, &ginfo, &executionLog);
second_time += stimer.getTime();
fprintf (stdout, "DONE RUNNING BRANCHING-AND-BOUND!\n");
if (!ginfo.bbpruned) ginfo.MakeSolved();
else fprintf (stdout, "Did not find the optimal solution, though.\n");
}
#pragma omp critical
{
if (thread_bestfound < bestfound) {
bestfound = thread_bestfound;
fprintf (stdout, "THREAD %d UPDATED TO %.3f\n", omp_get_thread_num(), bestfound);
}
}
}
#pragma omp barrier
{
fprintf (stdout, "Done with this.\n");
}
first_time = ftimer.getTime();
fprintf (stdout, "bbpruned %d\n", ginfo.bbpruned);
MULTISTART = false;
BRANCHBOUND = false;
}
if (MULTISTART) {
RunMultistart(g, mstype, msit, bestfound, bestknown, config, name, NULL, &executionLog, &bestSolution);
}
if (LOCALSEARCH) {
int maxit = 10;
for (int m=0; m<5; m++) {
double besttime = 99999999;
fprintf (stdout, "Running %d... ", m); fflush(stdout);
if (m==3) {
fprintf (stdout, "WARNING! SKIPPING METHOD 3.\n");
continue;
}
//if (m != 2) continue;
for (int i=0; i<maxit; i++) {
RFWTimer timer(true);
SteinerSolution solution(&g);
switch (m) {
case 0: MSTPrim (g, solution); break;
case 1: MSTKruskal (g, solution); break;
case 2: ConstructiveAlgorithms::SPH (g, solution, NULL, 1); break;
case 3: FullBoruvka (g, solution); break;
case 4: TestLocalSearch (g, solution); break;
}
if (m>=2 && MSTPRUNE) {
MSTPrune(g,solution);
}
solcost = solution.GetCost();
double t = timer.getTime();
if (t < besttime) besttime = t;
}
fprintf (stdout, "Method %d found solution of cost %d in %.3f milliseconds (best of %d runs).\n", m, solcost, besttime * 1000.0, maxit);
fflush(stdout);
}
}
if (BRANCHBOUND) {
BranchBound::RunBranchAndBound(g, seed, primal, bestfound, bestknown, config, NULL, &executionLog);
}
double walltime = timer.getTime();
fprintf (stdout, "totalwalltimeseconds %.12f\n", walltime);
//fprintf (stdout, "totaltimeseconds %.12f\n", walltime + second_time);
//fprintf (stdout, "bestsolution %.0f\n", bestfound);
Basics::ReportResults(stdout, "total", walltime + first_time, bestfound, bestknown);
Basics::ReportResults(stdout, "totalcpu", walltime + second_time, bestfound, bestknown);
// Dump official output logs.
if (!config.LOG_FILENAME.empty()) {
ofstream logFile(config.LOG_FILENAME.c_str());
if (logFile.is_open()) {
logFile << "SECTION Comment" << endl
<< "Name \"" << name << "\"" << endl
<< "Problem \"SPG\"" << endl
<< "Program \"puw\"" << endl
<< "Version \"" << version << "\"" << endl
<< "End" << endl
<< endl
<< "SECTION Solutions" << endl;
for (size_t i = 0; i < executionLog.solCost.size(); ++i) {
logFile << "Solution " << fixed << executionLog.solCost[i].second << " " << fixed << executionLog.solCost[i].first << endl;
}
logFile << "End" << endl
<< endl
<< "SECTION Run" << endl
<< "Threads 1" << endl
<< "Time " << fixed << walltime << endl
<< "Dual 0" << endl;
if (executionLog.solCost.empty())
logFile << "Primal inf" << endl;
else
logFile << "Primal " << fixed << executionLog.bestSolution.GetCost() << endl;
logFile << "End" << endl
<< endl;
if (!executionLog.solCost.empty()) {
logFile << "SECTION Finalsolution" << endl;
size_t numVertices = 0;
for (int v = 1; v <= g.VertexCount(); ++v) {
if (executionLog.bestSolution.GetDegree(v) > 0 || g.IsTerminal(v))
++numVertices;
}
logFile << "Vertices " << numVertices << endl;
for (int v = 1; v <= g.VertexCount(); ++v) {
if (executionLog.bestSolution.GetDegree(v) > 0 || g.IsTerminal(v))
logFile << "V " << v << endl;
}
logFile << "Edges " << executionLog.bestSolution.EdgeCount() << endl;
for (size_t e = 1; e <= g.EdgeCount(); ++e) {
if (executionLog.bestSolution.Contains(e))
logFile << "E " << g.GetFirstEndpoint(e) << " " << g.GetSecondEndpoint(e) << endl;
}
logFile << "End" << endl;
}
logFile.close();
}
}
executionLog.bestSolution.Output("steinerSolu.txt");
delete [] name;
}
static void CombineSolutions(SteinerSolution &target, SteinerSolution &sa, SteinerSolution &sb, RFWLocalRandom &random, SteinerConfig *config) {
Graph &g = *sa.g;
int n = g.VertexCount();
int m = g.EdgeCount();
const bool verbose = false;
/*
UniverseSet baselist = new UniverseSet(n);
VoronoiData voronoi = new VoronoiData(n);
UnionFind uf = new UnionFind(n);
SteinerSolution solution = new SteinerSolution(g);
BinaryHeap<ArcCost> heap = new BinaryHeap<ArcCost>(n);
ArcCost [] pertcost = new ArcCost [m+1];
SteinerSolution target = new SteinerSolution(g);
Console.Error.Write("{0} x {1}:", sa.GetCost(), sb.GetCost());
*/
vector<EdgeCost> pertcost(m+1,-1);
//was: 1000, (100,500), 1
for (int e = 1; e <= m; e++) {
int tcount = 0;
if (sa.Contains(e)) tcount++;
if (sb.Contains(e)) tcount++;
int mult = 1;
if (tcount == 0) mult = 1000; //random.GetInteger(200,300); //edge in neither solution: very expensive
else if (tcount == 1) mult = random.GetInteger(100, 500); //split edge: intermediate cost
else { mult = 1; } //random.GetInteger(100,200); } //edge in both: keep it
pertcost[e] = g.GetCost(e) * mult; // g.GetCost(a);
}
int root = Basics::PickRandomTerminal(g, random);
ConstructiveAlgorithms::SPH (g, target, &pertcost[0], root);
MSTPrune(g,target);
RunLocalSearch(g, target, random, -1, config);
if (verbose) fprintf (stdout, "%d x %d -> %d\n", sa.GetCost(), sb.GetCost(), target.GetCost());
/*
baselist.Reset();
for (int v = 1; v <= n; v++) {if (g.IsTerminal(v)) baselist.Insert(v);}
ComputeVoronoi(voronoi, baselist, heap, pertcost);
uf.Reset();
target.Reset();
Boruvka(target, voronoi, uf, pertcost);
ArcCost borcost = target.GetCost();
FullLocalSearch(target);
ArcCost newcost = target.GetCost();
Console.Error.WriteLine(" {0}", newcost);
return target;
}*/
}
static void BinaryMultistart (SteinerSolution &solution, int maxit, char *outprefix, SteinerConfig *config) {
int nlevels = 32;
vector<SteinerSolution*> levelsol (nlevels, NULL); //solution[i]: solution obtained by combining 2^i solutions
Graph &g = *solution.g;
int n = g.VertexCount();
int m = g.EdgeCount();
RFWTimer timer(true);
RFWLocalRandom random (RFWRandom::getInteger(1,999999999));
EdgeCost bestcost = 999999999;
const bool verbose =false;
bool USE_PERTURBATION = true;
bool ADAPTIVE_PERTURBATION = false;
fprintf (stdout, "Running multistart for %d iterations and %d levels (perturbation=%d).\n", maxit, nlevels, USE_PERTURBATION);
fflush(stdout);
vector<EdgeCost> pertcost (m+1,-1);
//bool USE_PERTURBATION = true;
//bool ADAPTIVE_PERTURBATION = false;
SteinerSolution cursol(&g);
SteinerSolution bestsol(&g);
SteinerSolution combsol(&g);
//EdgeCost bestcost = 999999999;
for (int i=0 ; i<maxit; i++) {
int root = random.GetInteger(1,n); //PickRandomTerminal(g, random);
if (USE_PERTURBATION) {
PerturbationTools::InitPerturbation(g, pertcost, random, config);
}
ConstructiveAlgorithms::SPH (g, cursol, USE_PERTURBATION ? &pertcost[0] : NULL, root);
MSTPrune(g,cursol);
RunLocalSearch(g, cursol, random, -1, config);
if (cursol.GetCost() < bestcost) {
bestcost = cursol.GetCost();
bestsol.CopyFrom(&cursol);
}
int j;
for (j=0; j<nlevels; j++) {
fprintf (stdout, "%10d : %2d : %.0f : ", (int)i, j, bestcost);
if (levelsol[j] == NULL) {
fprintf (stdout, "+%.0f\n", cursol.GetCost());
levelsol[j] = new SteinerSolution(&cursol);
break;
}
// so there is a solution at level j
//SteinerSolution *refsol = elite.GetReference(random.GetInteger(1, elite.Count()));
int maxtries = 5;
int t;
for (t=0; t<maxtries; t++) {
CombineSolutions(combsol, cursol, *levelsol[j], random, config);
//fprintf (stdout, "%.0f x %.0f -> %.0f\n", cursol.GetCost(), levelsol[j]->GetCost(), combsol.GetCost());
if (combsol.GetCost() < cursol.GetCost() && combsol.GetCost() < levelsol[j]->GetCost()) {
break; //cursol.CopyFrom(&combsol);
}
}
fprintf (stdout, "<%d>", t);
if (combsol.GetCost() > cursol.GetCost()) {
combsol.CopyFrom(&cursol);
fprintf (stdout, "a");
//fprintf (stdout, "!");
}
if (combsol.GetCost() > levelsol[j]->GetCost()) {
combsol.CopyFrom(levelsol[j]);
fprintf (stdout, "b");
}
cursol.CopyFrom(&combsol);
delete levelsol[j];
levelsol[j] = NULL;
//if (cursol.GetCost() < cursol.
if (cursol.GetCost() < bestcost) {
bestcost = cursol.GetCost();
bestsol.CopyFrom(&cursol);
}
}
if (i%10==0) fflush(stdout);
if (j==nlevels) {
fprintf (stdout, "Ran out of levels!\n");
break;
}
}
for (int i=0; i<nlevels; i++) {
if (levelsol[i]) delete levelsol[i];
}
solution.CopyFrom(&bestsol);
}
static void EliteMultistart (SteinerSolution &solution, int maxit, int capacity, char *outprefix, SteinerConfig *config) {
Graph &g = *solution.g;
SteinerSolution bestsol(&g);
SteinerSolution combsol(&g);
EdgeCost bestcost = INFINITE_COST;
RFWLocalRandom random (RFWRandom::getInteger(1,999999999));
SolutionPool elite(maxit);
for (int i=0; i<999999; i++) {
CombinationMultistart(solution, maxit, capacity, NULL, 0);
EdgeCost curcost = solution.GetCost();
fprintf (stdout, "Should be adding solution %.0f to capacity %d.\n", (double)curcost, capacity);
fflush(stdout);
int pos1 = elite.Add(&solution);
//int pos1 = -1;
CascadedCombination(solution, combsol, elite, -1, random, config);
curcost = solution.GetCost();
int pos2 = elite.Add(&solution);
fprintf (stdout, "[%d,%d:%.0f] ", pos1, pos2, (double)solution.GetCost());
if (curcost < bestcost) {
bestsol.CopyFrom(&solution);
bestcost = curcost;
}
fprintf (stdout, "Iteration %d: %.0f\n", i, (double)bestsol.GetCost());
elite.Output(stdout, 8);
}
solution.CopyFrom(&bestsol);
}
//--------------------------
// Repeatedly combine initial solution with others from the elite set, then add the result to elite set itself.
// Combinations continue until the algorithm fails to improve 'maxfail' times.
static void CascadedCombination(SteinerSolution &solution, SteinerSolution &combsol, SolutionPool &elite, int maxfail, RFWLocalRandom &random, SteinerConfig *config) {
if (maxfail < 0) maxfail = config->MAX_COMB_FAIL;
int failures_to_go = maxfail;
const bool verbose = false;
if (verbose) fprintf (stdout, "%d->", solution.GetCost());
while (failures_to_go > 0) {
SteinerSolution *refsol = elite.GetReference(random.GetInteger(1, elite.Count()));
CombineSolutions(combsol, solution, *refsol, random, config);
if (!combsol.IsBetter(&solution)) {
failures_to_go --;
} else {
solution.CopyFrom(&combsol);
}
}
if (verbose) fprintf (stdout, "%d\n", solution.GetCost());
elite.Add(&solution);
}
static void AddSmallPerturbation (Graph &g) {
fatal ("deprecated function");
int m = g.EdgeCount();
vector<EdgeCost> pertcost(m+1);
for (int e=1; e<=m; e++) {
EdgeCost c = 10000 * g.GetCost(e) + RFWRandom::getInteger(0,10);
pertcost[e] = c;
}
g.ApplyCosts(pertcost);
}
struct DistancePair {
int source;
EdgeCost distance;
};
class ClosenessData {
private:
int k;
int maxid;
void GetBounds (int v, int &first, int &last) {
first = v*maxid;
last = (v+1)*maxid;
}
public:
vector<DistancePair> data;
ClosenessData(int _k, int _maxid) {
k = _k;
maxid = _maxid;
data.resize(k*maxid+1);
}
};
static void FindKClosest (Graph &g, int k, vector<int> sources, ClosenessData &cdata) {
int n = g.VertexCount();
for (int v=1; v<=n; v++) {
//cdata[
}
}
static void KeyVertexInsertion (SteinerSolution &solution, RFWLocalRandom &random) {
//return;
Graph &g = *solution.g;
int n = g.VertexCount();
SteinerSolution tempsol(&g);
RFWStack<int,true> tempterm(n+1);
//fprintf (stdout, "Should be finding improvements!\n");
fprintf (stdout, "k");
const bool MOVE_SIDEWAYS = true;
vector<int> perm(n+1);
for (int v=1; v<=n; v++) {perm[v] = v;}
for (int i=1; i<n; i++) {
int j = random.GetInteger(i,n);
std::swap(perm[i], perm[j]);
}
int improvements = 1;
while (improvements > 0) {
improvements = 0;
//for (int v=1; v<=n; v++) {
for (int p=1; p<=n; p++) {
int v = perm[p]; //RFWRandom::getInteger(1,n); //warning! Should have a real permutation.
//fprintf (stdout, "%d ", v);
if (g.IsTerminal(v)) continue;
//if (!solution.Contains(v)) continue; //MUCH WEAKER VERSION OF THE SEARCH
/*
if (solution.GetDegree(v) <= 2) {
//fprintf (stdout, ".");
continue; //WARNING: THIS IS FOR TESTING ONLY
}*/
//fprintf (stdout, "v%d ", v);
tempterm.reset();
//fflush (stdout);
// push all current terminals
for (int w=1; w<=n; w++) {
if (g.IsTerminal(w)) continue;
if (solution.GetDegree(w) <= 2) continue;
//fprintf (stdout, "t%d:%d ", w, solution.GetDegree(w));
tempterm.push(w);
}
//fprintf (stdout, "Created %d new terminals.\n", tempterm.getNElements());
// push v itself (if not already pushed)
//if (solution.GetDegree(v) <= 2) tempterm.push(v);
int oldt = g.TerminalCount();
//fprintf (stdout, "oldt=%d ", g.TerminalCount());
for (int i=1; i<=tempterm.getNElements(); i++) {
int w = tempterm.peek(i);
//fprintf (stdout, "x");
if (g.IsTerminal(w)) fatal ("something wrong!\n");
g.MakeTerminal(w);
if (g.TerminalCount() == oldt) fatal ("insertion did nothing");
}
//fprintf (stdout, "newt=%d ", g.TerminalCount());
tempsol.Reset();
//fprintf (stdout, "%.0f+%.0f = ", solution.GetCost(), tempsol.GetCost());
ConstructiveAlgorithms::SPH(g, tempsol, NULL, v);
//fprintf (stdout, "%.0f>>%.0f ", oldcost, newcost);
for (int i=1; i<=tempterm.getNElements(); i++) {
int w = tempterm.peek(i);
g.UnmakeTerminal(w);
}
MSTPrune(g, tempsol);
EdgeCost oldcost = solution.GetCost();
EdgeCost newcost = tempsol.GetCost();
//if (newcost - oldcost > 0) fprintf (stdout, "%.0f ", newcost - oldcost);
//fflush(stdout);
double improvement = oldcost - newcost;
// remember the new solution if there is an improvement or a tie (if MOVE_SIDEWAYS is true)
if (improvement > EDGE_COST_PRECISION || (MOVE_SIDEWAYS && (improvement > -EDGE_COST_PRECISION))) {
solution.CopyFrom(&tempsol);
if (improvement > EDGE_COST_PRECISION) {
fprintf (stdout, ".");
improvements ++;
fprintf (stdout, "i%.0f ", newcost);
fflush(stdout);
return;
}
}
}
}
}
static void DecayLocalSearch (SteinerSolution &solution, vector<EdgeCost> &original, RFWLocalRandom &random, int decaysteps, double exponent, SteinerConfig *config, ExecutionLog *executionLogPtr = nullptr) {
Graph &g = *solution.g;
int m = g.EdgeCount();
vector<EdgeCost> current(m+1);
const bool verbose = true;
double precision = EDGE_COST_PRECISION;
// run a few iterations of the local search while decaying the perturbation (towards unperturbed solution)
int decaytogo = decaysteps;
for (;;) {
EdgeCost prevcost = solution.GetCost();
// run one round of local seach
MSTPrune(g,solution);
RunLocalSearch(g, solution, random, 1, config, executionLogPtr);
EdgeCost newcost = solution.GetCost();
if (decaytogo == 0) break;
if (prevcost - newcost <= precision) {
fprintf (stdout, "<%d> ", decaysteps - decaytogo);
break;
}
decaytogo --;
g.RetrieveCosts(current);
for (int e=1; e<=m; e++) {
//current[e] = original[e] + (current[e] - original[e]) * exponent; //NOT REALLY AN EXPONENT
current[e] = original[e] + (current[e] - original[e]) * exponent; //NOT REALLY AN EXPONENT
}
g.ApplyCosts(current);
solution.UpdateCost();
}
g.ApplyCosts(original); //restore original edge costs
solution.UpdateCost(); //recost the existing solution
EdgeCost before = solution.GetCost(); // this is the original cost
//fprintf (stdout, "d%.0f->", solution.GetCost());
//SPH (g, solution, NULL, root);
//fprintf (stdout, "[%d->", solution.GetCost());
// run local search on current solution using original costs
MSTPrune(g,solution);
RunLocalSearch(g, solution, random, -1, config);
EdgeCost after = solution.GetCost();
if (verbose) {
fprintf (stdout, " %.0f", after);
//fprintf (stdout, " %3.0f", before - after);
}
//fprintf (stdout, "%d]", solution.GetCost());
}
/**
* Generate randomized solution from scratch by perturbing edge weights, runing a constructive algorithm, then applying local search.
* The local search is applied to the perturbed graph initially, but the perturbation may be gradually dampened (removed).
*
*/
static void GenerateRandomizedSolution(SteinerSolution &solution, int root, vector<EdgeCost> &pertcost, RFWLocalRandom &random, SteinerConfig *config, ExecutionLog *executionLogPtr = nullptr) {
Graph &g = *solution.g;
int m = g.EdgeCount();
const bool VERBOSE_STEP = false;
vector<EdgeCost> original (m+1);
//remember original costs
g.RetrieveCosts(original);
// find local optimum with perturbed costs
g.ApplyCosts(pertcost);
ConstructiveAlgorithms::SPH (g, solution, NULL, root);
if (executionLogPtr != nullptr) {
fprintf(stdout, "ADDING SPH SOLUTION WITH COST %f.\n", solution.GetCost());
executionLogPtr->AddSolution(solution);
}
if (VERBOSE_STEP) {
fprintf (stdout, "Done after SPH (%d).\n", solution.GetCost());
fflush(stdout);
}
int LS_PERT_ROUNDS= std::max(999,g.VertexCount());
double LS_PERT_EXPONENT = 1.0; //no decay
if (config) {
LS_PERT_ROUNDS = config->LS_PERT_ROUNDS;
LS_PERT_EXPONENT = config->LS_PERT_EXPONENT;
}
if (LS_PERT_EXPONENT <= 0) fatal ("invalid perturbation exponent");
bool DECAY_LOCAL_SEARCH = (LS_PERT_EXPONENT <= 0.999999);
if (DECAY_LOCAL_SEARCH) {
DecayLocalSearch(solution, original, random, LS_PERT_ROUNDS, LS_PERT_EXPONENT, config, executionLogPtr);
} else {
MSTPrune(g,solution);
if (VERBOSE_STEP) {
fprintf (stdout, "Done after MSTPrune (%d).\n", solution.GetCost());
fflush(stdout);
}
RunLocalSearch(g, solution, random, LS_PERT_ROUNDS, config, executionLogPtr); //, 2);
if (VERBOSE_STEP) {
fprintf (stdout, "Done after LocalSearch (%d).\n", solution.GetCost());
fflush(stdout);
}
// find real local optimum
g.ApplyCosts(original);
solution.UpdateCost();
//SPH (g, solution, NULL, root);
//fprintf (stdout, "[%d->", solution.GetCost());
MSTPrune(g,solution);
RunLocalSearch(g, solution, random, -1, config);
//fprintf (stdout, "%d]", solution.GetCost());
}
}
static int ComputeCapacity(int maxit, SteinerConfig *config) {
double denominator = 1.0;
if (config) denominator = config->ELITE_DENOMINATOR;
int capacity = (int)ceil(sqrt((double)maxit / denominator));
return capacity;
}
static void PlainMultistart (SteinerSolution &solution, int maxit, int capacity, SteinerConfig *config) {
if (capacity<0) capacity = ComputeCapacity(maxit, config);
SolutionPool elite (capacity);
RFWLocalRandom random (RFWRandom::getInteger(1,999999999));
FlexibleMultistart (solution, maxit, elite, NULL, maxit, config);
//CombinationMultistart (solution, maxit, capacity, NULL, maxit, config);
SolutionPool children (capacity);
SolutionPool *a, *b;
a = &elite;
b = &children;
fprintf (stdout, "There are %d elite solutions.\n", elite.GetCount());
int maxfail = 100;
int failures = maxfail;
EdgeCost curbest = elite.FindBestCost();
//fprintf (stdout, "Initial best is %.0f\n", curbest);
//exit(-1);
while (1) {
fprintf (stdout, "HERE!\n");
fflush(stdout);
RecombineGeneration(*a, *b, random, config);
//if (b->FindBestCost() >= a->FindBestCost()) break;
//fprintf (stdout, "Doing stuff now.\n");
//fflush (stdout);
//EdgeCost newbest = curbest +1;
EdgeCost newbest = b->FindBestCost();
if (newbest >= curbest) {
failures --;
if (failures == 0) break;
} else {
failures = maxfail;
curbest = newbest;
}
fprintf (stdout, "New best solution is %.0f\n", curbest);
//break;
//fprintf (stdout, "Swapping (%d,%d)...\n", a->GetCount(), b->GetCount());
//fflush(stdout);
std::swap(a,b);
//fprintf (stdout, "Resetting...\n");
//fflush(stdout);
b->HardReset();
}
fprintf (stdout, "Ended with solution with cost %.0f\n", curbest);
}
static void CombinationMultistart(SteinerSolution &solution, int maxit, int capacity, char *outprefix, int COMBINATION_THRESHOLD = -1, SteinerConfig *config = NULL, GlobalInfo *ginfo = NULL, ExecutionLog *executionLogPtr = nullptr) {
if (capacity<0) capacity = ComputeCapacity(maxit, config);
SolutionPool elite (capacity);
if (!config->AGGRESSIVE_COMBINATION) COMBINATION_THRESHOLD = capacity;
fprintf (stdout, "<<<<< %p >>>>>>\n", ginfo);
FlexibleMultistart (solution, maxit, elite, outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr);
}
static void TimeBoundedMultistart(SteinerSolution &solution, int mstype, int maxitupper, char *outprefix, int COMBINATION_THRESHOLD = -1, SteinerConfig *config = NULL, GlobalInfo *ginfo = NULL, ExecutionLog *executionLogPtr = nullptr) {
SolutionPool tentativeElite(2);
RFWTimer tentativeTimer(true);
FlexibleMultistart(solution, 1, tentativeElite, outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr, false, false);
double tentativeTime = tentativeTimer.getTime();
int maxit = maxitupper;
const double blowupFactor = 2.5; // this fell from the sky after careful consideration
if (tentativeTime > 0 && config->TIME_LIMIT > 0)
maxit = static_cast<int>(ceil(config->TIME_LIMIT / tentativeTime / blowupFactor));
if (maxit > maxitupper)
maxit = maxitupper;
fprintf(stdout, "TENTATIVE TIME: %.3f SEC; WILL COMPUTE %d ITERATIONS (UPPER BOUND = %d).\n", tentativeTime, maxit, maxitupper);
int capacity = ComputeCapacity(maxit, config);
SolutionPool elite(capacity);
if (!config->AGGRESSIVE_COMBINATION) COMBINATION_THRESHOLD = capacity;
// Determine which multistart to call depending on mstype.
int localtype = mstype;
if (mstype == MS_TIMEBOUNDEDADAPTIVE) {
localtype = maxit > 2048 ? MS_TIMEBOUNDEDMULTILEVEL : MS_TIMEBOUNDEDCOMBINATION;
}
if (localtype == MS_TIMEBOUNDEDCOMBINATION) {
FlexibleMultistart(solution, maxitupper, elite, outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr);
}
else if (localtype == MS_TIMEBOUNDEDMULTILEVEL) {
MultilevelMultistart(solution, maxit, maxitupper, capacity, outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr);
}
else {
fatal("Not supported.");
}
if (tentativeElite.FindBestCost() < solution.GetCost()) {
solution.CopyFrom(tentativeElite.GetReference(tentativeElite.FindBestPosition()));
fprintf(stdout, "USING SOLUTION FROM FIRST TENTATIVE ITERATION.\n");
}
fprintf(stdout, "actualmstype %d\n", localtype);
}
template<class T> static void Permute(vector<T> &array, RFWLocalRandom &random) {
int s = (int)array.size();
for (int i=0; i<s-1; i++) {
int j = random.GetInteger(i,s-1);
std::swap(array[i], array[j]);
}
}
static void MultilevelMultistart(SteinerSolution &solution, int maxit, int maxitupper, int capacity, char *outprefix, int COMBINATION_THRESHOLD = -1, SteinerConfig *config = NULL, GlobalInfo *ginfo = NULL, ExecutionLog *executionLogPtr = nullptr) {
fprintf (stdout, "SHOULD BE RUNNING MMS FROM SOLUTION %.0f\n", solution.GetCost());
fflush(stdout);
if (capacity<0) capacity = ComputeCapacity(maxit, config);
const int SUBCOUNT = 4;
SolutionPool *subelite[SUBCOUNT];
if (!config->AGGRESSIVE_COMBINATION) COMBINATION_THRESHOLD = capacity;
int localit = maxit / (2*SUBCOUNT);
int subcapacity = ComputeCapacity(localit, config);
int restit = maxit - SUBCOUNT*localit;
int restcap = ComputeCapacity(restit, config);
SolutionPool elite(restcap);
// Only do phase one of the algorithm if there are enough iterations.
if (localit > 0) {
for (int i = 0; i < SUBCOUNT; i++) {
subelite[i] = new SolutionPool(subcapacity);
}
// Runs subcount independent multistarts using half the total number of iterations.
for (int i = 0; i < SUBCOUNT; i++) {
fprintf(stdout, "SUBPROBLEM %d\n", i);
FlexibleMultistart(solution, localit, *subelite[i], outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr);
fprintf(stdout, "\n\n");
}
vector<SteinerSolution*> solpointers;
for (int i = 0; i < SUBCOUNT; i++) {
subelite[i]->Output(stdout, 8);
fprintf(stdout, "\n");
int count = subelite[i]->GetCount();
for (int j = 1; j <= count; j++) solpointers.push_back(subelite[i]->GetReference(j));
}
RFWLocalRandom random(RFWRandom::getInteger(1, 1000000));
Permute(solpointers, random);
//std::sort(solpointers.begin(), solpointers.end(), [&](SteinerSolution *x, SteinerSolution *y) {return x->GetCost() >= y->GetCost();});
//sort (&perm[0], &perm[perm.size()], [&](int x, int y) {return totalbound[x]/count[x] > totalbound[y]/count[y];});
for (int i = 0; i < (int)solpointers.size(); i++) {
SteinerSolution *sol = solpointers[i];
if (sol->GetCost() < solution.GetCost()) { solution.CopyFrom(sol); }
elite.Add(sol);
}
for (int i = 0; i<SUBCOUNT; i++) {
delete subelite[i];
}
/*
for (int i=0; i<SUBCOUNT; i++) {
subelite[i]->Output(stdout, 8);
fprintf (stdout, "\n");
int count = subelite[i]->GetCount();
for (int j=1; j<=count; j++) {
SteinerSolution *sol = subelite[i]->GetReference(j);
if (sol->GetCost() < solution.GetCost()) {solution.CopyFrom(sol);}
elite.Add(sol);
}
}*/
elite.Output(stdout, 8);
}
fprintf (stdout, "SUPERPROBLEM (from solution %.0f):\n", solution.GetCost());
FlexibleMultistart(solution, maxitupper - SUBCOUNT*localit, elite, outprefix, COMBINATION_THRESHOLD, config, ginfo, executionLogPtr);
}
static void RecombineGeneration (SolutionPool &parents, SolutionPool &children, RFWLocalRandom &random, SteinerConfig *config) {
int pcount = parents.GetCount();
if (pcount == 0) return;
fprintf (stdout, "Should be combining.\n");
Graph &g = *(parents.GetReference(1)->g);
SteinerSolution newsol(&g);
SteinerSolution bestsol(&g);
bestsol.CopyFrom(parents.GetReference(parents.FindBestPosition()));
//fprintf (stdout, "WARNING: THIS IS VERY WRONG.\n");
for (int i=1; i<pcount; i++) {
SteinerSolution *a = parents.GetReference(i);
fprintf (stdout, " %.0f", a->GetCost());
for (int j=i+1; j<=pcount; j++) {
SteinerSolution *b = parents.GetReference(j);
CombineSolutions(newsol, *a, *b, random, config);
//fprintf (stdout, "%.0f x %.0f: %.0f\t", a->GetCost(), b->GetCost(), newsol.GetCost());
if (newsol.GetCost() < bestsol.GetCost()) {
bestsol.CopyFrom(&newsol);
}
children.Add(&newsol);
}
}
// make sure the best solution (even if from a previous iteration) is preserved
children.Add(&bestsol);
fprintf (stdout, "Best solution is %.0f\n", bestsol.GetCost());
}
static void FlexibleMultistart(SteinerSolution &solution, int maxit, SolutionPool &elite, char *outprefix, int COMBINATION_THRESHOLD = -1, SteinerConfig *config = NULL, GlobalInfo *ginfo = NULL, ExecutionLog *executionLogPtr = nullptr, bool USE_PERTURBATION = true, bool outputStats = true) {
Graph &g = *solution.g;
//AddSmallPerturbation(g);
int itbits = 6;
//int maxit = 1 << itbits;
//int capacity = 1 << (itbits / 2);
/*
if (capacity < 0) {
double denominator = 1.0;
if (config) denominator = config->ELITE_DENOMINATOR;
capacity = (int)ceil(sqrt((double)maxit / denominator));
}*/
int n = g.VertexCount();
SteinerSolution bestsol(&g); //best solution found so far
SteinerSolution combsol(&g); //combined solution
bestsol.CopyFrom(&solution);
//SolutionPool elite (capacity);
int capacity = elite.GetCapacity();
//Graph &g = *solution.g;
int m = g.EdgeCount();
RFWTimer timer(true);
RFWLocalRandom random (RFWRandom::getInteger(1,999999999));
EdgeCost bestcost = INFINITE_COST;
if (elite.GetCount() > 0) {
int p = elite.FindBestPosition();
bestsol.CopyFrom(elite.GetReference(p));
bestcost = bestsol.GetCost();
}
const bool verbose = false;
//bool = perturbation;
bool ADAPTIVE_PERTURBATION = false;
bool RESILIENT_PERTURBATION = USE_PERTURBATION;
if (config) {
int confpert = config->RESILIENT_PERTURBATION;
if (confpert == 0) {RESILIENT_PERTURBATION = false;}
else if (confpert == 1) {RESILIENT_PERTURBATION = true;}
}
fprintf (stdout, "Using resilient perturbation? %d\n", RESILIENT_PERTURBATION);
//int COMBINATION_THRESHOLD = -1; //capacity;
fprintf (stdout, "Running multistart for %d iterations and %d elite solutions (perturbation=%d).\n", maxit, capacity, USE_PERTURBATION);
//fflush (stdout);
vector<EdgeCost> pertcost (m+1,-1);
const bool VERBOSE_STEP = false;
int i;
for (i=0; i<maxit; i++) {
//if (ginfo) fprintf (stdout, "THERE IS A GINFO.\n");
if (ginfo && ginfo->IsSolved()) {
fprintf (stdout, "Stopping at iteration %d.\n", i);
break;
}
if (config->TIME_LIMIT > 0 && executionLogPtr->timerPtr->getTime() >= config->TIME_LIMIT) {
fprintf(stdout, "Stopping at iteration %d because of time limit of %2.f sec (%.2f sec passed).\n", i, config->TIME_LIMIT, executionLogPtr->timerPtr->getTime());
break;
}
int root = random.GetInteger(1,n); //PickRandomTerminal(g, random);
if (USE_PERTURBATION) {
ADAPTIVE_PERTURBATION = false; //((i % 2) == 1); //random.GetInteger(0,1)==0;
//ADAPTIVE_PERTURBATION = true;
if (ADAPTIVE_PERTURBATION) {
PerturbationTools::AdaptivePerturbation(g, pertcost, elite, random);
} else {
//fprintf (stdout, "Here!\n");
PerturbationTools::InitPerturbation(g, pertcost, random, config);
//fflush (stdout);
}
}
if (RESILIENT_PERTURBATION) {
// both constructive and the local search use perturbation
GenerateRandomizedSolution (solution, root, pertcost, random, config);
} else {
// non-resilient perturbation:
ConstructiveAlgorithms::SPH (g, solution, USE_PERTURBATION ? &pertcost[0] : NULL, root);
if (executionLogPtr != nullptr)
executionLogPtr->AddSolution(solution);
MSTPrune(g,solution);
RunLocalSearch(g, solution, random, -1, config, executionLogPtr);
}
if (executionLogPtr != nullptr) {
executionLogPtr->AddSolution(solution);
}
//fprintf (stdout, "Adding original solution...\n");
elite.Add(&solution); //add initial solution to the pool
//global.UpdateSolution(solution.GetCost()); //make sure we remember it's the best
if (i >= COMBINATION_THRESHOLD) {
CascadedCombination(solution, combsol, elite, -1, random, config);
} else {
fprintf (stdout, "! ");
}
EdgeCost solcost = solution.GetCost();
//fprintf (stdout, "Found solution costing %d.\n", solcost);
if (solcost < bestcost) {
if (executionLogPtr != nullptr) {
executionLogPtr->AddSolution(solution);
}
bestcost = solcost;
bestsol.CopyFrom(&solution);
//fprintf (stdout, "HERE (%.2f %p %p %.2f).\n", bestcost, outprefix, config, config->OUTPUT_THRESHOLD);
if (outprefix) {
if (config && bestcost < config->OUTPUT_THRESHOLD) {
fprintf (stdout, "\n<outputting solution with value %0f>\n", bestcost);
config->OUTPUT_THRESHOLD = bestcost;
bestsol.Output(outprefix);
}
}
if (ginfo) ginfo->UpdateBestFound(bestcost);
}
bool localverbose = ((i % 10) == 0);
if (localverbose) {
fprintf (stdout, "%6d : %6d : %10.0f : %10.5f\n", i, root, (double)solcost, (double)bestcost);
fflush(stdout);
}
if (config && bestcost <= config->EARLY_STOP_BOUND) {
fprintf (stdout, "Early stop!\n");
break;
}
//elite.Output(stdout);
//if (i % 10 == 0) fflush (stdout);
}
if (outputStats) {
//fprintf (stdout, "msiterations %d\n", maxit);
fprintf(stdout, "actualiterations %d\n", i);
fprintf(stdout, "earlystop %d\n", maxit != i);
fprintf(stdout, "mselite %d\n", capacity);
//fprintf (stdout, "totaltimeseconds %.8f\n", timer.getTime());
//fprintf (stdout, "mssolution %.0f\n", (double)bestcost);
}
fflush (stdout);
solution.CopyFrom(&bestsol);
}
static void Multistart (SteinerSolution &solution, SteinerConfig *config) {
int maxit = 9999;
Graph &g = *solution.g;
int m = g.EdgeCount();
RFWTimer timer(true);
RFWLocalRandom random (RFWRandom::getInteger(1,999999999));
EdgeCost bestcost = INFINITE_COST;
bool USE_PERTURBATION = true;
fprintf (stdout, "Running multistart for %d iterations with perturbation=%d.\n", maxit, USE_PERTURBATION);
vector<EdgeCost> pertcost (m+1,-1);
for (int i=0; i<maxit; i++) {
int root = Basics::PickRandomTerminal(g, random);
if (USE_PERTURBATION) PerturbationTools::InitPerturbation(g, pertcost, random, NULL);
ConstructiveAlgorithms::SPH (g, solution, USE_PERTURBATION ? &pertcost[0] : NULL, root);
MSTPrune(g,solution);
RunLocalSearch(g, solution, random, -1, config);
EdgeCost solcost = solution.GetCost();
if (solcost < bestcost) {
bestcost = solcost;
}
if (i % 10 == 0) {
fprintf (stdout, "%6d : %6d : %6d : %6d\n", i, root, solcost, bestcost);
fflush(stdout);
}
//if (i % 10 == 0) fflush (stdout);
}
fflush (stdout);
fprintf (stdout, "totaltimeseconds %.8f\n", timer.getTime());
fprintf (stdout, "solution %d\n", bestcost);
/*
if (LOCALSEARCH) {
int maxit = 10;
for (int m=0; m<5; m++) {
double besttime = 99999999;
fprintf (stdout, "Running %d... ", m); fflush(stdout);
if (m==3) {
fprintf (stdout, "WARNING! SKIPPING METHOD 3.\n");
continue;
}
//if (m != 2) continue;
for (int i=0; i<maxit; i++) {
RFWTimer timer(true);
SteinerSolution solution(&g);
switch (m) {
case 0: MSTPrim (g, solution); break;
case 1: MSTKruskal (g, solution); break;
case 2: SPH (g, solution, NULL, 1); break;
case 3: FullBoruvka (g, solution); break;
case 4: TestLocalSearch (g, solution); break;
}
if (m>=2 && MSTPRUNE) {
MSTPrune(g,solution);
}
solcost = solution.GetCost();
double t = timer.getTime();
if (t < besttime) besttime = t;
}
fprintf (stdout, "Method %d found solution of cost %d in %.3f milliseconds (best of %d runs).\n", m, solcost, besttime * 1000.0, maxit);
fflush(stdout);
}
}*/
}
static void RunLocalSearch (Graph &g, SteinerSolution &solution, RFWLocalRandom &random, int maxrounds, SteinerConfig *config, ExecutionLog *executionLogPtr = nullptr) {
bool RUN_Q = false;
bool RUN_V = false;
bool RUN_U = false;
bool RUN_K = false;
bool RESTRICT_K = false; //
bool verbose = false;
static bool first = true;
char *lstype = config->LSTYPE;
bool wait = false;
for (int i=0; ;i++) {
char c = lstype[i];
if (c==0) break;
if (c=='w') {
wait = true;
continue;
}
switch (c) {
case 'k': RUN_K = true; RESTRICT_K = wait; break;
case 'v': RUN_V = true; break;
case 'u': RUN_U = true; break;
case 'q': RUN_Q = true; break;
default: fprintf (stdout, "WARNING: invalid local search parameter (%c).\n", c);
}
wait = false;
}
//fprintf (stdout, "<%d%d>", RUN_K, RESTRICT_K);
//return;
//int maxrounds = 999;
if (maxrounds < 0) maxrounds = 999; //999; //large number
if (first) {
fprintf (stdout, "Running with maxrounds %d.\n", maxrounds);
}
//SPH (g, solution, NULL, PickRandomTerminal(g,random));
//if (verbose) fprintf (stdout, "SPH found solution %d.\n", solution.GetCost());
int n = g.VertexCount();
EdgeCost oldcost = solution.GetCost();
RFWTimer timer(true);
int rounds = 0;
int i=0;
for (i=0; i<maxrounds; i++) {
rounds ++;
if (RUN_V) {
LSVertexInsertion::VertexInsertion(g, solution, n, random);
MSTPrune(g, solution);
if (verbose) fprintf (stdout, " v%d ", solution.GetCost());
}
//fprintf (stdout, "Starting key vertex elimination!\n");
//fflush (stdout);
if (RUN_Q) {
LSKeyPath::KeyVertexElimination(g, solution, random);
//fprintf (stdout, "Ending key vertex elimination!\n");
if (verbose) fprintf (stdout, " q%d ", solution.GetCost());
}
if (RUN_U) {
LSVertexElimination::VertexElimination(g, solution, random);
if (verbose) fprintf (stdout, " u%d ", solution.GetCost());
}
if (RUN_K) {
if (!RESTRICT_K || solution.GetCost() == oldcost) {
KeyVertexInsertion(solution, random);
}
}
EdgeCost newcost = solution.GetCost();
if (newcost > oldcost + EDGE_COST_PRECISION) fatal ("invalid result");
if (newcost > oldcost - EDGE_COST_PRECISION) break; //stop if result did not improve
if (executionLogPtr != nullptr) executionLogPtr->AddSolution(solution);
oldcost = newcost;
}
const bool VERBOSE_ROUNDS = false;
if (VERBOSE_ROUNDS) fprintf (stdout, "%d ", i);
//fprintf (stdout, "%d ", rounds);
if (verbose) fprintf (stdout, "\n\nDone with local search: %d (%.2f ms, %.2f ms average)\n", solution.GetCost(), 1000 * timer.getTime(), 1000 * timer.getTime() / (double)rounds);
//exit(-1);
first = false;
}
static void TestLocalSearch (Graph &g, SteinerSolution &solution) {
RFWLocalRandom random(RFWRandom::getInteger(1,999999999));
bool RUN_Q = true;
bool RUN_V = true;
bool RUN_U = false;
bool verbose = false;
ConstructiveAlgorithms::SPH (g, solution, NULL, Basics::PickRandomTerminal(g,random));
if (verbose) fprintf (stdout, "SPH found solution %d.\n", solution.GetCost());
int n = g.VertexCount();
EdgeCost oldcost = solution.GetCost();
RFWTimer timer(true);
int rounds = 0;
for (int i=0; i<10; i++) {
rounds ++;
if (RUN_V) {
LSVertexInsertion::VertexInsertion(g, solution, n, random);
MSTPrune(g, solution);
if (verbose) fprintf (stdout, " v%d ", solution.GetCost());
}
//fprintf (stdout, "Starting key vertex elimination!\n");
//fflush (stdout);
if (RUN_Q) {
LSKeyPath::KeyVertexElimination(g, solution, random);
//fprintf (stdout, "Ending key vertex elimination!\n");
if (verbose) fprintf (stdout, " q%d ", solution.GetCost());
}
if (RUN_U) {
LSVertexElimination::VertexElimination(g, solution, random);
if (verbose) fprintf (stdout, " u%d ", solution.GetCost());
}
EdgeCost newcost = solution.GetCost();
if (newcost > oldcost) fatal ("invalid result");
if (newcost == oldcost) break;
oldcost = newcost;
}
if (verbose) fprintf (stdout, "\n\nDone with local search: %d (%.2f ms, %.2f ms average)\n", solution.GetCost(), 1000 * timer.getTime(), 1000 * timer.getTime() / (double)rounds);
//exit(-1);
}
// Comput minimum spanning tree of the graph g using Prim's algorithm (ignores terminals)
// 'solution' will contain the MST edges
static void MSTPrim (Graph &g, SteinerSolution &solution) {
bool verbose = false;
int n = g.VertexCount();
BinaryHeap<EdgeCost> heap(n); // = new BinaryHeap<ArcCost>(n);
vector<int> parc (n+1); //not need to initialize
unsigned int r = Basics::PickRandomTerminal(g);
parc[r] = 0;
int nscanned = 0;
solution.Reset();
//int inscount = 0;
heap.Insert(r, 0);
while (!heap.IsEmpty()) {
unsigned int v;
EdgeCost acost;
heap.RemoveFirst(v,acost); //v, out acost);
if (v!=r) solution.Insert(parc[v]); //add parent edge to the solution
//scan outgoing arcs
nscanned ++;
SPGArc *a, *end;
for (g.GetBounds(v,a,end); a<end; a++) {
int w = a->head; //neighbor
if (solution.GetDegree(w) > 0) continue; //ignore if already in solution
if (heap.Insert(w, a->cost)) {
parc[w] = a->label;
//inscount ++;
}
}
}
//fprintf (stdout, "%.3f ", (double)inscount / (double)n);
//if (nscanned != n) fprintf (stdout, "Warning: graph is not connected");
}
//--------------------------------------------------------------
// Kruskal's algorithm to compute the MST of the full graph.
// (Could be made faster for some instances with partial sort.)
//--------------------------------------------------------------
static void MSTKruskal (Graph &g, SteinerSolution &solution) {
// create list of all edges sorted in increasing order of weight
const bool verbose = false;
int i, m = g.EdgeCount();
vector<int> elist(m+1);
for (i=0; i<m; i++) {elist[i] = i+1;}
sort(&elist[0], &elist[m], [&](int x, int y) {return g.GetCost(x)<g.GetCost(y);});
// create empty solution and union find with singletons
solution.Reset();
int n = g.VertexCount();
UnionFind uf(n);
int togo = n-1; //number of unions left
// process all edges in order
for (i=0; i<m; i++) {
int e = elist[i];
int v, w;
g.GetEndpoints(e,v,w);
if (uf.Union(v,w)) { //if successfully joined...
solution.Insert(e); //...we have a new edge in the tree
if (--togo==0) break;
}
}
if (verbose) fprintf (stdout, "%.3f ", (double)i/(double)m);
}
/// Compute the MST of the distance network of the subgraph induced
/// by the vertices in bases.
/// <param name="solution">Final solution (output)</param>
/// <param name="bases">Set of bases (key vertices)</param>
/*
static void DNH(Graph &g, SteinerSolution &solution, UniverseSet &baselist) {
int n = g.VertexCount();
int m = g.EdgeCount();
VoronoiData voronoi = new VoronoiData(n);
UnionFind uf = new UnionFind(n);
BinaryHeap<ArcCost> heap = new BinaryHeap<ArcCost>(n);
ArcCost [] pertcost = null;
ComputeVoronoi(voronoi, baselist, heap, pertcost);
solution.Reset();
Boruvka(solution, voronoi, uf, pertcost);
//Console.Error.WriteLine("DNH");
}
*/
/// Boruvka-based implementation of DNH (given a Voronoi diagram and the associated union-find data structure).
/// Traverses a list of edge IDs in each pass, eliminating those that are no longer boundary.
/// Seems to be worse than the version that actually traverses graphs.
static void Boruvka(Graph &g, SteinerSolution &solution, VoronoiData &voronoi, UnionFind &uf, EdgeCost *pertcost) {
int v, n = g.VertexCount();
int m = g.EdgeCount();
EdgeCost solvalue = 0;
const bool verbose = false;
//count boundary regions in the current diagram
int nregions = 0;
for (v=1; v<=n; v++) {
// it's not clear find is needed, unless some merges happened before
if (uf.Find(voronoi.GetBase(v))==v) nregions ++;
}
//Boruvka's algorithm
int *minarc = new int[n+1]; //minimum outgoing edge from the region based in v
EdgeCost *minvalue = new EdgeCost[n+1]; //value associated with the neighbor
int *elist = new int [m]; //list of all potential boundary edges
for (int i=0; i<m; i++) elist[i] = (i+1);
int ecount = m; //number of edges in edge list
int rounds = 0;
bool changes = true;
while (changes && nregions > 1) {
rounds ++;
//if (rounds > 3) break;
changes = false;
//initially, we don't know what are the arcs out of each component
for (v=1; v<=n; v++) {
minarc[v] = -1;
minvalue[v] = 0;
}
int nextpos = 0;
//fprintf (stdout, "%d ", ecount);
for (int i=0; i<ecount; i++) {
int e = elist[i]; //get edge in the current position
int v, w;
g.GetEndpoints(e,v,w);
int bv = voronoi.GetBase(v);
int bw = voronoi.GetBase(w);
if (bv == bw) continue; //same base
bv = uf.Find(bv);
bw = uf.Find(bw);
if (bv == bw) continue; //same component
//found a boundary edge: move it forward in the list
if (i!=nextpos) elist[nextpos++] = e;
// get length of actual edge
EdgeCost cost = (pertcost!=NULL) ? pertcost[e] : g.GetCost(e);
cost += voronoi.GetDistance(v) + voronoi.GetDistance(w);
//update bv and bw if better
if (minarc[bv]==-1 || (cost<minvalue[bv])) {minarc[bv]=e; minvalue[bv]=cost;}
if (minarc[bw]==-1 || (cost<minvalue[bw])) {minarc[bw]=e; minvalue[bw]=cost;}
}
ecount = nextpos; //fewer edges for next round
//join each region to its best neighbor
int bvisited = 0;
int b;
for (b=1; b<=n; b++) {
if (minarc[b] >= 0) { //best neighbor defined...
bvisited ++;
int w = 0;
g.GetEndpoints(minarc[b], v, w);
int bv = voronoi.GetBase(v);
int bw = voronoi.GetBase(w);
if (uf.Union(bv,bw)) { // if they were not already joined...
changes = true;
nregions--;
solution.Insert(minarc[b]);
while (v != bv) {
int f = voronoi.GetParentArc(v);
if (!solution.Insert(f)) break;
v = g.GetOther(f, v);
}
while (w != bw) {
int f = voronoi.GetParentArc(w);
if (!solution.Insert(f)) break;
w = g.GetOther(f, w);
}
}
}
}
}
if (verbose) fprintf(stdout, "\n");
delete [] minvalue;
delete [] minarc;
delete [] elist;
}
static void DNHPrim (Graph &g, SteinerSolution &solution, VoronoiData &voronoi, UnionFind &uf) {
int n = g.VertexCount();
int m = g.EdgeCount();
vector <int> new2old (m+1,-1);
Graph dg;
dg.SetVertices(n);
dg.SetEdges(m); //maximum tentative number of edges
// build appropriate subgraph of the distance network
int ecount = 0;
for (int v=1; v<=n; v++) {
int bv = uf.Find(voronoi.GetBase(v));
EdgeCost vdist = -1;
SPGArc *a, *end;
for (g.GetBounds(v,a,end); a<end; a++) {
int w = a->head;
if (v>=w) continue;
int bw = uf.Find(voronoi.GetBase(w));
if (bv == bw) continue;
dg.MakeTerminal(bv);
dg.MakeTerminal(bw);
if (vdist<0) vdist = voronoi.GetDistance(v);
EdgeCost cost = a->cost + vdist + voronoi.GetDistance(w);
dg.AddEdge(bv,bw,cost);
new2old[++ecount] = a->label;
}
}
dg.Commit(); //create actual graph
// find a solution in the new graph
SteinerSolution ds(&dg);
MSTPrim(dg,ds);
// transform into solution in the new graph
solution.Reset();
int newm = dg.EdgeCount();
for (int e=1; e<=newm; e++) {
if (!ds.Contains(e)) continue;
int orige = new2old[e]; //original boundary edge
if (orige<1 || orige>m) {fatal ("Edge out of range.\n");}
int v,w;
g.GetEndpoints(orige,v,w);
solution.Insert(orige);
for (;;) {
int f = voronoi.GetParentArc(v);
if (f<1 || !solution.Insert(f)) break;
v = g.GetOther(f,v);
}
for (;;) {
int f = voronoi.GetParentArc(w);
if (f<1 || !solution.Insert(f)) break;
w = g.GetOther(f,w);
}
}
}
/// Run DNH (Boruvka implementation) to create a solution from scratch.
/// If 'r' is null, uses the original edge weights; otherwise, perturbs
/// edge weights before running the algorithm.
/// <param name="solution">The output solution (will be deleted).</param>
/// <param name="r">Random number generator.</param>
static void FullBoruvka(Graph &g, SteinerSolution &solution) { //, OptRandom r) {
int n = g.VertexCount();
int m = g.EdgeCount();
UniverseSet baselist(n); // = new UniverseSet(n);
VoronoiData voronoi(n); // = new VoronoiData(n);
UnionFind uf(n); // = new UnionFind(n);
BinaryHeap<EdgeCost> heap(n); // = new BinaryHeap<ArcCost>(n);
/*
ArcCost [] pertcost = null;
if (r != null) {
pertcost = new ArcCost[m + 1];
InitPerturbation(pertcost, r);
}
*/
baselist.Reset();
for (int v = 1; v <= n; v++) {
if (g.IsTerminal(v)) baselist.Insert(v);
}
//fprintf (stdout, "Should be computing Voronoi.\n");
Basics::ComputeVoronoi(g, voronoi, baselist, heap, NULL); //pertcost);
solution.Reset();
// return;
//fprintf (stdout, "Missing boruvka!\n");
//Boruvka(g, solution, voronoi, uf, NULL);
Preprocessing::BoruvkaGraph(g, solution, voronoi, uf, NULL);
//DNHPrim(g,solution,voronoi,uf);
//Console.Error.WriteLine("t3:{0} ", timer.GetTime());
}
/// Modifies a solution by computing the MST of the subgraph induced by its vertices
/// and removing all vertices of degree one. Changes the solution.
/// <param name="svertices">Vertices in the solution (doesn't change).</param>
/// <param name="solution">Edges in the solution (may change).</param>
static bool MSTPrune(Graph &g, SteinerSolution &solution) {
//return 0;
EdgeCost original = solution.GetCost();
int n = g.VertexCount();
UniverseSet svertices(n);
Basics::MarkSolutionNodes(g, solution, svertices);
MST(g,solution,svertices);
Basics::Prune(g,solution);
//fprintf (stdout, "Solution costs %d, gain is %d.\n", solution.GetCost(), original - solution.GetCost());
//Prune(g,solution);
//fprintf (stdout, "g%d ", original - solution.GetCost());
return (solution.GetCost() < original) ? 1 : 0;
}
static int VeryOldPickTerminal(Graph &g, RFWLocalRandom &random) {
int t = 0;
int count = 0;
int n = g.VertexCount();
for (int v=1; v<=n; v++) {
if (g.IsTerminal(v)) {
if (t==0 || g.GetDegree(v) < g.GetDegree(t)) {
t = v;
}
}
}
return t;
}
/// <summary>
/// Compute the MST of the subgraph induced by svertices
/// (assumed to contain all terminals---DO I NEED THIS?)
/// </summary>
/// <param name="svertices">list of vertices to be spanned</param>
/// <param name="solution">solution in which the MST will be stored</param>
/// <returns>Number of vertices scanned.</returns>
static int MST (Graph &g, SteinerSolution &solution, UniverseSet &svertices) {
bool verbose = false;
int n = g.VertexCount();
BinaryHeap<EdgeCost> heap(n);
vector<int> parc (n+1);
int r = Basics::PickRandomTerminal(g);
if (!svertices.Contains(r)) fatal ("Terminal does not appear to belong to the solution.");
parc[r] = 0;
int nscanned = 0;
//run Prim's algorithm
solution.Reset();
heap.Insert(r, 0);
while (!heap.IsEmpty()) {
unsigned int v;
EdgeCost acost;
heap.RemoveFirst(v,acost);
if (v!=r) solution.Insert(parc[v]); //add edge (p(v),v) to solution
//scan vertices
nscanned ++;
SPGArc *a, *end;
for (g.GetBounds(v,a,end); a<end; a++) {
int w = a->head;
if (!svertices.Contains(w)) continue; //we only care about svertex
if (solution.GetDegree(w) > 0) continue; //vertex already in the new tree
if (heap.Insert(w, a->cost)) parc[w] = a->label;
}
}
//if (solution.Count() < g.TerminalCount() - 1) {fatal ("solution does not have enough vertices");}
return nscanned;
}
};
|
MzXMLHandler.h | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#ifndef OPENMS_FORMAT_HANDLERS_MZXMLHANDLER_H
#define OPENMS_FORMAT_HANDLERS_MZXMLHANDLER_H
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FORMAT/Base64.h>
#include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h>
#include <OpenMS/FORMAT/HANDLERS/XMLHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <stack>
namespace OpenMS
{
class MetaInfoInterface;
namespace Internal
{
/**
@brief XML handlers for MzXMLFile
MapType has to be a MSExperiment or have the same interface.
Do not use this class. It is only needed in MzXMLFile.
*/
template <typename MapType>
class MzXMLHandler :
public XMLHandler
{
public:
/**@name Constructors and destructor */
//@{
/// Constructor for a read-only handler
MzXMLHandler(MapType& exp, const String& filename, const String& version, ProgressLogger& logger) :
XMLHandler(filename, version),
exp_(&exp),
cexp_(0),
decoder_(),
nesting_level_(0),
skip_spectrum_(false),
spec_write_counter_(1),
consumer_(NULL),
scan_count_(0),
logger_(logger)
{
init_();
}
/// Constructor for a write-only handler
MzXMLHandler(const MapType& exp, const String& filename, const String& version, const ProgressLogger& logger) :
XMLHandler(filename, version),
exp_(0),
cexp_(&exp),
decoder_(),
nesting_level_(0),
skip_spectrum_(false),
spec_write_counter_(1),
consumer_(NULL),
scan_count_(0),
logger_(logger)
{
init_();
}
/// Destructor
virtual ~MzXMLHandler() {}
//@}
// Docu in base class
virtual void endElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname);
// Docu in base class
virtual void startElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname, const xercesc::Attributes& attributes);
// Docu in base class
virtual void characters(const XMLCh* const chars, const XMLSize_t length);
/// Write the contents to a stream
void writeTo(std::ostream& os);
/// Sets the options
void setOptions(const PeakFileOptions& options)
{
options_ = options;
}
///Gets the scan count
UInt getScanCount()
{
return scan_count_;
}
/// Set the IMSDataConsumer consumer which will consume the read data
void setMSDataConsumer(Interfaces::IMSDataConsumer<MapType> * consumer)
{
consumer_ = consumer;
}
private:
/// initialize members (call from C'tor)
void init_()
{
cv_terms_.resize(6);
//Polarity
String("any;+;-").split(';', cv_terms_[0]);
//Scan type
// is no longer used cv_terms_[1] is empty now
//Ionization method
String(";ESI;EI;CI;FAB;;;;;;;;;;;;;APCI;;;;;;;;MALDI").split(';', cv_terms_[2]);
cv_terms_[2].resize(IonSource::SIZE_OF_IONIZATIONMETHOD);
//Mass analyzer
String(";Quadrupole;Quadrupole Ion Trap;;;TOF;Magnetic Sector;FT-ICR;").split(';', cv_terms_[3]);
cv_terms_[3].resize(MassAnalyzer::SIZE_OF_ANALYZERTYPE);
//Detector
String(";EMT;;;Faraday Cup;;;;;Channeltron;Daly;Microchannel plate").split(';', cv_terms_[4]);
cv_terms_[4].resize(IonDetector::SIZE_OF_TYPE);
//Resolution method
String(";FWHM;TenPercentValley;Baseline").split(';', cv_terms_[5]);
cv_terms_[5].resize(MassAnalyzer::SIZE_OF_RESOLUTIONMETHOD);
/* // OLD:
cv_terms_.resize(6);
//Polarity
String("any;+;-").split(';',cv_terms_[0]);
//Scan type
// is no longer used cv_terms_[1] is empty now
//Ionization method
String(";ESI;EI;CI;FAB;TSP;MALDI;FD;FI;PD;SI;TI;API;ISI;CID;CAD;HN;APCI;APPI;ICP").split(';',cv_terms_[2]);
//Mass analyzer
String(";Quadrupole;Quadrupole Ion Trap;;;TOF;Magnetic Sector;FT-ICR;").split(';',cv_terms_[3]);
//Detector
String(";EMT;Daly;;Faraday Cup;;;;Channeltron").split(';',cv_terms_[4]);
//Resolution method
String(";FWHM;TenPercentValley;Baseline").split(';',cv_terms_[5]);
*/
}
protected:
/// Peak type
typedef typename MapType::PeakType PeakType;
/// Spectrum type
typedef MSSpectrum<PeakType> SpectrumType;
/// map pointer for reading
MapType* exp_;
/// map pointer for writing
const MapType* cexp_;
/// Options for loading and storing
PeakFileOptions options_;
/**@name temporary data structures to hold parsed data */
//@{
Base64 decoder_;
Int nesting_level_;
/**
@brief Data necessary to generate a single spectrum
Small struct holds all data necessary to populate a spectrum at a
later timepoint (since reading of the base64 data and generation of
spectra can be done at distinct timepoints).
*/
struct SpectrumData
{
UInt peak_count_;
String precision_;
String compressionType_;
String char_rest_;
SpectrumType spectrum;
bool skip_data;
};
/// Vector of spectrum data stored for later parallel processing
std::vector< SpectrumData > spectrum_data_;
//@}
/// Flag that indicates whether this spectrum should be skipped (due to options)
bool skip_spectrum_;
/// spectrum counter (spectra without peaks are not written)
UInt spec_write_counter_;
/// Consumer class to work on spectra
Interfaces::IMSDataConsumer<MapType>* consumer_;
/// Consumer class to work on spectra
UInt scan_count_;
/// Progress logging class
const ProgressLogger& logger_;
/// write metaInfo to xml (usually in nameValue-tag)
inline void writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, int indent = 4, String tag = "nameValue")
{
std::vector<String> keys; // Vector to hold keys to meta info
meta.getKeys(keys);
for (std::vector<String>::const_iterator it = keys.begin(); it != keys.end(); ++it)
{
if ((*it)[0] != '#') // internally used meta info start with '#'
{
os << String(indent, '\t') << "<" << tag << " name=\"" << *it << "\" value=\"" << writeXMLEscape(meta.getMetaValue(*it)) << "\"/>\n";
}
}
}
/// data processing auxiliary variable
std::vector< boost::shared_ptr< DataProcessing> > data_processing_;
/**
@brief Fill a single spectrum with data from input
@note Do not modify any internal state variables of the class since
this function will be executed in parallel.
*/
void doPopulateSpectraWithData_(SpectrumData & spectrum_data)
{
typedef typename SpectrumType::PeakType PeakType;
//std::cout << "reading scan" << "\n";
if (spectrum_data.char_rest_ == "") // no peaks
{
return;
}
//remove whitespaces from binary data
//this should not be necessary, but linebreaks inside the base64 data are unfortunately no exception
spectrum_data.char_rest_.removeWhitespaces();
if (spectrum_data.precision_ == "64")
{
std::vector<double> data;
if (spectrum_data.compressionType_ == "zlib")
{
decoder_.decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data, true);
}
else
{
decoder_.decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data);
}
spectrum_data.char_rest_ = "";
PeakType peak;
//push_back the peaks into the container
for (Size n = 0; n < (2 * spectrum_data.peak_count_); n += 2)
{
// check if peak in in the specified m/z and intensity range
if ((!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(data[n])))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(data[n + 1]))))
{
peak.setMZ(data[n]);
peak.setIntensity(data[n + 1]);
spectrum_data.spectrum.push_back(peak);
}
}
}
else //precision 32
{
std::vector<float> data;
if (spectrum_data.compressionType_ == "zlib")
{
decoder_.decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data, true);
}
else
{
decoder_.decode(spectrum_data.char_rest_, Base64::BYTEORDER_BIGENDIAN, data);
}
spectrum_data.char_rest_ = "";
PeakType peak;
//push_back the peaks into the container
for (Size n = 0; n < (2 * spectrum_data.peak_count_); n += 2)
{
if ((!options_.hasMZRange() || options_.getMZRange().encloses(DPosition<1>(data[n])))
&& (!options_.hasIntensityRange() || options_.getIntensityRange().encloses(DPosition<1>(data[n + 1]))))
{
peak.setMZ(data[n]);
peak.setIntensity(data[n + 1]);
spectrum_data.spectrum.push_back(peak);
}
}
}
}
/**
@brief Populate all spectra on the stack with data from input
Will populate all spectra on the current work stack with data (using
multiple threads if available) and append them to the result.
*/
void populateSpectraWithData_()
{
// Whether spectrum should be populated with data
if (options_.getFillData())
{
size_t errCount = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize i = 0; i < (SignedSize)spectrum_data_.size(); i++)
{
// parallel exception catching and re-throwing business
if (!errCount) // no need to parse further if already an error was encountered
{
try
{
doPopulateSpectraWithData_(spectrum_data_[i]);
if (options_.getSortSpectraByMZ() && !spectrum_data_[i].spectrum.isSorted())
{
spectrum_data_[i].spectrum.sortByPosition();
}
}
catch (...)
{
#pragma omp critical(HandleException)
++errCount;
}
}
}
if (errCount != 0)
{
throw Exception::ParseError(__FILE__, __LINE__, __PRETTY_FUNCTION__, file_, "Error during parsing of binary data.");
}
}
// Append all spectra
for (Size i = 0; i < spectrum_data_.size(); i++)
{
if (consumer_ != NULL)
{
consumer_->consumeSpectrum(spectrum_data_[i].spectrum);
if (options_.getAlwaysAppendData())
{
exp_->addSpectrum(spectrum_data_[i].spectrum);
}
}
else
{
exp_->addSpectrum(spectrum_data_[i].spectrum);
}
}
// Delete batch
spectrum_data_.clear();
}
private:
/// Not implemented
MzXMLHandler();
static const XMLCh* s_value_;
static const XMLCh* s_count_;
static const XMLCh* s_type_;
static const XMLCh* s_name_;
static const XMLCh* s_version_;
static const XMLCh* s_filename_;
static const XMLCh* s_filetype_;
static const XMLCh* s_filesha1_;
static const XMLCh* s_completiontime_;
static const XMLCh* s_precision_;
static const XMLCh* s_byteorder_;
static const XMLCh* s_pairorder_;
static const XMLCh* s_compressionType_;
static const XMLCh* s_precursorintensity_;
static const XMLCh* s_precursorcharge_;
static const XMLCh* s_windowwideness_;
static const XMLCh* s_mslevel_;
static const XMLCh* s_peakscount_;
static const XMLCh* s_polarity_;
static const XMLCh* s_scantype_;
static const XMLCh* s_filterline_;
static const XMLCh* s_retentiontime_;
static const XMLCh* s_startmz_;
static const XMLCh* s_endmz_;
static const XMLCh* s_first_;
static const XMLCh* s_last_;
static const XMLCh* s_phone_;
static const XMLCh* s_email_;
static const XMLCh* s_uri_;
static const XMLCh* s_num_;
static const XMLCh* s_intensitycutoff_;
static const XMLCh* s_centroided_;
static const XMLCh* s_deisotoped_;
static const XMLCh* s_chargedeconvoluted_;
// init all the static members, which is necessary because otherwise the undefined order will cause problems
void initStaticMembers_()
{
static bool init(false);
if (!init)
{
s_value_ = xercesc::XMLString::transcode("value");
s_count_ = xercesc::XMLString::transcode("scanCount");
s_type_ = xercesc::XMLString::transcode("type");
s_name_ = xercesc::XMLString::transcode("name");
s_version_ = xercesc::XMLString::transcode("version");
s_filename_ = xercesc::XMLString::transcode("fileName");
s_filetype_ = xercesc::XMLString::transcode("fileType");
s_filesha1_ = xercesc::XMLString::transcode("fileSha1");
s_completiontime_ = xercesc::XMLString::transcode("completionTime");
s_precision_ = xercesc::XMLString::transcode("precision");
s_byteorder_ = xercesc::XMLString::transcode("byteOrder");
s_pairorder_ = xercesc::XMLString::transcode("pairOrder");
s_compressionType_ = xercesc::XMLString::transcode("compressionType");
s_precursorintensity_ = xercesc::XMLString::transcode("precursorIntensity");
s_precursorcharge_ = xercesc::XMLString::transcode("precursorCharge");
s_windowwideness_ = xercesc::XMLString::transcode("windowWideness");
s_mslevel_ = xercesc::XMLString::transcode("msLevel");
s_peakscount_ = xercesc::XMLString::transcode("peaksCount");
s_polarity_ = xercesc::XMLString::transcode("polarity");
s_scantype_ = xercesc::XMLString::transcode("scanType");
s_filterline_ = xercesc::XMLString::transcode("filterLine");
s_retentiontime_ = xercesc::XMLString::transcode("retentionTime");
s_startmz_ = xercesc::XMLString::transcode("startMz");
s_endmz_ = xercesc::XMLString::transcode("endMz");
s_first_ = xercesc::XMLString::transcode("first");
s_last_ = xercesc::XMLString::transcode("last");
s_phone_ = xercesc::XMLString::transcode("phone");
s_email_ = xercesc::XMLString::transcode("email");
s_uri_ = xercesc::XMLString::transcode("URI");
s_num_ = xercesc::XMLString::transcode("num");
s_intensitycutoff_ = xercesc::XMLString::transcode("intensityCutoff");
s_centroided_ = xercesc::XMLString::transcode("centroided");
s_deisotoped_ = xercesc::XMLString::transcode("deisotoped");
s_chargedeconvoluted_ = xercesc::XMLString::transcode("chargeDeconvoluted");
init = true;
}
return;
}
};
//--------------------------------------------------------------------------------
// this cannot be moved into a function as VS2008 does not allow more than 31 static members in a function .. don't ask...
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_value_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_count_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_type_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_name_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_version_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_filename_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_filetype_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_filesha1_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_completiontime_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_precision_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_byteorder_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_pairorder_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_compressionType_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_precursorintensity_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_precursorcharge_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_windowwideness_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_mslevel_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_peakscount_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_polarity_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_scantype_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_filterline_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_retentiontime_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_startmz_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_endmz_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_first_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_last_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_phone_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_email_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_uri_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_num_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_intensitycutoff_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_centroided_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_deisotoped_ = 0;
template <typename MapType>
const XMLCh * MzXMLHandler<MapType>::s_chargedeconvoluted_ = 0;
template <typename MapType>
void MzXMLHandler<MapType>::startElement(const XMLCh* const /*uri*/,
const XMLCh* const /*local_name*/, const XMLCh* const qname,
const xercesc::Attributes& attributes)
{
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
static bool init_static_members(false);
if (!init_static_members)
{
initStaticMembers_();
}
String tag = sm_.convert(qname);
open_tags_.push_back(tag);
//std::cout << " -- Start -- "<< tag << " -- " << "\n";
//Skip all tags until the the next scan
if (skip_spectrum_ && tag != "scan")
return;
if (tag == "msRun")
{
Int count = 0;
optionalAttributeAsInt_(count, attributes, s_count_);
exp_->reserve(count);
logger_.startProgress(0, count, "loading mzXML file");
scan_count_ = 0;
data_processing_.clear();
//start and end time are xs:duration. This makes no sense => ignore them
}
else if (tag == "parentFile")
{
SourceFile sf;
sf.setNameOfFile(attributeAsString_(attributes, s_filename_));
sf.setFileType(attributeAsString_(attributes, s_filetype_));
sf.setChecksum(attributeAsString_(attributes, s_filesha1_), SourceFile::SHA1);
exp_->getSourceFiles().push_back(sf);
}
else if (tag == "software")
{
String& parent_tag = *(open_tags_.end() - 2);
if (parent_tag == "dataProcessing")
{
data_processing_.back()->getSoftware().setVersion(attributeAsString_(attributes, s_version_));
data_processing_.back()->getSoftware().setName(attributeAsString_(attributes, s_name_));
data_processing_.back()->setMetaValue("#type", String(attributeAsString_(attributes, s_type_)));
String time;
optionalAttributeAsString_(time, attributes, s_completiontime_);
data_processing_.back()->setCompletionTime(asDateTime_(time));
}
else if (parent_tag == "msInstrument")
{
exp_->getInstrument().getSoftware().setVersion(attributeAsString_(attributes, s_version_));
exp_->getInstrument().getSoftware().setName(attributeAsString_(attributes, s_name_));
}
}
else if (tag == "peaks")
{
//precision
spectrum_data_.back().precision_ = "32";
optionalAttributeAsString_(spectrum_data_.back().precision_, attributes, s_precision_);
if (spectrum_data_.back().precision_ != "32" && spectrum_data_.back().precision_ != "64")
{
error(LOAD, String("Invalid precision '") + spectrum_data_.back().precision_ + "' in element 'peaks'");
}
//byte order
String byte_order = "network";
optionalAttributeAsString_(byte_order, attributes, s_byteorder_);
if (byte_order != "network")
{
error(LOAD, String("Invalid or missing byte order '") + byte_order + "' in element 'peaks'. Must be 'network'!");
}
//pair order
String pair_order = "m/z-int";
optionalAttributeAsString_(pair_order, attributes, s_pairorder_);
if (pair_order != "m/z-int")
{
error(LOAD, String("Invalid or missing pair order '") + pair_order + "' in element 'peaks'. Must be 'm/z-int'!");
}
//compressionType
spectrum_data_.back().compressionType_ = "none";
optionalAttributeAsString_(spectrum_data_.back().compressionType_, attributes, s_compressionType_);
if (spectrum_data_.back().compressionType_ != "none" && spectrum_data_.back().compressionType_ != "zlib")
{
error(LOAD, String("Invalid compression type ") + spectrum_data_.back().compressionType_ + "in elements 'peaks'. Must be 'none' or 'zlib'! ");
}
}
else if (tag == "precursorMz")
{
//add new precursor
spectrum_data_.back().spectrum.getPrecursors().push_back(Precursor());
//intensity
try
{
spectrum_data_.back().spectrum.getPrecursors().back().setIntensity(attributeAsDouble_(attributes, s_precursorintensity_));
}
catch (Exception::ParseError& /*e*/)
{
error(LOAD, "Mandatory attribute 'precursorIntensity' of tag 'precursorMz' not found! Setting precursor intensity to zero!");
}
//charge
Int charge = 0;
if (optionalAttributeAsInt_(charge, attributes, s_precursorcharge_))
{
spectrum_data_.back().spectrum.getPrecursors().back().setCharge(charge);
}
//window bounds (here only the width is stored in both fields - this is corrected when we parse the m/z position)
double window = 0.0;
if (optionalAttributeAsDouble_(window, attributes, s_windowwideness_))
{
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowLowerOffset(window);
}
}
else if (tag == "scan")
{
skip_spectrum_ = false;
nesting_level_++;
if (options_.getMetadataOnly())
throw EndParsingSoftly(__FILE__, __LINE__, __PRETTY_FUNCTION__);
// check if the scan is in the desired MS / RT range
UInt ms_level = attributeAsInt_(attributes, s_mslevel_);
if (ms_level == 0)
{
warning(LOAD, String("Invalid 'msLevel' attribute with value '0' in 'scan' element found. Assuming ms level 1!"));
ms_level = 1;
}
//parse retention time and convert it from xs:duration to seconds
double retention_time = 0.0;
String time_string = "";
if (optionalAttributeAsString_(time_string, attributes, s_retentiontime_))
{
time_string = time_string.suffix('T');
//std::cout << "Initial trim: " << time_string << "\n";
if (time_string.has('H'))
{
retention_time += 3600 * asDouble_(time_string.prefix('H'));
time_string = time_string.suffix('H');
//std::cout << "After H: " << time_string << "\n";
}
if (time_string.has('M'))
{
retention_time += 60 * asDouble_(time_string.prefix('M'));
time_string = time_string.suffix('M');
//std::cout << "After M: " << time_string << "\n";
}
if (time_string.has('S'))
{
retention_time += asDouble_(time_string.prefix('S'));
time_string = time_string.suffix('S');
//std::cout << "After S: " << time_string << "\n";
}
}
logger_.setProgress(scan_count_);
if ((options_.hasRTRange() && !options_.getRTRange().encloses(DPosition<1>(retention_time)))
|| (options_.hasMSLevels() && !options_.containsMSLevel(ms_level))
|| options_.getSizeOnly())
{
// skip this tag
skip_spectrum_ = true;
++scan_count_;
return;
}
// Add a new spectrum, initialize and set MS level and RT
spectrum_data_.resize(spectrum_data_.size() + 1); // TODO !!
spectrum_data_.back().peak_count_ = 0;
spectrum_data_.back().spectrum.setMSLevel(ms_level);
spectrum_data_.back().spectrum.setRT(retention_time);
spectrum_data_.back().spectrum.setNativeID(String("scan=") + attributeAsString_(attributes, s_num_));
//peak count == twice the scan size
spectrum_data_.back().peak_count_ = attributeAsInt_(attributes, s_peakscount_);
spectrum_data_.back().spectrum.reserve(spectrum_data_.back().peak_count_ / 2 + 1);
spectrum_data_.back().spectrum.setDataProcessing(data_processing_);
//centroided, chargeDeconvoluted, deisotoped, collisionEnergy are ignored
//other optional attributes
ScanWindow window;
optionalAttributeAsDouble_(window.begin, attributes, s_startmz_);
optionalAttributeAsDouble_(window.end, attributes, s_endmz_);
if (window.begin != 0.0 || window.end != 0.0)
{
spectrum_data_.back().spectrum.getInstrumentSettings().getScanWindows().push_back(window);
}
String polarity = "any";
optionalAttributeAsString_(polarity, attributes, s_polarity_);
spectrum_data_.back().spectrum.getInstrumentSettings().setPolarity((IonSource::Polarity) cvStringToEnum_(0, polarity, "polarity"));
// Filter string (see CV term MS:1000512 in mzML)
String filterLine = "";
optionalAttributeAsString_(filterLine, attributes, s_filterline_);
if (!filterLine.empty())
{
spectrum_data_.back().spectrum.setMetaValue("filter string", filterLine);
}
String type = "";
optionalAttributeAsString_(type, attributes, s_scantype_);
if (type == "")
{
//unknown/unset => do nothing here => no warning in the end
}
else if (type == "zoom")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setZoomScan(true);
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else if (type == "Full")
{
if (ms_level > 1)
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MSNSPECTRUM);
else
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else if (type == "SIM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::SIM);
}
else if (type == "SRM" || type == "MRM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::SRM);
}
else if (type == "CRM")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::CRM);
}
else if (type == "Q1")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else if (type == "Q3")
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else if (type == "EMS") //Non-standard type: Enhanced MS (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else if (type == "EPI") //Non-standard type: Enhanced Product Ion (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
spectrum_data_.back().spectrum.setMSLevel(2);
}
else if (type == "ER") // Non-standard type: Enhanced Resolution (ABI - Sashimi converter)
{
spectrum_data_.back().spectrum.getInstrumentSettings().setZoomScan(true);
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
}
else
{
spectrum_data_.back().spectrum.getInstrumentSettings().setScanMode(InstrumentSettings::MASSSPECTRUM);
warning(LOAD, String("Unknown scan mode '") + type + "'. Assuming full scan");
}
++scan_count_;
}
else if (tag == "operator")
{
exp_->getContacts().resize(1);
exp_->getContacts().back().setFirstName(attributeAsString_(attributes, s_first_));
exp_->getContacts().back().setLastName(attributeAsString_(attributes, s_last_));
String tmp = "";
optionalAttributeAsString_(tmp, attributes, s_email_);
exp_->getContacts().back().setEmail(tmp);
tmp = "";
optionalAttributeAsString_(tmp, attributes, s_phone_);
if (tmp != "")
{
exp_->getContacts().back().setMetaValue("#phone", tmp);
}
tmp = "";
optionalAttributeAsString_(tmp, attributes, s_uri_);
exp_->getContacts().back().setURL(tmp);
}
else if (tag == "msManufacturer")
{
exp_->getInstrument().setVendor(attributeAsString_(attributes, s_value_));
}
else if (tag == "msModel")
{
exp_->getInstrument().setModel(attributeAsString_(attributes, s_value_));
}
else if (tag == "msIonisation")
{
exp_->getInstrument().getIonSources().resize(1);
exp_->getInstrument().getIonSources()[0].setIonizationMethod((IonSource::IonizationMethod) cvStringToEnum_(2, attributeAsString_(attributes, s_value_), "msIonization"));
}
else if (tag == "msMassAnalyzer")
{
exp_->getInstrument().getMassAnalyzers().resize(1);
exp_->getInstrument().getMassAnalyzers()[0].setType((MassAnalyzer::AnalyzerType) cvStringToEnum_(3, attributeAsString_(attributes, s_value_), "msMassAnalyzer"));
}
else if (tag == "msDetector")
{
exp_->getInstrument().getIonDetectors().resize(1);
exp_->getInstrument().getIonDetectors()[0].setType((IonDetector::Type) cvStringToEnum_(4, attributeAsString_(attributes, s_value_), "msDetector"));
}
else if (tag == "msResolution")
{
exp_->getInstrument().getMassAnalyzers()[0].setResolutionMethod((MassAnalyzer::ResolutionMethod) cvStringToEnum_(5, attributeAsString_(attributes, s_value_), "msResolution"));
}
else if (tag == "dataProcessing")
{
data_processing_.push_back( DataProcessingPtr(new DataProcessing));
String boolean = "";
optionalAttributeAsString_(boolean, attributes, s_deisotoped_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::DEISOTOPING);
}
boolean = "";
optionalAttributeAsString_(boolean, attributes, s_chargedeconvoluted_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::CHARGE_DECONVOLUTION);
}
double cutoff = 0.0;
optionalAttributeAsDouble_(cutoff, attributes, s_intensitycutoff_);
if (cutoff != 0.0)
{
data_processing_.back()->setMetaValue("#intensity_cutoff", cutoff);
}
boolean = "";
optionalAttributeAsString_(boolean, attributes, s_centroided_);
if (boolean == "true" || boolean == "1")
{
data_processing_.back()->getProcessingActions().insert(DataProcessing::PEAK_PICKING);
}
}
else if (tag == "nameValue")
{
String name = "";
optionalAttributeAsString_(name, attributes, s_name_);
if (name == "")
return;
String value = "";
optionalAttributeAsString_(value, attributes, s_value_);
String& parent_tag = *(open_tags_.end() - 2);
if (parent_tag == "msInstrument")
{
exp_->getInstrument().setMetaValue(name, value);
}
else if (parent_tag == "scan")
{
spectrum_data_.back().spectrum.setMetaValue(name, value);
}
else
{
std::cout << " Warning: Unexpected tag 'nameValue' in tag '" << parent_tag << "'" << "\n";
}
}
else if (tag == "processingOperation")
{
String name = "";
optionalAttributeAsString_(name, attributes, s_name_);
if (name == "")
return;
String value = "";
optionalAttributeAsString_(value, attributes, s_value_);
data_processing_.back()->setMetaValue(name, value);
}
//std::cout << " -- !Start -- " << "\n";
}
template <typename MapType>
void MzXMLHandler<MapType>::endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname)
{
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
//std::cout << " -- End -- " << sm_.convert(qname) << " -- " << "\n";
static const XMLCh* s_mzxml = xercesc::XMLString::transcode("mzXML");
static const XMLCh* s_scan = xercesc::XMLString::transcode("scan");
open_tags_.pop_back();
if (equal_(qname, s_mzxml))
{
// Flush the remaining data
populateSpectraWithData_();
// End of mzXML
logger_.endProgress();
}
else if (equal_(qname, s_scan))
{
// End of scan: go up one nesting level
// Check whether to populate spectra when on highest nesting level
nesting_level_--;
OPENMS_PRECONDITION(nesting_level_ >= 0, "Nesting level needs to be zero or more")
if (nesting_level_ == 0 && spectrum_data_.size() >= options_.getMaxDataPoolSize())
{
populateSpectraWithData_();
}
}
//std::cout << " -- End -- " << "\n";
sm_.clear();
}
template <typename MapType>
void MzXMLHandler<MapType>::characters(const XMLCh* const chars, const XMLSize_t length)
{
//Abort if this spectrum should be skipped
if (skip_spectrum_)
return;
if (open_tags_.back() == "peaks")
{
//chars may be split to several chunks => concatenate them
if (options_.getFillData())
{
// Since we convert a Base64 string here, it can only contain plain ASCII
sm_.appendASCII(chars, length, spectrum_data_.back().char_rest_);
}
}
else if (open_tags_.back() == "offset" || open_tags_.back() == "indexOffset" || open_tags_.back() == "sha1")
{
}
else if (open_tags_.back() == "precursorMz")
{
char* transcoded_chars = sm_.convert(chars);
double mz_pos = asDouble_(transcoded_chars);
//precursor m/z
spectrum_data_.back().spectrum.getPrecursors().back().setMZ(mz_pos);
//update window bounds - center them around the m/z pos
double window_width = spectrum_data_.back().spectrum.getPrecursors().back().getIsolationWindowLowerOffset();
if (window_width != 0.0)
{
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowLowerOffset(0.5 * window_width);
spectrum_data_.back().spectrum.getPrecursors().back().setIsolationWindowUpperOffset(0.5 * window_width);
}
}
else if (open_tags_.back() == "comment")
{
char* transcoded_chars = sm_.convert(chars);
String parent_tag = *(open_tags_.end() - 2);
//std::cout << "- Comment of parent " << parent_tag << "\n";
if (parent_tag == "msInstrument")
{
exp_->getInstrument().setMetaValue("#comment", String(transcoded_chars));
}
else if (parent_tag == "dataProcessing")
{
//this is currently ignored
}
else if (parent_tag == "scan")
{
spectrum_data_.back().spectrum.setComment(transcoded_chars);
}
else if (String(transcoded_chars).trim() != "")
{
warning(LOAD, String("Unhandled comment '") + transcoded_chars + "' in element '" + open_tags_.back() + "'");
}
}
else
{
char* transcoded_chars = sm_.convert(chars);
if (String(transcoded_chars).trim() != "")
{
warning(LOAD, String("Unhandled character content '") + transcoded_chars + "' in element '" + open_tags_.back() + "'");
}
}
}
template <typename MapType>
void MzXMLHandler<MapType>::writeTo(std::ostream& os)
{
//determine how many spectra there are (count only those with peaks)
UInt count_tmp_ = 0;
for (Size s = 0; s < cexp_->size(); s++)
{
const SpectrumType& spec = (*cexp_)[s];
if (spec.size() != 0)
++count_tmp_;
}
if (count_tmp_ == 0)
++count_tmp_;
logger_.startProgress(0, cexp_->size(), "storing mzXML file");
os << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
<< "<mzXML xmlns=\"http://sashimi.sourceforge.net/schema_revision/mzXML_2.1\" "
<< "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
<< "xsi:schemaLocation=\"http://sashimi.sourceforge.net/schema_revision/mzXML_2.1 "
<< "http://sashimi.sourceforge.net/schema_revision/mzXML_2.1/mzXML_idx_2.1.xsd\">\n"
<< "\t<msRun scanCount=\"" << count_tmp_ << "\">\n";
//----------------------------------------------------------------------------------------
// parent files
//----------------------------------------------------------------------------------------
if (cexp_->getSourceFiles().empty())
{
os << "\t\t<parentFile fileName=\"\" fileType=\"processedData\" fileSha1=\"0000000000000000000000000000000000000000\"/>\n";
}
else
{
for (Size i = 0; i < cexp_->getSourceFiles().size(); ++i)
{
const SourceFile& sf = cexp_->getSourceFiles()[i];
os << "\t\t<parentFile fileName=\"" << sf.getNameOfFile() << "\" fileType=\"";
//file type is an enum in mzXML => search for 'raw' string
String tmp_string = sf.getFileType();
tmp_string.toLower();
if (tmp_string.hasSubstring("raw"))
{
os << "RAWData";
}
else
{
os << "processedData";
}
//Sha1 checksum must have 40 characters => create a fake if it is unknown
os << "\" fileSha1=\"";
tmp_string = sf.getChecksum();
if (sf.getChecksum().size() != 40 || sf.getChecksumType() != SourceFile::SHA1)
{
os << "0000000000000000000000000000000000000000";
}
else
{
os << sf.getChecksum();
}
os << "\"/>\n";
}
}
//----------------------------------------------------------------------------------------
//instrument
//----------------------------------------------------------------------------------------
if (cexp_->getInstrument() != Instrument() || cexp_->getContacts().size() != 0)
{
const Instrument& inst = cexp_->getInstrument();
os << "\t\t<msInstrument>\n"
<< "\t\t\t<msManufacturer category=\"msManufacturer\" value=\"" << inst.getVendor() << "\"/>\n" << "\t\t\t<msModel category=\"msModel\" value=\"" << inst.getModel() << "\"/>\n";
if (inst.getIonSources().empty() || !inst.getIonSources()[0].getIonizationMethod())
{
os << "\t\t\t<msIonisation category=\"msIonisation\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msIonisation category=\"msIonisation\" value=\"" << cv_terms_[2][inst.getIonSources()[0].getIonizationMethod()] << "\"/>\n";
}
const std::vector<MassAnalyzer>& analyzers = inst.getMassAnalyzers();
if (analyzers.empty() || !analyzers[0].getResolutionMethod())
{
os << "\t\t\t<msMassAnalyzer category=\"msMassAnalyzer\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msMassAnalyzer category=\"msMassAnalyzer\" value=\"" << cv_terms_[3][analyzers[0].getType()] << "\"/>\n";
}
if (inst.getIonDetectors().empty() || !inst.getIonDetectors()[0].getType())
{
os << "\t\t\t<msDetector category=\"msDetector\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msDetector category=\"msDetector\" value=\"" << cv_terms_[4][inst.getIonDetectors()[0].getType()] << "\"/>\n";
}
os << "\t\t\t<software type=\"acquisition\" name=\"" << inst.getSoftware().getName() << "\" version=\"" << inst.getSoftware().getVersion() << "\"/>\n";
if (analyzers.empty() || !analyzers[0].getResolutionMethod())
{
os << "\t\t\t<msResolution category=\"msResolution\" value=\"\"/>\n";
}
else
{
os << "\t\t\t<msResolution category=\"msResolution\" value=\"" << cv_terms_[5][analyzers[0].getResolutionMethod()] << "\"/>\n";
}
if (cexp_->getContacts().size() > 0)
{
const ContactPerson& cont = cexp_->getContacts()[0];
os << "\t\t\t<operator first=\"" << cont.getFirstName() << "\" last=\"" << cont.getLastName() << "\"";
if (cont.getEmail() != "")
{
os << " email=\"" << cont.getEmail() << "\"";
}
if (cont.getURL() != "")
{
os << " URI=\"" << cont.getURL() << "\"";
}
if (cont.metaValueExists("#phone"))
{
os << " phone=\"" << writeXMLEscape(cont.getMetaValue("#phone").toString()) << "\"";
}
os << "/>\n";
}
writeUserParam_(os, inst, 3);
if (inst.metaValueExists("#comment"))
{
os << "\t\t\t<comment>" << writeXMLEscape(inst.getMetaValue("#comment")) << "</comment>\n";
}
os << "\t\t</msInstrument>\n";
}
//----------------------------------------------------------------------------------------
//data processing (the information of the first spectrum is assigned to the whole file)
//----------------------------------------------------------------------------------------
if (cexp_->size() == 0 || (*cexp_)[0].getDataProcessing().empty())
{
os << "\t\t<dataProcessing>\n"
<< "\t\t\t<software type=\"processing\" name=\"\" version=\"\"/>\n"
<< "\t\t</dataProcessing>\n";
}
else
{
for (Size i = 0; i < (*cexp_)[0].getDataProcessing().size(); ++i)
{
const DataProcessing& data_processing = * (*cexp_)[0].getDataProcessing()[i].get();
os << "\t\t<dataProcessing deisotoped=\""
<< data_processing.getProcessingActions().count(DataProcessing::DEISOTOPING)
<< "\" chargeDeconvoluted=\""
<< data_processing.getProcessingActions().count(DataProcessing::CHARGE_DECONVOLUTION)
<< "\" centroided=\""
<< data_processing.getProcessingActions().count(DataProcessing::PEAK_PICKING)
<< "\"";
if (data_processing.metaValueExists("#intensity_cutoff"))
{
os << " intensityCutoff=\"" << writeXMLEscape(data_processing.getMetaValue("#intensity_cutoff").toString()) << "\"";
}
os << ">\n"
<< "\t\t\t<software type=\"";
if (data_processing.metaValueExists("#type"))
{
os << writeXMLEscape(data_processing.getMetaValue("#type").toString());
}
else
{
os << "processing";
}
os << "\" name=\"" << data_processing.getSoftware().getName()
<< "\" version=\"" << data_processing.getSoftware().getVersion();
if (data_processing.getCompletionTime() != DateTime())
{
os << "\" completionTime=\"" << data_processing.getCompletionTime().get().substitute(' ', 'T');
}
os << "\"/>\n";
writeUserParam_(os, data_processing, 3, "processingOperation");
os << "\t\t</dataProcessing>\n";
}
}
//check if the nativeID of all spectra are numbers or numbers prefixed with 'scan='
//If not we need to renumber all spectra.
bool all_numbers = true;
bool all_empty = true;
bool all_prefixed_numbers = true;
for (Size s = 0; s < cexp_->size(); s++)
{
String native_id = (*cexp_)[s].getNativeID();
if (!native_id.hasPrefix("scan="))
{
all_prefixed_numbers = false;
}
else
{
native_id = native_id.substr(5);
}
try
{
native_id.toInt();
}
catch (Exception::ConversionError&)
{
all_numbers = false;
all_prefixed_numbers = false;
if (native_id != "")
{
all_empty = false;
}
}
}
//If we need to renumber and the nativeIDs were not empty, warn the user
if (!all_numbers && !all_empty)
{
warning(STORE, "Not all spectrum native IDs are numbers or correctly prefixed with 'scan='. The spectra are renumbered and the native IDs are lost!");
}
// write scans
std::stack<UInt> open_scans;
for (Size s = 0; s < cexp_->size(); s++)
{
logger_.setProgress(s);
const SpectrumType& spec = (*cexp_)[s];
UInt ms_level = spec.getMSLevel();
open_scans.push(ms_level);
Size spectrum_id = s + 1;
if (all_prefixed_numbers)
{
spectrum_id = spec.getNativeID().substr(5).toInt();
}
else if (all_numbers)
{
spectrum_id = spec.getNativeID().toInt();
}
os << String(ms_level + 1, '\t')
<< "<scan num=\"" << spectrum_id << "\" msLevel=\""
<< ms_level << "\" peaksCount=\""
<< spec.size() << "\" polarity=\"";
if (spec.getInstrumentSettings().getPolarity() == IonSource::POSITIVE)
{
os << "+";
}
else if (spec.getInstrumentSettings().getPolarity() == IonSource::NEGATIVE)
{
os << "-";
}
else
{
os << "any";
}
//scan type
switch (spec.getInstrumentSettings().getScanMode())
{
case InstrumentSettings::UNKNOWN:
break;
case InstrumentSettings::MASSSPECTRUM:
case InstrumentSettings::MS1SPECTRUM:
case InstrumentSettings::MSNSPECTRUM:
if (spec.getInstrumentSettings().getZoomScan())
{
os << "\" scanType=\"zoom";
}
else
{
os << "\" scanType=\"Full";
}
break;
case InstrumentSettings::SIM:
os << "\" scanType=\"SIM";
break;
case InstrumentSettings::SRM:
os << "\" scanType=\"SRM";
break;
case InstrumentSettings::CRM:
os << "\" scanType=\"CRM";
break;
default:
os << "\" scanType=\"Full";
warning(STORE, String("Scan type '") + InstrumentSettings::NamesOfScanMode[spec.getInstrumentSettings().getScanMode()] + "' not supported by mzXML. Using 'Full' scan mode!");
}
// filter line
if (spec.metaValueExists("filter string") )
{
os << "\" filterLine=\"";
os << writeXMLEscape ( (String)spec.getMetaValue("filter string") );
}
// base peak mz (used by some programs like MAVEN), according to xsd:
// "m/z of the base peak (most intense peak)"
os << "\" basePeakMz=\"";
double basePeakInt = 0;
double basePeakMz = 0;
for (Size j = 0; j < spec.size(); j++)
{
if (spec[j].getIntensity() > basePeakInt)
{
basePeakInt = spec[j].getIntensity();
basePeakMz = spec[j].getMZ();
}
}
os << basePeakMz;
// retention time
os << "\" retentionTime=\"";
if (spec.getRT() < 0)
os << "-";
os << "PT" << std::fabs(spec.getRT()) << "S\"";
if (!spec.getInstrumentSettings().getScanWindows().empty())
{
os << " startMz=\"" << spec.getInstrumentSettings().getScanWindows()[0].begin << "\" endMz=\"" << spec.getInstrumentSettings().getScanWindows()[0].end << "\"";
}
if (spec.getInstrumentSettings().getScanWindows().size() > 1)
{
warning(STORE, "The MzXML format can store only one scan window for each scan. Only the first one is stored!");
}
// end of "scan" attributes
os << ">\n";
for (Size i = 0; i < spec.getPrecursors().size(); ++i)
{
const Precursor& precursor = spec.getPrecursors()[i];
//intensity
os << String(ms_level + 2, '\t') << "<precursorMz precursorIntensity=\"" << precursor.getIntensity();
//charge
if (precursor.getCharge() != 0)
os << "\" precursorCharge=\"" << precursor.getCharge();
//window size
if (precursor.getIsolationWindowLowerOffset() + precursor.getIsolationWindowUpperOffset() > 0.0)
os << "\" windowWideness=\"" << (precursor.getIsolationWindowUpperOffset() + precursor.getIsolationWindowLowerOffset());
//m/z
os << "\">" << precursor.getMZ() << "</precursorMz>\n";
}
if (!spec.empty())
{
os << String(ms_level + 2, '\t') << "<peaks precision=\"32\"" << " byteOrder=\"network\" pairOrder=\"m/z-int\">";
//std::cout << "Writing scan " << s << "\n";
std::vector<float> tmp;
for (Size i = 0; i < spec.size(); i++)
{
tmp.push_back(spec[i].getMZ());
tmp.push_back(spec[i].getIntensity());
}
String encoded;
decoder_.encode(tmp, Base64::BYTEORDER_BIGENDIAN, encoded);
os << encoded << "</peaks>\n";
}
else
{
os << String(ms_level + 2, '\t') << "<peaks precision=\"32\"" << " byteOrder=\"network\" pairOrder=\"m/z-int\" xsi:nil=\"true\"/>\n";
}
writeUserParam_(os, spec, ms_level + 2);
if (spec.getComment() != "")
{
os << String(ms_level + 2, '\t') << "<comment>" << spec.getComment() << "</comment>\n";
}
//check MS level of next scan and close scans (scans can be nested)
UInt next_ms_level = 0;
if (s < cexp_->size() - 1)
{
next_ms_level = ((*cexp_)[s + 1]).getMSLevel();
}
//std::cout << "scan: " << s << " this: " << ms_level << " next: " << next_ms_level << "\n";
if (next_ms_level <= ms_level)
{
for (Size i = 0; i <= ms_level - next_ms_level && !open_scans.empty(); ++i)
{
os << String(ms_level - i + 1, '\t') << "</scan>\n";
open_scans.pop();
}
}
}
os << "\t</msRun>\n"
<< "\t<indexOffset>0</indexOffset>\n"
<< "</mzXML>\n";
logger_.endProgress();
spec_write_counter_ = 1;
}
} // namespace Internal
} // namespace OpenMS
#endif
|
filtering_openmesh.h | #pragma once
#include <omp.h>
#include <queue>
#include "../common/openmesh_report.h"
#include "../common/openmesh_trimesh.h"
#include "rxmesh/rxmesh_attribute.h"
/**
*computeSigma_s()
*/
double computeSigma_s(
const std::vector<TriMesh::VertexHandle>& vertex_neighbour,
const TriMesh& mesh,
const TriMesh::Point pi,
const TriMesh::Normal ni)
{
float offset = 0;
float sum = 0;
float sum_sqs = 0;
size_t count = vertex_neighbour.size();
for (size_t i = 0; i < count; ++i) {
TriMesh::Point pj = mesh.point(vertex_neighbour[i]);
float t = (pj - pi) | ni;
t = sqrt(t * t);
sum += t;
sum_sqs += t * t;
}
float c = static_cast<float>(count);
offset = (sum_sqs / c) - ((sum * sum) / (c * c));
float sigma_s =
(sqrt(offset) < 1.0e-12) ? (sqrt(offset) + 1.0e-12) : sqrt(offset);
return sigma_s;
}
/**
* getAdaptiveVertexNeighbor()
*/
void getAdaptiveVertexNeighbor(
TriMesh& mesh,
TriMesh::VertexHandle vh,
float sigma_c,
std::vector<TriMesh::VertexHandle>& vertex_neighbor)
{
std::vector<bool> mark(mesh.n_vertices(), false);
vertex_neighbor.clear();
std::queue<TriMesh::VertexHandle> queue_vertex_handle;
mark[vh.idx()] = true;
queue_vertex_handle.push(vh);
float radius = 2.0 * sigma_c;
TriMesh::Point ci = mesh.point(vh);
while (!queue_vertex_handle.empty()) {
TriMesh::VertexHandle vh = queue_vertex_handle.front();
vertex_neighbor.push_back(vh);
queue_vertex_handle.pop();
for (TriMesh::VertexVertexIter vv_it = mesh.vv_iter(vh);
vv_it.is_valid(); ++vv_it) {
TriMesh::VertexHandle vh_neighbor = *vv_it;
if (mark[vh_neighbor.idx()] == false) {
TriMesh::Point cj = mesh.point(vh_neighbor);
float length = (cj - ci).length();
if (length <= radius)
queue_vertex_handle.push(vh_neighbor);
mark[vh_neighbor.idx()] = true;
}
}
}
}
template <typename T>
void filtering_openmesh(const int num_omp_threads,
TriMesh& input_mesh,
RXMESH::RXMeshAttribute<T>& filtered_coord,
size_t& max_neighbour_size)
{
// Report
OpenMeshReport report("Filtering_OpenMesh");
report.command_line(Arg.argc, Arg.argv);
report.system();
report.model_data(Arg.obj_file_name, input_mesh);
std::string method =
"OpenMesh " + std::to_string(num_omp_threads) + " Core";
report.add_member("method", method);
std::string order = "default";
if (Arg.shuffle) {
order = "shuffle";
} else if (Arg.sort) {
order = "sorted";
}
report.add_member("input_order", order);
report.add_member("num_filter_iter", Arg.num_filter_iter);
// Allocate space for the filtered output coordinates
filtered_coord.init(input_mesh.n_vertices(), 3u, RXMESH::HOST);
filtered_coord.reset(0.0, RXMESH::HOST);
// this where each thread will store its neighbour vertices
// we allocate enough space such that each thread can store as much
// neighbour vertices as the number of vertices in the mesh.
std::vector<std::vector<TriMesh::VertexHandle>> vertex_neighbour;
for (int i = 0; i < num_omp_threads; ++i) {
std::vector<TriMesh::VertexHandle> vn;
vn.reserve(input_mesh.n_vertices());
vertex_neighbour.push_back(vn);
}
max_neighbour_size = 0;
RXMESH::CPUTimer timer;
timer.start();
for (uint32_t itr = 0; itr < Arg.num_filter_iter; ++itr) {
input_mesh.request_face_normals();
input_mesh.request_vertex_normals();
input_mesh.update_normals();
const int num_vertrices = static_cast<int>(input_mesh.n_vertices());
#pragma omp parallel for schedule(static) num_threads(num_omp_threads) \
reduction(max \
: max_neighbour_size)
for (int vert = 0; vert < num_vertrices; vert++) {
TriMesh::VertexIter v_it = input_mesh.vertices_begin() + vert;
int tid = omp_get_thread_num();
// calculate sigma_c
TriMesh::Point pi = input_mesh.point(*v_it);
TriMesh::Normal ni = input_mesh.normal(*v_it);
float sigma_c = 1e10;
for (TriMesh::VertexVertexIter vv_it = input_mesh.vv_iter(*v_it);
vv_it.is_valid(); vv_it++) {
TriMesh::Point pj = input_mesh.point(*vv_it);
float length = (pi - pj).length();
if (length < sigma_c) {
sigma_c = length;
}
}
// get the neighbor vertices
vertex_neighbour[tid].clear();
getAdaptiveVertexNeighbor(input_mesh, *v_it, sigma_c,
vertex_neighbour[tid]);
max_neighbour_size =
max(max_neighbour_size, vertex_neighbour[tid].size());
// calculate sigma_s
float sigma_s =
computeSigma_s(vertex_neighbour[tid], input_mesh, pi, ni);
float sum = 0;
float normalizer = 0;
// calculate new vertex position
for (int iv = 0; iv < (int)vertex_neighbour[tid].size(); iv++) {
TriMesh::Point pj = input_mesh.point(vertex_neighbour[tid][iv]);
float t = (pi - pj).length();
float h = (pj - pi) | ni;
float wc = std::exp(-0.5 * t * t / (sigma_c * sigma_c));
float ws = std::exp(-0.5 * h * h / (sigma_s * sigma_s));
sum += wc * ws * h;
normalizer += wc * ws;
}
auto updated_point = pi + ni * (sum / normalizer);
filtered_coord(vert, 0) = updated_point[0];
filtered_coord(vert, 1) = updated_point[1];
filtered_coord(vert, 2) = updated_point[2];
}
// update the mesh for the next iterations (needed to update the
// normals correctly)
#pragma omp parallel for schedule(static) num_threads(num_omp_threads)
for (int vert = 0; vert < num_vertrices; vert++) {
TriMesh::VertexIter v_it = input_mesh.vertices_begin() + vert;
TriMesh::Point p;
p[0] = filtered_coord(vert, 0);
p[1] = filtered_coord(vert, 1);
p[2] = filtered_coord(vert, 2);
input_mesh.set_point(*v_it, p);
}
}
timer.stop();
report.add_member("max_neighbour_size", uint32_t(max_neighbour_size));
RXMESH_TRACE("filtering_openmesh() max_neighbour_size= {}",
max_neighbour_size);
RXMESH_TRACE("filtering_openmesh() took {} (ms) (i.e., {} ms/iter) ",
timer.elapsed_millis(),
timer.elapsed_millis() / float(Arg.num_filter_iter));
// write output
// std::string fn = STRINGIFY(OUTPUT_DIR) "filtering_openmesh.obj";
// if (!OpenMesh::IO::write_mesh(input_mesh, fn)) {
// RXMESH_WARN("OpenMesh cannot write mesh to file {}", fn);
//}
// Finalize report
report.add_member("total_time (ms)", timer.elapsed_millis());
RXMESH::TestData td;
td.test_name = "MCF";
td.num_threads = num_omp_threads;
td.time_ms.push_back(timer.elapsed_millis());
td.passed.push_back(true);
report.add_test(td);
report.write(
Arg.output_folder + "/openmesh",
"MCF_OpenMesh_" + RXMESH::extract_file_name(Arg.obj_file_name));
} |
CALPHADFreeEnergyFunctionsBinaryThreePhase.h | #ifndef included_CALPHADFreeEnergyFunctionsBinaryThreePhase
#define included_CALPHADFreeEnergyFunctionsBinaryThreePhase
#include "CALPHADSpeciesPhaseGibbsEnergy.h"
#include "InterpolationType.h"
#include "Phases.h"
#include "datatypes.h"
#include "functions.h"
#include <boost/property_tree/ptree.hpp>
#include <cassert>
#include <fstream>
#include <iostream>
#include <math.h>
namespace Thermo4PFM
{
class CALPHADFreeEnergyFunctionsBinaryThreePhase
{
public:
CALPHADFreeEnergyFunctionsBinaryThreePhase(
boost::property_tree::ptree& input_db,
boost::optional<boost::property_tree::ptree&> newton_db,
const EnergyInterpolationType energy_interp_func_type,
const ConcInterpolationType conc_interp_func_type);
~CALPHADFreeEnergyFunctionsBinaryThreePhase(){};
double computeFreeEnergy(const double temperature, const double* const conc,
const PhaseIndex pi, const bool gp = false);
void computeDerivFreeEnergy(const double temperature,
const double* const conc, const PhaseIndex pi, double*);
void computeSecondDerivativeFreeEnergy(const double temp,
const double* const conc, const PhaseIndex pi, double* d2fdc2);
bool computeCeqT(const double temperature, double* ceq,
const int maxits = 20, const bool verbose = false);
void preRunDiagnostics(const double T0 = 300., const double T1 = 3000.);
int computePhaseConcentrations(const double temperature, const double* conc,
const double* const phi, double* x);
void energyVsPhiAndC(const double temperature, const double* const ceq,
const bool found_ceq, const double phi_well_scale,
const int npts_phi = 51,
const int npts_c = 50); // # of compositions to use (>1)
void printEnergyVsComposition(
const double temperature, std::ostream& os, const int npts = 100);
double fchem(const double* const phi, const double* const conc,
const double temperature);
void printEnergyVsPhiHeader(const double temperature, const int nphi,
const int nc, const double cmin, const double cmax, const double slopec,
std::ostream& os) const;
void printEnergyVsPhi(const double* const conc, const double temperature,
const double phi_well_scale, const int npts, const double slopec,
std::ostream& os);
void computeTdependentParameters(const double temperature,
CalphadDataType* Lmix_L, CalphadDataType* Lmix_A,
CalphadDataType* Lmix_B, CalphadDataType* fA, CalphadDataType* fB);
private:
EnergyInterpolationType energy_interp_func_type_;
ConcInterpolationType conc_interp_func_type_;
void readNewtonparameters(boost::property_tree::ptree& newton_db);
char* fenergy_diag_filename_;
double newton_tol_;
double newton_alpha_;
int newton_maxits_;
bool newton_verbose_;
// Single species energies in each phase
// size 2 for species 0 and 1
CALPHADSpeciesPhaseGibbsEnergy g_species_phaseL_[2];
CALPHADSpeciesPhaseGibbsEnergy g_species_phaseA_[2];
CALPHADSpeciesPhaseGibbsEnergy g_species_phaseB_[2];
// size 4 for L0, L1, L2, L3,
// can contain up to 3 coefficients a,b,c for a+b*T,
// possibly +c*T*ln(T) if compiled with -DLMIX_WTLOGT
CalphadDataType LmixPhaseL_[4][MAX_POL_T_INDEX];
CalphadDataType LmixPhaseA_[4][MAX_POL_T_INDEX];
CalphadDataType LmixPhaseB_[4][MAX_POL_T_INDEX];
double (*fun_ptr_arr_[3])(const double){ linear_interp_func,
pbg_interp_func, harmonic_interp_func };
void readParameters(boost::property_tree::ptree& calphad_db);
#ifdef HAVE_OPENMP_OFFLOAD
#pragma omp declare target
#endif
// energy of species "is" in phase L,A
double getFenergyPhaseL(const short is, const double temperature)
{
return g_species_phaseL_[is].fenergy(temperature);
}
double getFenergyPhaseA(const short is, const double temperature)
{
return g_species_phaseA_[is].fenergy(temperature);
}
double getFenergyPhaseB(const short is, const double temperature)
{
return g_species_phaseB_[is].fenergy(temperature);
}
CalphadDataType lmixPhase(
const unsigned index, const PhaseIndex pi, const double temperature)
{
// assert(index < 4);
switch (pi)
{
case PhaseIndex::phaseL:
return LmixPhaseL_[index][0]
+ LmixPhaseL_[index][1] * temperature
#ifdef LMIX_WTLOGT
+ LmixPhaseL_[index][2] * temperature * log(temperature)
#endif
;
case PhaseIndex::phaseA:
return LmixPhaseA_[index][0]
+ LmixPhaseA_[index][1] * temperature
#ifdef LMIX_WTLOGT
+ LmixPhaseA_[index][2] * temperature * log(temperature)
#endif
;
case PhaseIndex::phaseB:
return LmixPhaseB_[index][0]
+ LmixPhaseB_[index][1] * temperature
#ifdef LMIX_WTLOGT
+ LmixPhaseB_[index][2] * temperature * log(temperature)
#endif
;
default:
return NAN;
}
}
#ifdef HAVE_OPENMP_OFFLOAD
#pragma omp end declare target
#endif
void computePhasesFreeEnergies(const double temperature,
const double* const hphi, const double conc, double& fl, double& fa,
double& fb);
};
}
#endif
|
task_codegen.c | // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -fopenmp-version=50 -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 -fopenmp-version=50 -x c -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -x c -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -fopenmp-version=50 -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
typedef void *omp_depend_t;
typedef __UINTPTR_TYPE__ omp_event_handle_t;
void foo();
// CHECK-LABEL: @main
int main() {
omp_depend_t d, x;
omp_event_handle_t evt;
int a, *b;
// CHECK: [[D_ADDR:%.+]] = alloca i8*,
// CHECK: [[X_ADDR:%.+]] = alloca i8*,
// CHECK: [[EVT_ADDR:%.+]] = alloca i64,
// CHECK: [[A_ADDR:%.+]] = alloca i32,
// CHECK: [[DEPOBJ_SIZE_ADDR:%.+]] = alloca i64,
// CHECK: [[DEPOBJ_SIZE_ADDR1:%.+]] = alloca i64,
// CHECK: = alloca i64,
// CHECK: [[DEP_COUNTER_ADDR:%.+]] = alloca i64,
// CHECK-DAG: store i64 0, i64* [[DEPOBJ_SIZE_ADDR1]],
// CHECK-DAG: store i64 0, i64* [[DEPOBJ_SIZE_ADDR]],
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(
// CHECK: [[ALLOC:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 [[GTID]], i32 65, i64 48, i64 0, i32 (i32, i8*)* bitcast (i32 (i32, [[PRIVATES_TY:%.+]]*)* [[TASK_ENTRY:@.+]] to i32 (i32, i8*)*))
// CHECK: [[EVT_VAL:%.+]] = call i8* @__kmpc_task_allow_completion_event(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[ALLOC]])
// CHECK: [[CAST_EVT_VAL:%.+]] = ptrtoint i8* [[EVT_VAL]] to i64
// CHECK: store i64 [[CAST_EVT_VAL]], i64* [[EVT_ADDR]],
// CHECK: [[DATA:%.+]] = bitcast i8* [[ALLOC]] to [[PRIVATES_TY]]*
// CHECK: [[D:%.+]] = load i8*, i8** [[D_ADDR]],
// CHECK: [[D_DEP:%.+]] = bitcast i8* [[D]] to %struct.kmp_depend_info*
// CHECK: [[D_DEP_BASE:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[D_DEP]], i{{.+}} -1
// CHECK: [[D_DEP_BASE_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[D_DEP_BASE]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[SIZE1:%.+]] = load i64, i64* [[D_DEP_BASE_SIZE]],
// CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR]],
// CHECK: [[SIZE:%.+]] = add nuw i64 [[SZ]], [[SIZE1]]
// CHECK: store i64 [[SIZE]], i64* [[DEPOBJ_SIZE_ADDR]],
// CHECK: [[X:%.+]] = load i8*, i8** [[X_ADDR]],
// CHECK: [[X_DEP:%.+]] = bitcast i8* [[X]] to %struct.kmp_depend_info*
// CHECK: [[X_DEP_BASE:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[X_DEP]], i{{.+}} -1
// CHECK: [[X_DEP_BASE_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[X_DEP_BASE]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[SIZE2:%.+]] = load i64, i64* [[X_DEP_BASE_SIZE]],
// CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR1]],
// CHECK: [[SIZE3:%.+]] = add nuw i64 [[SZ]], [[SIZE2]]
// CHECK: store i64 [[SIZE3]], i64* [[DEPOBJ_SIZE_ADDR1]],
// CHECK: [[SZ:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR]],
// CHECK: [[SZ1:%.+]] = load i64, i64* [[DEPOBJ_SIZE_ADDR1]],
// CHECK: [[SIZE1:%.+]] = add nuw i64 0, [[SZ]]
// CHECK: [[SIZE2:%.+]] = add nuw i64 [[SIZE1]], [[SZ1]]
// CHECK: [[SIZE:%.+]] = add nuw i64 [[SIZE2]], 2
// CHECK: [[SV:%.+]] = call i8* @llvm.stacksave()
// CHECK: store i8* [[SV]], i8** [[SV_ADDR:%.+]],
// CHECK: [[VLA:%.+]] = alloca %struct.kmp_depend_info, i64 [[SIZE]],
// CHECK: [[SIZE32:%.+]] = trunc i64 [[SIZE]] to i32
// CHECK: [[VLA0:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 0
// CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[A_ADDR_CAST:%.+]] = ptrtoint i32* [[A_ADDR]] to i64
// CHECK: store i64 [[A_ADDR_CAST]], i64* [[BASE_ADDR]],
// CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 1
// CHECK: store i64 4, i64* [[SIZE_ADDR]],
// CHECK: [[FLAGS_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA0]], i{{.+}} 0, i{{.+}} 2
// CHECK: store i8 1, i8* [[FLAGS_ADDR]],
// CHECK: [[A:%.+]] = load i32, i32* [[A_ADDR]],
// CHECK: [[A_CAST:%.+]] = sext i32 [[A]] to i64
// CHECK: [[SZ1:%.+]] = mul nuw i64 24, [[A_CAST]]
// CHECK: [[A:%.+]] = load i32, i32* [[A_ADDR]],
// CHECK: [[A_CAST:%.+]] = sext i32 [[A]] to i64
// CHECK: [[SZ:%.+]] = mul nuw i64 [[SZ1]], [[A_CAST]]
// CHECK: [[VLA1:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 1
// CHECK: [[BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[B_ADDR_CAST:%.+]] = ptrtoint i32** %{{.+}} to i64
// CHECK: store i64 [[B_ADDR_CAST]], i64* [[BASE_ADDR]],
// CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 1
// CHECK: store i64 [[SZ]], i64* [[SIZE_ADDR]],
// CHECK: [[FLAGS_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA1]], i{{.+}} 0, i{{.+}} 2
// CHECK: store i8 1, i8* [[FLAGS_ADDR]],
// CHECK: store i64 2, i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[D:%.+]] = load i8*, i8** [[D_ADDR]],
// CHECK: [[BC:%.+]] = bitcast i8* [[D]] to %struct.kmp_depend_info*
// CHECK: [[PREV:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[BC]], i64 -1
// CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[PREV]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[SIZE:%.+]] = load i64, i64* [[SIZE_ADDR]],
// CHECK: [[BYTES:%.+]] = mul nuw i64 24, [[SIZE]]
// CHECK: [[POS:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[VLA_D:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 [[POS]]
// CHECK: [[DEST:%.+]] = bitcast %struct.kmp_depend_info* [[VLA_D]] to i8*
// CHECK: [[SRC:%.+]] = bitcast %struct.kmp_depend_info* [[BC]] to i8*
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align {{.+}} [[DEST]], i8* align {{.+}} [[SRC]], i64 [[BYTES]], i1 false)
// CHECK: [[ADD:%.+]] = add nuw i64 [[POS]], [[SIZE]]
// CHECK: store i64 [[ADD]], i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[X:%.+]] = load i8*, i8** [[X_ADDR]],
// CHECK: [[BC:%.+]] = bitcast i8* [[X]] to %struct.kmp_depend_info*
// CHECK: [[PREV:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[BC]], i64 -1
// CHECK: [[SIZE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[PREV]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[SIZE:%.+]] = load i64, i64* [[SIZE_ADDR]],
// CHECK: [[BYTES:%.+]] = mul nuw i64 24, [[SIZE]]
// CHECK: [[POS:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[VLA_X:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[VLA]], i64 [[POS]]
// CHECK: [[DEST:%.+]] = bitcast %struct.kmp_depend_info* [[VLA_X]] to i8*
// CHECK: [[SRC:%.+]] = bitcast %struct.kmp_depend_info* [[BC]] to i8*
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align {{.+}} [[DEST]], i8* align {{.+}} [[SRC]], i64 [[BYTES]], i1 false)
// CHECK: [[ADD:%.+]] = add nuw i64 [[POS]], [[SIZE]]
// CHECK: store i64 [[ADD]], i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[BC:%.+]] = bitcast %struct.kmp_depend_info* [[VLA]] to i8*
// CHECK: call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[ALLOC]], i32 [[SIZE32]], i8* [[BC]], i32 0, i8* null)
// CHECK: [[SV:%.+]] = load i8*, i8** [[SV_ADDR]],
// CHECK: call void @llvm.stackrestore(i8* [[SV]])
#pragma omp task depend(in: a, ([3][a][a])&b) depend(depobj: d, x) detach(evt)
{
#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(
// CHECK-LINE: @bar
void bar() {
int **a;
// CHECK: call void @__kmpc_for_static_init_4(
#pragma omp for
for (int i = 0; i < 10; ++i)
// CHECK: [[BUF:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 %{{.+}}, i32 1, i64 48,
// CHECK: [[BC_BUF:%.+]] = bitcast i8* [[BUF]] to [[TT_WITH_PRIVS:%.+]]*
// CHECK: [[PRIVS:%.+]] = getelementptr inbounds [[TT_WITH_PRIVS]], [[TT_WITH_PRIVS]]* [[BC_BUF]], i32 0, i32 1
// CHECK: [[I_PRIV:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}} [[PRIVS]], i32 0, i32 0
// CHECK: [[I:%.+]] = load i32, i32* [[I_ADDR:%.+]],
// CHECK: store i32 %{{.+}}, i32* [[I_PRIV]],
// NELEMS = 1 * ((i - 0 + 2 - 1) / 2);
// CHECK: [[END:%.+]] = load i32, i32* [[I_ADDR]],
// CHECK: [[EB_SUB:%.+]] = sub i32 [[END]], 0
// CHECK: [[EB_SUB_2_ADD:%.+]] = add i32 [[EB_SUB]], 2
// CHECK: [[EB_SUB_2_ADD_1_SUB:%.+]] = sub i32 [[EB_SUB_2_ADD]], 1
// CHECK: [[EB_SUB_2_ADD_1_SUB_2_DIV:%.+]] = udiv i32 [[EB_SUB_2_ADD_1_SUB]], 2
// CHECK: [[ELEMS:%.+]] = zext i32 [[EB_SUB_2_ADD_1_SUB_2_DIV]] to i64
// CHECK: [[NELEMS:%.+]] = mul nuw i64 [[ELEMS]], 1
// ITERATOR_TOTAL = NELEMS + 0;
// CHECK: [[ITERATOR_TOTAL:%.+]] = add nuw i64 0, [[NELEMS]]
// NELEMS = ITERATOR_TOTAL + non-iterator-deps (=0)
// CHECK: [[TOTAL:%.+]] = add nuw i64 [[ITERATOR_TOTAL]], 0
// %struct.kmp_depend_info DEPS[TOTAL];
// CHECK: [[DEPS:%.+]] = alloca %struct.kmp_depend_info, i64 [[TOTAL]],
// CHECK: [[NDEPS:%.+]] = trunc i64 [[TOTAL]] to i32
// i64 DEP_COUNTER = 0;
// CHECK: store i64 0, i64* [[DEP_COUNTER_ADDR:%.+]],
// NELEMS = ((i - 0 + 2 - 1) / 2);
// CHECK: [[END:%.+]] = load i32, i32* [[I_ADDR]],
// CHECK: [[EB_SUB:%.+]] = sub i32 [[END]], 0
// CHECK: [[EB_SUB_2_ADD:%.+]] = add i32 [[EB_SUB]], 2
// CHECK: [[EB_SUB_2_ADD_1_SUB:%.+]] = sub i32 [[EB_SUB_2_ADD]], 1
// CHECK: [[ELEMS:%.+]] = udiv i32 [[EB_SUB_2_ADD_1_SUB]], 2
// i32 COUNTER = 0;
// CHECK: store i32 0, i32* [[COUNTER_ADDR:%.+]],
// CHECK: br label %[[CONT:.+]]
// Loop.
// CHECK: [[CONT]]:
// CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]],
// CHECK: [[CMP:%.+]] = icmp ult i32 [[COUNTER]], [[ELEMS]]
// CHECK: br i1 [[CMP]], label %[[BODY:.+]], label %[[EXIT:.+]]
// CHECK: [[BODY]]:
// k = 0 + 2*COUNTER;
// CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]],
// CHECK: [[C2_MUL:%.+]] = mul i32 [[COUNTER]], 2
// CHECK: [[C2_MUL_0_ADD:%.+]] = add i32 0, [[C2_MUL]]
// CHECK: store i32 [[C2_MUL_0_ADD]], i32* [[K_ADDR:%.+]],
// &a[k][i]
// CHECK: [[A:%.+]] = load i32**, i32*** [[A_ADDR:%.+]],
// CHECK: [[K:%.+]] = load i32, i32* [[K_ADDR]],
// CHECK: [[IDX:%.+]] = zext i32 [[K]] to i64
// CHECK: [[AK_ADDR:%.+]] = getelementptr inbounds i32*, i32** [[A]], i64 [[IDX]]
// CHECK: [[AK:%.+]] = load i32*, i32** [[AK_ADDR]],
// CHECK: [[I:%.+]] = load i32, i32* [[I_ADDR]],
// CHECK: [[IDX:%.+]] = sext i32 [[I]] to i64
// CHECK: [[AKI_ADDR:%.+]] = getelementptr inbounds i32, i32* [[AK]], i64 [[IDX]]
// DEPS[DEP_COUNTER].base_addr = &a[k][i];
// CHECK: [[DEP_COUNTER:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[DEPS_DC:%.+]] = getelementptr %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS]], i64 [[DEP_COUNTER]]
// CHECK: [[DEPS_DC_BASE_ADDR:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 0
// CHECK: [[AKI_INT:%.+]] = ptrtoint i32* [[AKI_ADDR]] to i64
// CHECK: store i64 [[AKI_INT]], i64* [[DEPS_DC_BASE_ADDR]],
// DEPS[DEP_COUNTER].size = sizeof(a[k][i]);
// CHECK: [[DEPS_DC_SIZE:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 1
// CHECK: store i64 4, i64* [[DEPS_DC_SIZE]],
// DEPS[DEP_COUNTER].flags = in;
// CHECK: [[DEPS_DC_FLAGS:%.+]] = getelementptr inbounds %struct.kmp_depend_info, %struct.kmp_depend_info* [[DEPS_DC]], i{{.+}} 0, i{{.+}} 2
// CHECK: store i8 1, i8* [[DEPS_DC_FLAGS]],
// DEP_COUNTER = DEP_COUNTER + 1;
// CHECK: [[DEP_COUNTER:%.+]] = load i64, i64* [[DEP_COUNTER_ADDR]],
// CHECK: [[INC:%.+]] = add nuw i64 [[DEP_COUNTER]], 1
// CHECK: store i64 [[INC]], i64* [[DEP_COUNTER_ADDR]],
// COUNTER = COUNTER + 1;
// CHECK: [[COUNTER:%.+]] = load i32, i32* [[COUNTER_ADDR]],
// CHECK: [[INC:%.+]] = add i32 [[COUNTER]], 1
// CHECK: store i32 [[INC]], i32* [[COUNTER_ADDR]],
// CHECK: br label %[[CONT]]
// CHECK: [[EXIT]]:
// CHECK: [[DEP_BEGIN:%.+]] = bitcast %struct.kmp_depend_info* [[DEPS]] to i8*
// CHECK: = call i32 @__kmpc_omp_task_with_deps(%struct.ident_t* @{{.+}}, i32 %{{.+}}, i8* [[BUF]], i32 [[NDEPS]], i8* [[DEP_BEGIN]], i32 0, i8* null)
#pragma omp task depend(iterator(unsigned k=0:i:2), in: a[k][i])
++i;
}
#endif
|
dropout-inl.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 dropout-inl.h
* \brief
* \author Bing Xu, Da Zheng, Hang Zhang
*/
#ifndef MXNET_OPERATOR_NN_DROPOUT_INL_H_
#define MXNET_OPERATOR_NN_DROPOUT_INL_H_
#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include <algorithm>
#include "../mxnet_op.h"
#include "../mshadow_op.h"
#include "../random/sampler.h"
#include "../tensor/elemwise_binary_broadcast_op.h"
#define MXNET_USE_MKL_DROPOUT defined(USE_MKL) && defined(_OPENMP) && !defined(__CUDACC__)
#if MXNET_USE_MKL_DROPOUT
#include <omp.h>
#include <mkl_vml_functions.h>
#include <mkl_vsl.h>
#endif // MXNET_USE_MKL_DROPOUT
#define MXNET_USE_CUDNN_DROPOUT MXNET_USE_CUDNN == 1 && CUDNN_MAJOR >= 7
namespace dropout {
enum DropoutOpInputs {kData};
enum DropoutOpOutputs {kOut, kMask};
enum DropoutOpForwardResource {kRandom};
enum DropoutOpMode {kTraining, kAlways};
} // namespace dropout
namespace mxnet {
namespace op {
const int MAX_DIM = 5;
struct DropoutParam : public dmlc::Parameter<DropoutParam> {
float p;
int mode;
TShape axes;
dmlc::optional<bool> cudnn_off;
DMLC_DECLARE_PARAMETER(DropoutParam) {
DMLC_DECLARE_FIELD(p).set_default(0.5)
.set_range(0, 1)
.describe("Fraction of the input that gets dropped out during training time.");
DMLC_DECLARE_FIELD(mode)
.add_enum("training", dropout::kTraining)
.add_enum("always", dropout::kAlways)
.set_default(dropout::kTraining)
.describe("Whether to only turn on dropout during training or to also turn on for inference.");
DMLC_DECLARE_FIELD(axes).set_default(TShape())
.describe("Axes for variational dropout kernel.");
DMLC_DECLARE_FIELD(cudnn_off).set_default(dmlc::optional<bool>(true))
.describe("Whether to turn off cudnn in dropout operator. "
"This option is ignored if axes is specified.");
}
}; // struct DropoutParam
template<typename xpu, typename DType>
class DropoutOp {
#if MXNET_USE_MKL_DROPOUT
static void BernoulliGenerate(common::random::RandGenerator<cpu, DType> gen,
int n, double p, int* r) {
typename RandGenerator<xpu, DType>::Impl genImpl(&gen, 1);
const int seed = 17 + abs(genImpl.rand() % 4096);
CHECK_GE(seed, 0);
const int nthr = engine::OpenMP::Get()->GetRecommendedOMPThreadCount();
#pragma omp parallel num_threads(nthr)
{
const int ithr = omp_get_thread_num();
const int avg_amount = (n + nthr - 1) / nthr;
const int my_offset = ithr * avg_amount;
const int my_amount = std::min(my_offset + avg_amount, n) - my_offset;
if (my_amount > 0) {
VSLStreamStatePtr stream;
vslNewStream(&stream, VSL_BRNG_MCG31, seed);
vslSkipAheadStream(stream, my_offset);
viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount, r + my_offset, p);
vslDeleteStream(&stream);
}
}
}
static inline bool MKLAvailable() {
// BernoulliGenerate expects an array int, so for types smaller than int, the mask buffer
// will be too small, so we can;t use MKL in those cases
return sizeof(DType) >= sizeof(int);
}
// MKL forward pass
inline void MKLForward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<TBlob> &out_data) {
Stream<xpu> *s = ctx.get_stream<xpu>();
RandGenerator<xpu, DType> *pgen = ctx.requested[0].get_parallel_random<xpu, DType>();
CHECK_NOTNULL(pgen);
Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> data = in_data[dropout::kData].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> out = out_data[dropout::kOut].FlatTo2D<xpu, DType>(s);
DType *outptr = out.dptr_;
DType *dataptr = data.dptr_;
auto maskptr = reinterpret_cast<int *>(mask.dptr_);
int count = mask.shape_[0] * mask.shape_[1];
BernoulliGenerate(*pgen, count, this->pkeep_, maskptr);
const float pk_1 = 1.0f / this->pkeep_;
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (int i = 0; i < count; ++i) {
outptr[i] = dataptr[i] * maskptr[i] * pk_1;
}
}
// MKL backward pass
inline void MKLBackward(const OpContext &ctx,
const std::vector<TBlob> &in_grad,
const std::vector<TBlob> &out_data,
const std::vector<TBlob> &out_grad) {
Stream<xpu> *s = ctx.get_stream<xpu>();
Tensor<xpu, 2, DType> grad = out_grad[dropout::kOut].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s);
Tensor<xpu, 2, DType> gdata = in_grad[dropout::kData].FlatTo2D<xpu, DType>(s);
DType *ingradptr = gdata.dptr_;
const DType *outgradptr = grad.dptr_;
auto maskptr = reinterpret_cast<int *>(mask.dptr_);
int count = mask.shape_[0] * mask.shape_[1];
const float pk_1 = 1.0f / this->pkeep_;
#pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
for (int i = 0; i < count; ++i) {
ingradptr[i] = outgradptr[i] * maskptr[i] * pk_1;
}
}
#endif // #if MXNET_USE_MKL_DROPOUT
public:
/*!
* \brief Dropout kernel, compute dropout tensor
*/
struct DropoutKernel {
/*!
* \brief Dropout kernel function
* \param id Thread number (0-based representing count)
* \param gen Random number generator
* \param N Total number of items in the output
* \param step Step between items, related to parallelism
* \param dropout_out Output dropout values
* \param mask_out Output mask (is multiplied to create dropout output, may be 0)
* \param input_data Input data to perform the dropout on
* \param pkeep Dropout rate (keep when the generated random number is less than this value)
*/
MSHADOW_XINLINE static void Map(int id,
RandGenerator<xpu, DType> gen,
const int N,
const int step,
DType *dropout_out,
DType *mask_out,
const DType *input_data,
const real_t pkeep) {
RNG_KERNEL_LOOP(xpu, DType, id, gen, N, step, {
const real_t rand_num = static_cast<real_t>(genImpl.uniform());
mask_out[i] = mshadow_op::threshold_eq::Map<real_t>(rand_num, pkeep) * (1.0f / pkeep);
dropout_out[i] = input_data[i] * mask_out[i];
});
}
};
struct BernoulliKernel {
/*! \brief Bernoulli kernel for generating mask */
MSHADOW_XINLINE static void Map(int id,
RandGenerator<xpu, DType> gen,
const int N,
const int step,
DType *mask_out,
const real_t pkeep) {
RNG_KERNEL_LOOP(xpu, DType, id, gen, N, step, {
const real_t rand_num = static_cast<real_t>(genImpl.uniform());
mask_out[i] = mshadow_op::threshold::Map<real_t>(rand_num, pkeep) * (1.0f / pkeep);
});
}
};
explicit DropoutOp(const DropoutParam ¶m, Context ctx) {
this->pkeep_ = 1.0f - param.p;
this->mode_ = static_cast<dropout::DropoutOpMode>(param.mode);
this->axes_ = param.axes;
this->dropout_passthrough_ = true;
#if MXNET_USE_CUDNN_DROPOUT
this->cudnn_off_ = param.cudnn_off && param.cudnn_off.value();
this->ctx_ = ctx;
if (ctx.dev_type == kGPU && this->pkeep_ > 0 && !this->cudnn_off_) {
dtype_ = mshadow::DataType<DType>::kCudnnFlag;
CUDNN_CALL(cudnnCreateTensorDescriptor(&x_desc_));
CUDNN_CALL(cudnnCreateTensorDescriptor(&y_desc_));
CUDNN_CALL(cudnnCreateTensorDescriptor(&dx_desc_));
CUDNN_CALL(cudnnCreateTensorDescriptor(&dy_desc_));
CUDNN_CALL(cudnnCreateDropoutDescriptor(&dropout_desc_));
}
#endif // MXNET_USE_CUDNN_DROPOUT
}
~DropoutOp() {
#if MXNET_USE_CUDNN_DROPOUT
if (this->ctx_.dev_type == kGPU && this->pkeep_ > 0 && !this->cudnn_off_) {
CUDNN_CALL(cudnnDestroyTensorDescriptor(x_desc_));
CUDNN_CALL(cudnnDestroyTensorDescriptor(y_desc_));
CUDNN_CALL(cudnnDestroyTensorDescriptor(dx_desc_));
CUDNN_CALL(cudnnDestroyTensorDescriptor(dy_desc_));
CUDNN_CALL(cudnnDestroyDropoutDescriptor(dropout_desc_));
}
#endif // MXNET_USE_CUDNN_DROPOUT
}
#if MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
inline bool CuDNNAvailable() {
return this->pkeep_ > 0 && !this->cudnn_off_;
}
inline void CuDNNForward(const OpContext &ctx,
const TBlob &in,
const TBlob &mask,
const TBlob &out) {
Stream<xpu> *s = ctx.get_stream<xpu>();
// set dropout state.
ctx.requested[0].get_cudnn_dropout_desc(&dropout_desc_, s, 1.0f - this->pkeep_, seed_);
// describe input/output tensor
int dim[4], stride[4];
dim[0] = 1;
dim[1] = 1;
dim[2] = 1;
dim[3] = out.Size();
stride[0] = out.Size();
stride[1] = out.Size();
stride[2] = out.Size();
stride[3] = 1;
CUDNN_CALL(cudnnSetTensorNdDescriptor(x_desc_,
dtype_,
4,
dim,
stride));
CUDNN_CALL(cudnnSetTensorNdDescriptor(y_desc_,
dtype_,
4,
dim,
stride));
// perform dropout with cudnn
CUDNN_CALL(cudnnDropoutGetReserveSpaceSize(x_desc_, &dropout_reserve_byte_));
// cudnn uses bits to record the positions that are dropped, so reserve bytes is always
// 1/8 of input size.
CHECK_GE(mask.Size() * sizeof(DType), dropout_reserve_byte_) <<
"The size of the mask space is smaller than the required cudnn reserved space.";
CUDNN_CALL(cudnnDropoutForward(s->dnn_handle_,
dropout_desc_,
x_desc_,
in.dptr<DType>(),
y_desc_,
out.dptr<DType>(),
mask.dptr<DType>(),
dropout_reserve_byte_));
}
inline void CuDNNBackward(const OpContext &ctx,
const TBlob &out_grad,
const TBlob &mask,
const TBlob &in_grad) {
Stream<xpu> *s = ctx.get_stream<xpu>();
// describe input/output tensor
int dim[4], stride[4];
dim[0] = 1;
dim[1] = 1;
dim[2] = 1;
dim[3] = in_grad.Size();
stride[0] = in_grad.Size();
stride[1] = in_grad.Size();
stride[2] = in_grad.Size();
stride[3] = 1;
CUDNN_CALL(cudnnSetTensorNdDescriptor(dy_desc_,
dtype_,
4,
dim,
stride));
CUDNN_CALL(cudnnSetTensorNdDescriptor(dx_desc_,
dtype_,
4,
dim,
stride));
// perform dropout with cudnn
CUDNN_CALL(cudnnDropoutBackward(s->dnn_handle_,
dropout_desc_,
dy_desc_,
out_grad.dptr<DType>(),
dx_desc_,
in_grad.dptr<DType>(),
mask.dptr<DType>(),
dropout_reserve_byte_));
}
#endif // MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
void Forward(const OpContext &ctx,
const std::vector<TBlob> &in_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &out_data) {
this->dropout_passthrough_ = true;
if (req[dropout::kOut] != kNullOp) {
CHECK_EQ(in_data.size(), 1U);
if (ctx.is_train) {
CHECK_EQ(out_data.size(), 2U);
}
Stream<xpu> *s = ctx.get_stream<xpu>();
const TBlob &in = in_data[dropout::kData];
const TBlob &out = out_data[dropout::kOut];
const TBlob &mask = out_data[dropout::kMask];
if (this->pkeep_ < 1 && (ctx.is_train || this->mode_ == dropout::kAlways)) {
this->dropout_passthrough_ = false;
if (this->axes_.ndim() == 0) {
#if MXNET_USE_MKL_DROPOUT
if (MKLAvailable()) {
MKLForward(ctx, in_data, out_data);
return;
}
#endif // MXNET_USE_MKL_DROPOUT
#if MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
if (CuDNNAvailable()) {
CuDNNForward(ctx, in, mask, out);
return;
}
#endif // MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
RandGenerator<xpu, DType> *pgen = ctx.requested[0].get_parallel_random<xpu, DType>();
CHECK_NOTNULL(pgen);
CHECK(req[dropout::kOut] != kAddTo);
LaunchRNG<DropoutKernel, xpu>(s, pgen, out.Size(),
out.dptr<DType>(),
mask.dptr<DType>(),
in.dptr<DType>(),
this->pkeep_);
return;
} else {
RandGenerator<xpu, DType> *pgen = ctx.requested[0].get_parallel_random<xpu, DType>();
CHECK_NOTNULL(pgen);
// initialize the mask
LaunchRNG<BernoulliKernel, xpu>(s, pgen, mask.Size(),
mask.dptr<DType>(),
this->pkeep_);
// broadcast mul
TShape new_lshape, new_rshape, new_oshape;
int ndim = BinaryBroadcastShapeCompact(in.shape_,
mask.shape_, out.shape_,
&new_lshape, &new_rshape, &new_oshape);
if (!ndim) {
MXNET_ASSIGN_REQ_SWITCH(req[dropout::kOut], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch(
s, out.Size(), out.dptr<DType>(), in.dptr<DType>(),
mask.dptr<DType>());
});
} else {
BROADCAST_NDIM_SWITCH(ndim, NDim, {
mshadow::Shape<NDim> oshape = new_oshape.get<NDim>();
mshadow::Shape<NDim> lstride = mxnet_op::calc_stride(new_lshape.get<NDim>());
mshadow::Shape<NDim> rstride = mxnet_op::calc_stride(new_rshape.get<NDim>());
mxnet_op::Kernel<mxnet_op::binary_broadcast_kernel<NDim, DType,
mshadow_op::mul>, xpu>::
template LaunchEx(s, new_oshape.Size(), req[dropout::kOut],
lstride, rstride, oshape,
in.dptr<DType>(),
mask.dptr<DType>(), out.dptr<DType>());
});
}
}
} else {
MXNET_ASSIGN_REQ_SWITCH(req[dropout::kOut], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, Req>, xpu>::Launch(
s, out.Size(), out.dptr<DType>(), in.dptr<DType>());
});
}
}
}
void Backward(const OpContext &ctx,
const std::vector<TBlob> &out_grad,
const std::vector<TBlob> &out_data,
const std::vector<OpReqType> &req,
const std::vector<TBlob> &in_grad) {
using namespace mshadow;
using namespace mshadow::expr;
Stream<xpu> *s = ctx.get_stream<xpu>();
if (!this->dropout_passthrough_) {
this->dropout_passthrough_ = true;
const TBlob &gdata = in_grad[dropout::kData];
const TBlob &grad = out_grad[dropout::kOut];
const TBlob &mask = out_data[dropout::kMask];
if (this->axes_.ndim() == 0) {
#if MXNET_USE_MKL_DROPOUT
if (MKLAvailable()) {
MKLBackward(ctx, in_grad, out_data, out_grad);
return;
}
#endif // MXNET_USE_MKL_DROPOUT
#if MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
if (CuDNNAvailable()) {
CuDNNBackward(ctx, grad, mask, gdata);
return;
}
#endif // MXNET_USE_CUDNN_DROPOUT && defined(__CUDACC__)
// standard case for dropout
CHECK_EQ(grad.Size(), mask.Size());
MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch(
s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>(), mask.dptr<DType>());
});
return;
} else {
// broardcast mul
TShape new_lshape, new_rshape, new_oshape;
int ndim = BinaryBroadcastShapeCompact(grad.shape_,
mask.shape_, gdata.shape_,
&new_lshape, &new_rshape, &new_oshape);
if (!ndim) {
MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::mul, Req>, xpu>::Launch(
s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>(), mask.dptr<DType>());
});
} else {
BROADCAST_NDIM_SWITCH(ndim, NDim, {
mshadow::Shape<NDim> oshape = new_oshape.get<NDim>();
mshadow::Shape<NDim> lstride = mxnet_op::calc_stride(new_lshape.get<NDim>());
mshadow::Shape<NDim> rstride = mxnet_op::calc_stride(new_rshape.get<NDim>());
mxnet_op::Kernel<mxnet_op::binary_broadcast_kernel<NDim, DType,
mshadow_op::mul>, xpu>::
template LaunchEx(s, new_oshape.Size(), req[0], lstride, rstride, oshape,
grad.dptr<DType>(), mask.dptr<DType>(), gdata.dptr<DType>());
});
}
}
} else {
const TBlob& gdata = in_grad[dropout::kData];
const TBlob& grad = out_grad[dropout::kOut];
MXNET_ASSIGN_REQ_SWITCH(req[dropout::kData], Req, {
mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, Req>, xpu>::Launch(
s, gdata.Size(), gdata.dptr<DType>(), grad.dptr<DType>());
});
}
}
private:
/*! \brief Dropout rate (keep when the generated random number is less than this value) */
real_t pkeep_;
/*! \brief Dropout mode */
dropout::DropoutOpMode mode_;
/*! \brief Axes on which dropout mask is shared in the form of broadcast multiply */
TShape axes_;
/*! \brief Flag to record whether forward is executed in pass-through mode */
bool dropout_passthrough_;
#if MXNET_USE_CUDNN_DROPOUT
bool cudnn_off_;
Context ctx_;
cudnnDataType_t dtype_;
cudnnDropoutDescriptor_t dropout_desc_;
uint64_t seed_ = 17 + rand() % 4096; // NOLINT(runtime/threadsafe_fn)
size_t dropout_reserve_byte_;
cudnnTensorDescriptor_t x_desc_, y_desc_, dx_desc_, dy_desc_;
#endif // MXNET_USE_CUDNN_DROPOUT
}; // class DropoutOp
static OpStatePtr CreateDropoutState(const nnvm::NodeAttrs &attrs,
const Context ctx,
const std::vector<TShape> &in_shapes,
const std::vector<int> &in_types) {
const DropoutParam& param = nnvm::get<DropoutParam>(attrs.parsed);
OpStatePtr state;
MSHADOW_REAL_TYPE_SWITCH(in_types[dropout::kData], DType, {
if (ctx.dev_type == kGPU) {
state = OpStatePtr::Create<DropoutOp<gpu, DType>>(param, ctx);
} else {
state = OpStatePtr::Create<DropoutOp<cpu, DType>>(param, ctx);
}
return state;
});
LOG(FATAL) << "should never reach here";
return OpStatePtr(); // should never reach here
}
template<typename xpu>
void DropoutCompute(const OpStatePtr& state,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
DropoutOp<xpu, DType>& op = state.get_state<DropoutOp<xpu, DType>>();
op.Forward(ctx, inputs, req, outputs);
});
}
template<typename xpu>
void DropoutGradCompute(const OpStatePtr& state,
const OpContext& ctx,
const std::vector<TBlob>& inputs,
const std::vector<OpReqType>& req,
const std::vector<TBlob>& outputs) {
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(outputs.size(), 1);
CHECK_EQ(req.size(), 1);
std::vector<TBlob> out_grads(2);
std::vector<TBlob> out_data(2);
out_grads[dropout::kOut] = inputs[0];
out_data[dropout::kMask] = inputs[1];
MSHADOW_REAL_TYPE_SWITCH(inputs[0].type_flag_, DType, {
DropoutOp<xpu, DType>& op = state.get_state<DropoutOp<xpu, DType>>();
op.Backward(ctx, out_grads, out_data, req, outputs);
});
}
} // namespace op
} // namespace mxnet
#undef MXNET_USE_MKL_DROPOUT
#endif // MXNET_OPERATOR_NN_DROPOUT_INL_H_
|
perftest.c | /**
* Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED.
* Copyright (C) The University of Tennessee and The University
* of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED.
* Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "libperf.h"
#include "libperf_int.h"
#include <ucs/sys/string.h>
#include <ucs/sys/sys.h>
#include <ucs/debug/log.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <getopt.h>
#include <string.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <locale.h>
#if HAVE_MPI
# include <mpi.h>
#elif HAVE_RTE
# include<rte.h>
#endif
#define MAX_BATCH_FILES 32
#define TL_RESOURCE_NAME_NONE "<none>"
#define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCqM:r:T:d:x:A:BUm:"
enum {
TEST_FLAG_PRINT_RESULTS = UCS_BIT(0),
TEST_FLAG_PRINT_TEST = UCS_BIT(1),
TEST_FLAG_SET_AFFINITY = UCS_BIT(8),
TEST_FLAG_NUMERIC_FMT = UCS_BIT(9),
TEST_FLAG_PRINT_FINAL = UCS_BIT(10),
TEST_FLAG_PRINT_CSV = UCS_BIT(11)
};
typedef struct sock_rte_group {
int is_server;
int connfd;
} sock_rte_group_t;
typedef struct test_type {
const char *name;
ucx_perf_api_t api;
ucx_perf_cmd_t command;
ucx_perf_test_type_t test_type;
const char *desc;
} test_type_t;
struct perftest_context {
ucx_perf_params_t params;
const char *server_addr;
int port;
int mpi;
unsigned cpu;
unsigned flags;
unsigned num_batch_files;
char *batch_files[MAX_BATCH_FILES];
char *test_names[MAX_BATCH_FILES];
sock_rte_group_t sock_rte_group;
};
test_type_t tests[] = {
{"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG,
"active message latency"},
{"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG,
"put latency"},
{"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG,
"atomic add latency"},
{"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI,
"get latency / bandwidth / message rate"},
{"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic fetch-and-add latency / rate"},
{"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic swap latency / rate"},
{"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic compare-and-swap latency / rate"},
{"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI,
"active message bandwidth / message rate"},
{"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
"put bandwidth / message rate"},
{"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic add message rate"},
{"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG,
"tag match latency"},
{"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI,
"tag match bandwidth"},
{"tag_sync_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_PINGPONG,
"tag sync match latency"},
{"tag_sync_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_STREAM_UNI,
"tag sync match bandwidth"},
{"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG,
"put latency"},
{"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI,
"put bandwidth"},
{"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI,
"get latency / bandwidth / message rate"},
{"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic add bandwidth / message rate"},
{"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic fetch-and-add latency / bandwidth / rate"},
{"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic swap latency / bandwidth / rate"},
{"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI,
"atomic compare-and-swap latency / bandwidth / rate"},
{"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI,
"stream bandwidth"},
{"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG,
"stream latency"},
{NULL}
};
static int sock_io(int sock, ssize_t (*sock_call)(int, void *, size_t, int),
int poll_events, void *data, size_t size,
void (*progress)(void *arg), void *arg, const char *name)
{
size_t total = 0;
struct pollfd pfd;
int ret;
while (total < size) {
pfd.fd = sock;
pfd.events = poll_events;
pfd.revents = 0;
ret = poll(&pfd, 1, 1); /* poll for 1ms */
if (ret > 0) {
ucs_assert(ret == 1);
ucs_assert(pfd.revents & poll_events);
ret = sock_call(sock, (char*)data + total, size - total, 0);
if (ret < 0) {
ucs_error("%s() failed: %m", name);
return -1;
}
total += ret;
} else if ((ret < 0) && (errno != EINTR)) {
ucs_error("poll(fd=%d) failed: %m", sock);
return -1;
}
/* progress user context */
if (progress != NULL) {
progress(arg);
}
}
return 0;
}
static int safe_send(int sock, void *data, size_t size,
void (*progress)(void *arg), void *arg)
{
return sock_io(sock, (void*)send, POLLOUT, data, size, progress, arg, "send");
}
static int safe_recv(int sock, void *data, size_t size,
void (*progress)(void *arg), void *arg)
{
return sock_io(sock, recv, POLLIN, data, size, progress, arg, "recv");
}
static void print_progress(char **test_names, unsigned num_names,
const ucx_perf_result_t *result, unsigned flags,
int final)
{
static const char *fmt_csv = "%.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n";
static const char *fmt_numeric = "%'14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %'11.0f %'11.0f\n";
static const char *fmt_plain = "%14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %11.0f %11.0f\n";
unsigned i;
if (!(flags & TEST_FLAG_PRINT_RESULTS) ||
(!final && (flags & TEST_FLAG_PRINT_FINAL)))
{
return;
}
if (flags & TEST_FLAG_PRINT_CSV) {
for (i = 0; i < num_names; ++i) {
printf("%s,", test_names[i]);
}
}
printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv :
(flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric :
fmt_plain,
(double)result->iters,
result->latency.typical * 1000000.0,
result->latency.moment_average * 1000000.0,
result->latency.total_average * 1000000.0,
result->bandwidth.moment_average / (1024.0 * 1024.0),
result->bandwidth.total_average / (1024.0 * 1024.0),
result->msgrate.moment_average,
result->msgrate.total_average);
fflush(stdout);
}
static void print_header(struct perftest_context *ctx)
{
const char *test_api_str;
const char *test_data_str;
test_type_t *test;
unsigned i;
if (ctx->flags & TEST_FLAG_PRINT_TEST) {
for (test = tests; test->name; ++test) {
if ((test->command == ctx->params.command) && (test->test_type == ctx->params.test_type)) {
break;
}
}
if (test->name != NULL) {
if (test->api == UCX_PERF_API_UCT) {
test_api_str = "transport layer";
switch (ctx->params.uct.data_layout) {
case UCT_PERF_DATA_LAYOUT_SHORT:
test_data_str = "short";
break;
case UCT_PERF_DATA_LAYOUT_BCOPY:
test_data_str = "bcopy";
break;
case UCT_PERF_DATA_LAYOUT_ZCOPY:
test_data_str = "zcopy";
break;
default:
test_data_str = "(undefined)";
break;
}
} else if (test->api == UCX_PERF_API_UCP) {
test_api_str = "protocol layer";
test_data_str = "(automatic)"; /* TODO contig/stride/stream */
} else {
return;
}
printf("+------------------------------------------------------------------------------------------+\n");
printf("| API: %-60s |\n", test_api_str);
printf("| Test: %-60s |\n", test->desc);
printf("| Data layout: %-60s |\n", test_data_str);
printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params));
}
}
if (ctx->flags & TEST_FLAG_PRINT_CSV) {
if (ctx->flags & TEST_FLAG_PRINT_RESULTS) {
for (i = 0; i < ctx->num_batch_files; ++i) {
printf("%s,", basename(ctx->batch_files[i]));
}
printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n");
}
} else {
if (ctx->flags & TEST_FLAG_PRINT_RESULTS) {
printf("+--------------+-----------------------------+---------------------+-----------------------+\n");
printf("| | latency (usec) | bandwidth (MB/s) | message rate (msg/s) |\n");
printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n");
printf("| # iterations | typical | average | overall | average | overall | average | overall |\n");
printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n");
} else if (ctx->flags & TEST_FLAG_PRINT_TEST) {
printf("+------------------------------------------------------------------------------------------+\n");
}
}
}
static void print_test_name(struct perftest_context *ctx)
{
char buf[200];
unsigned i, pos;
if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) {
strcpy(buf, "+--------------+---------+---------+---------+----------+----------+-----------+-----------+");
pos = 1;
for (i = 0; i < ctx->num_batch_files; ++i) {
if (i != 0) {
buf[pos++] = '/';
}
memcpy(&buf[pos], ctx->test_names[i],
ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1));
pos += strlen(ctx->test_names[i]);
}
if (ctx->flags & TEST_FLAG_PRINT_RESULTS) {
printf("%s\n", buf);
}
}
}
static void usage(const struct perftest_context *ctx, const char *program)
{
static const char* api_names[] = {
[UCX_PERF_API_UCT] = "UCT",
[UCX_PERF_API_UCP] = "UCP"
};
test_type_t *test;
int UCS_V_UNUSED rank;
#if HAVE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (ctx->mpi && (rank != 0)) {
return;
}
#endif
#if HAVE_MPI
printf(" Note: test can be also launched as an MPI application\n");
printf("\n");
#elif HAVE_RTE
printf(" Note: this test can be also launched as an libRTE application\n");
printf("\n");
#endif
printf(" Usage: %s [ server-hostname ] [ options ]\n", program);
printf("\n");
printf(" Common options:\n");
printf(" -t <test> test to run:\n");
for (test = tests; test->name; ++test) {
printf(" %13s - %s %s\n", test->name,
api_names[test->api], test->desc);
}
printf("\n");
printf(" -s <size> list of scatter-gather sizes for single message (%zu)\n",
ctx->params.msg_size_list[0]);
printf(" for example: \"-s 16,48,8192,8192,14\"\n");
printf(" -n <iters> number of iterations to run (%ld)\n", ctx->params.max_iter);
printf(" -w <iters> number of warm-up iterations (%zu)\n",
ctx->params.warmup_iter);
printf(" -c <cpu> set affinity to this CPU (off)\n");
printf(" -O <count> maximal number of uncompleted outstanding sends (%u)\n",
ctx->params.max_outstanding);
printf(" -i <offset> distance between consecutive scatter-gather entries (%zu)\n",
ctx->params.iov_stride);
printf(" -T <threads> number of threads in the test (%d), if >1 implies \"-M multi\"\n",
ctx->params.thread_count);
printf(" -B register memory with NONBLOCK flag\n");
printf(" -b <file> read and execute tests from a batch file: every line in the\n");
printf(" file is a test to run, first word is test name, the rest of\n");
printf(" the line is command-line arguments for the test.\n");
printf(" -p <port> TCP port to use for data exchange (%d)\n", ctx->port);
#if HAVE_MPI
printf(" -P <0|1> disable/enable MPI mode (%d)\n", ctx->mpi);
#endif
printf(" -m <mem type> memory type of messages\n");
printf(" host - system memory(default)\n");
#if HAVE_CUDA
printf(" cuda - NVIDIA GPU memory\n");
printf(" cuda-managed - NVIDIA cuda managed/unified memory\n");
#endif
printf(" -h show this help message\n");
printf("\n");
printf(" Output format:\n");
printf(" -N use numeric formatting (thousands separator)\n");
printf(" -f print only final numbers\n");
printf(" -v print CSV-formatted output\n");
printf("\n");
printf(" UCT only:\n");
printf(" -d <device> device to use for testing\n");
printf(" -x <tl> transport to use for testing\n");
printf(" -D <layout> data layout for sender side:\n");
printf(" short - short messages (default, cannot be used for get)\n");
printf(" bcopy - copy-out (cannot be used for atomics)\n");
printf(" zcopy - zero-copy (cannot be used for atomics)\n");
printf(" iov - scatter-gather list (iovec)\n");
printf(" -W <count> flow control window size, for active messages (%u)\n",
ctx->params.uct.fc_window);
printf(" -H <size> active message header size (%zu)\n",
ctx->params.am_hdr_size);
printf(" -A <mode> asynchronous progress mode (thread)\n");
printf(" thread - separate progress thread\n");
printf(" signal - signal-based timer\n");
printf("\n");
printf(" UCP only:\n");
printf(" -M <thread> thread support level for progress engine (single)\n");
printf(" single - only the master thread can access\n");
printf(" serialized - one thread can access at a time\n");
printf(" multi - multiple threads can access\n");
printf(" -D <layout>[,<layout>]\n");
printf(" data layout for sender and receiver side (contig)\n");
printf(" contig - Continuous datatype\n");
printf(" iov - Scatter-gather list\n");
printf(" -C use wild-card tag for tag tests\n");
printf(" -U force unexpected flow by using tag probe\n");
printf(" -r <mode> receive mode for stream tests (recv)\n");
printf(" recv : Use ucp_stream_recv_nb\n");
printf(" recv_data : Use ucp_stream_recv_data_nb\n");
printf("\n");
printf(" NOTE: When running UCP tests, transport and device should be specified by\n");
printf(" environment variables: UCX_TLS and UCX_[SELF|SHM|NET]_DEVICES.\n");
printf("\n");
}
static const char *__basename(const char *path)
{
const char *p = strrchr(path, '/');
return (p == NULL) ? path : (p + 1);
}
static ucs_status_t parse_ucp_datatype_params(const char *optarg,
ucp_perf_datatype_t *datatype)
{
const char *iov_type = "iov";
const size_t iov_type_size = strlen("iov");
const char *contig_type = "contig";
const size_t contig_type_size = strlen("contig");
if (0 == strncmp(optarg, iov_type, iov_type_size)) {
*datatype = UCP_PERF_DATATYPE_IOV;
} else if (0 == strncmp(optarg, contig_type, contig_type_size)) {
*datatype = UCP_PERF_DATATYPE_CONTIG;
} else {
return UCS_ERR_INVALID_PARAM;
}
return UCS_OK;
}
static ucs_status_t parse_message_sizes_params(const char *optarg,
ucx_perf_params_t *params)
{
char *optarg_ptr, *optarg_ptr2;
size_t token_num, token_it;
const char delim = ',';
optarg_ptr = (char *)optarg;
token_num = 0;
/* count the number of given message sizes */
while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) {
++optarg_ptr;
++token_num;
}
++token_num;
params->msg_size_list = realloc(params->msg_size_list,
sizeof(*params->msg_size_list) * token_num);
if (NULL == params->msg_size_list) {
return UCS_ERR_NO_MEMORY;
}
optarg_ptr = (char *)optarg;
errno = 0;
for (token_it = 0; token_it < token_num; ++token_it) {
params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10);
if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) ||
((errno != 0) && (params->msg_size_list[token_it] == 0)) ||
(optarg_ptr == optarg_ptr2)) {
free(params->msg_size_list);
params->msg_size_list = NULL; /* prevent double free */
ucs_error("Invalid option substring argument at position %lu", token_it);
return UCS_ERR_INVALID_PARAM;
}
optarg_ptr = optarg_ptr2 + 1;
}
params->msg_size_cnt = token_num;
return UCS_OK;
}
static void init_test_params(ucx_perf_params_t *params)
{
memset(params, 0, sizeof(*params));
params->api = UCX_PERF_API_LAST;
params->command = UCX_PERF_CMD_LAST;
params->test_type = UCX_PERF_TEST_TYPE_LAST;
params->thread_mode = UCS_THREAD_MODE_SINGLE;
params->thread_count = 1;
params->async_mode = UCS_ASYNC_MODE_THREAD;
params->wait_mode = UCX_PERF_WAIT_MODE_LAST;
params->max_outstanding = 1;
params->warmup_iter = 10000;
params->am_hdr_size = 8;
params->alignment = ucs_get_page_size();
params->max_iter = 1000000l;
params->max_time = 0.0;
params->report_interval = 1.0;
params->flags = UCX_PERF_TEST_FLAG_VERBOSE;
params->uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW;
params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT;
params->mem_type = UCT_MD_MEM_TYPE_HOST;
params->msg_size_cnt = 1;
params->iov_stride = 0;
params->ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG;
params->ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG;
strcpy(params->uct.dev_name, TL_RESOURCE_NAME_NONE);
strcpy(params->uct.tl_name, TL_RESOURCE_NAME_NONE);
params->msg_size_list = malloc(sizeof(*params->msg_size_list) *
params->msg_size_cnt);
params->msg_size_list[0] = 8;
}
static ucs_status_t parse_test_params(ucx_perf_params_t *params, char opt, const char *optarg)
{
test_type_t *test;
char *optarg2 = NULL;
switch (opt) {
case 'd':
ucs_snprintf_zero(params->uct.dev_name, sizeof(params->uct.dev_name),
"%s", optarg);
return UCS_OK;
case 'x':
ucs_snprintf_zero(params->uct.tl_name, sizeof(params->uct.tl_name),
"%s", optarg);
return UCS_OK;
case 't':
for (test = tests; test->name; ++test) {
if (!strcmp(optarg, test->name)) {
params->api = test->api;
params->command = test->command;
params->test_type = test->test_type;
break;
}
}
if (test->name == NULL) {
ucs_error("Invalid option argument for -t");
return UCS_ERR_INVALID_PARAM;
}
return UCS_OK;
case 'D':
if (!strcmp(optarg, "short")) {
params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT;
} else if (!strcmp(optarg, "bcopy")) {
params->uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY;
} else if (!strcmp(optarg, "zcopy")) {
params->uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY;
} else if (UCS_OK == parse_ucp_datatype_params(optarg,
¶ms->ucp.send_datatype)) {
optarg2 = strchr(optarg, ',');
if (optarg2) {
if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1,
¶ms->ucp.recv_datatype)) {
return -1;
}
}
} else {
ucs_error("Invalid option argument for -D");
return -1;
}
return UCS_OK;
case 'i':
params->iov_stride = atol(optarg);
return UCS_OK;
case 'n':
params->max_iter = atol(optarg);
return UCS_OK;
case 's':
return parse_message_sizes_params(optarg, params);
case 'H':
params->am_hdr_size = atol(optarg);
return UCS_OK;
case 'W':
params->uct.fc_window = atoi(optarg);
return UCS_OK;
case 'O':
params->max_outstanding = atoi(optarg);
return UCS_OK;
case 'w':
params->warmup_iter = atol(optarg);
return UCS_OK;
case 'o':
params->flags |= UCX_PERF_TEST_FLAG_ONE_SIDED;
return UCS_OK;
case 'B':
params->flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK;
return UCS_OK;
case 'q':
params->flags &= ~UCX_PERF_TEST_FLAG_VERBOSE;
return UCS_OK;
case 'C':
params->flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD;
return UCS_OK;
case 'U':
params->flags |= UCX_PERF_TEST_FLAG_TAG_UNEXP_PROBE;
return UCS_OK;
case 'M':
if (!strcmp(optarg, "single")) {
params->thread_mode = UCS_THREAD_MODE_SINGLE;
return UCS_OK;
} else if (!strcmp(optarg, "serialized")) {
params->thread_mode = UCS_THREAD_MODE_SERIALIZED;
return UCS_OK;
} else if (!strcmp(optarg, "multi")) {
params->thread_mode = UCS_THREAD_MODE_MULTI;
return UCS_OK;
} else {
ucs_error("Invalid option argument for -M");
return UCS_ERR_INVALID_PARAM;
}
case 'T':
params->thread_count = atoi(optarg);
params->thread_mode = UCS_THREAD_MODE_MULTI;
return UCS_OK;
case 'A':
if (!strcmp(optarg, "thread")) {
params->async_mode = UCS_ASYNC_MODE_THREAD;
return UCS_OK;
} else if (!strcmp(optarg, "signal")) {
params->async_mode = UCS_ASYNC_MODE_SIGNAL;
return UCS_OK;
} else {
ucs_error("Invalid option argument for -A");
return UCS_ERR_INVALID_PARAM;
}
case 'r':
if (!strcmp(optarg, "recv_data")) {
params->flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA;
return UCS_OK;
} else if (!strcmp(optarg, "recv")) {
params->flags &= ~UCX_PERF_TEST_FLAG_STREAM_RECV_DATA;
return UCS_OK;
}
return UCS_ERR_INVALID_PARAM;
case 'm':
if (!strcmp(optarg, "host")) {
params->mem_type = UCT_MD_MEM_TYPE_HOST;
return UCS_OK;
} else if(!strncmp(optarg, "cuda", 4)) {
#if HAVE_CUDA
params->mem_type = (!strcmp(optarg, "cuda-managed")) ?
UCT_MD_MEM_TYPE_CUDA_MANAGED : UCT_MD_MEM_TYPE_CUDA;
return UCS_OK;
#else
ucs_error("not built with cuda support");
return UCS_ERR_INVALID_PARAM;
#endif
}
return UCS_ERR_INVALID_PARAM;
default:
return UCS_ERR_INVALID_PARAM;
}
}
static ucs_status_t read_batch_file(FILE *batch_file, const char *file_name,
int *line_num, ucx_perf_params_t *params,
char** test_name_p)
{
#define MAX_SIZE 256
#define MAX_ARG_SIZE 2048
ucs_status_t status;
char buf[MAX_ARG_SIZE];
int argc;
char *argv[MAX_SIZE + 1];
int c;
char *p;
do {
if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) {
return UCS_ERR_NO_ELEM;
}
++(*line_num);
argc = 0;
p = strtok(buf, " \t\n\r");
while (p && (argc < MAX_SIZE)) {
argv[argc++] = p;
p = strtok(NULL, " \t\n\r");
}
argv[argc] = NULL;
} while ((argc == 0) || (argv[0][0] == '#'));
optind = 1;
while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) {
status = parse_test_params(params, c, optarg);
if (status != UCS_OK) {
ucs_error("in batch file '%s' line %d: -%c %s: %s",
file_name, *line_num, c, optarg, ucs_status_string(status));
return status;
}
}
*test_name_p = strdup(argv[0]);
return UCS_OK;
}
static ucs_status_t parse_opts(struct perftest_context *ctx, int mpi_initialized,
int argc, char **argv)
{
ucs_status_t status;
int c;
ucs_trace_func("");
init_test_params(&ctx->params);
ctx->server_addr = NULL;
ctx->num_batch_files = 0;
ctx->port = 13337;
ctx->flags = 0;
ctx->mpi = mpi_initialized;
optind = 1;
while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) {
switch (c) {
case 'p':
ctx->port = atoi(optarg);
break;
case 'b':
if (ctx->num_batch_files < MAX_BATCH_FILES) {
ctx->batch_files[ctx->num_batch_files++] = optarg;
}
break;
case 'N':
ctx->flags |= TEST_FLAG_NUMERIC_FMT;
break;
case 'f':
ctx->flags |= TEST_FLAG_PRINT_FINAL;
break;
case 'v':
ctx->flags |= TEST_FLAG_PRINT_CSV;
break;
case 'c':
ctx->flags |= TEST_FLAG_SET_AFFINITY;
ctx->cpu = atoi(optarg);
break;
case 'P':
#if HAVE_MPI
ctx->mpi = atoi(optarg) && mpi_initialized;
break;
#endif
case 'h':
usage(ctx, __basename(argv[0]));
return UCS_ERR_CANCELED;
default:
status = parse_test_params(&ctx->params, c, optarg);
if (status != UCS_OK) {
usage(ctx, __basename(argv[0]));
return status;
}
break;
}
}
if (optind < argc) {
ctx->server_addr = argv[optind];
}
return UCS_OK;
}
static unsigned sock_rte_group_size(void *rte_group)
{
return 2;
}
static unsigned sock_rte_group_index(void *rte_group)
{
sock_rte_group_t *group = rte_group;
return group->is_server ? 0 : 1;
}
static void sock_rte_barrier(void *rte_group, void (*progress)(void *arg),
void *arg)
{
#pragma omp master
{
sock_rte_group_t *group = rte_group;
const unsigned magic = 0xdeadbeef;
unsigned sync;
sync = magic;
safe_send(group->connfd, &sync, sizeof(unsigned), progress, arg);
sync = 0;
safe_recv(group->connfd, &sync, sizeof(unsigned), progress, arg);
ucs_assert(sync == magic);
}
#pragma omp barrier
}
static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec,
int iovcnt, void **req)
{
sock_rte_group_t *group = rte_group;
size_t size;
int i;
size = 0;
for (i = 0; i < iovcnt; ++i) {
size += iovec[i].iov_len;
}
safe_send(group->connfd, &size, sizeof(size), NULL, NULL);
for (i = 0; i < iovcnt; ++i) {
safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len, NULL,
NULL);
}
}
static void sock_rte_recv(void *rte_group, unsigned src, void *buffer,
size_t max, void *req)
{
sock_rte_group_t *group = rte_group;
int group_index;
size_t size;
group_index = sock_rte_group_index(rte_group);
if (src == group_index) {
return;
}
ucs_assert_always(src == (1 - group_index));
safe_recv(group->connfd, &size, sizeof(size), NULL, NULL);
ucs_assert_always(size <= max);
safe_recv(group->connfd, buffer, size, NULL, NULL);
}
static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result,
void *arg, int is_final)
{
struct perftest_context *ctx = arg;
print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags,
is_final);
}
static ucx_perf_rte_t sock_rte = {
.group_size = sock_rte_group_size,
.group_index = sock_rte_group_index,
.barrier = sock_rte_barrier,
.post_vec = sock_rte_post_vec,
.recv = sock_rte_recv,
.exchange_vec = (void*)ucs_empty_function,
.report = sock_rte_report,
};
static ucs_status_t setup_sock_rte(struct perftest_context *ctx)
{
struct sockaddr_in inaddr;
struct hostent *he;
ucs_status_t status;
int optval = 1;
int sockfd, connfd;
int ret;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
ucs_error("socket() failed: %m");
status = UCS_ERR_IO_ERROR;
goto err;
}
if (ctx->server_addr == NULL) {
optval = 1;
ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
if (ret < 0) {
ucs_error("setsockopt(SO_REUSEADDR) failed: %m");
status = UCS_ERR_INVALID_PARAM;
goto err_close_sockfd;
}
inaddr.sin_family = AF_INET;
inaddr.sin_port = htons(ctx->port);
inaddr.sin_addr.s_addr = INADDR_ANY;
memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero));
ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr));
if (ret < 0) {
ucs_error("bind() failed: %m");
status = UCS_ERR_INVALID_ADDR;
goto err_close_sockfd;
}
ret = listen(sockfd, 10);
if (ret < 0) {
ucs_error("listen() failed: %m");
status = UCS_ERR_IO_ERROR;
goto err_close_sockfd;
}
printf("Waiting for connection...\n");
/* Accept next connection */
connfd = accept(sockfd, NULL, NULL);
if (connfd < 0) {
ucs_error("accept() failed: %m");
status = UCS_ERR_IO_ERROR;
goto err_close_sockfd;
}
close(sockfd);
safe_recv(connfd, &ctx->params, sizeof(ctx->params), NULL, NULL);
if (ctx->params.msg_size_cnt) {
ctx->params.msg_size_list = malloc(sizeof(*ctx->params.msg_size_list) *
ctx->params.msg_size_cnt);
if (NULL == ctx->params.msg_size_list) {
status = UCS_ERR_NO_MEMORY;
goto err_close_connfd;
}
safe_recv(connfd, ctx->params.msg_size_list,
sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt,
NULL, NULL);
}
ctx->sock_rte_group.connfd = connfd;
ctx->sock_rte_group.is_server = 1;
} else {
he = gethostbyname(ctx->server_addr);
if (he == NULL || he->h_addr_list == NULL) {
ucs_error("host %s not found: %s", ctx->server_addr,
hstrerror(h_errno));
status = UCS_ERR_INVALID_ADDR;
goto err_close_sockfd;
}
inaddr.sin_family = he->h_addrtype;
inaddr.sin_port = htons(ctx->port);
ucs_assert(he->h_length == sizeof(inaddr.sin_addr));
memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length);
memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero));
ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr));
if (ret < 0) {
ucs_error("connect() failed: %m");
status = UCS_ERR_UNREACHABLE;
goto err_close_sockfd;
}
safe_send(sockfd, &ctx->params, sizeof(ctx->params), NULL, NULL);
if (ctx->params.msg_size_cnt) {
safe_send(sockfd, ctx->params.msg_size_list,
sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt,
NULL, NULL);
}
ctx->sock_rte_group.connfd = sockfd;
ctx->sock_rte_group.is_server = 0;
}
if (ctx->sock_rte_group.is_server) {
ctx->flags |= TEST_FLAG_PRINT_TEST;
} else {
ctx->flags |= TEST_FLAG_PRINT_RESULTS;
}
ctx->params.rte_group = &ctx->sock_rte_group;
ctx->params.rte = &sock_rte;
ctx->params.report_arg = ctx;
return UCS_OK;
err_close_connfd:
close(connfd);
goto err;
err_close_sockfd:
close(sockfd);
err:
return status;
}
static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx)
{
close(ctx->sock_rte_group.connfd);
return UCS_OK;
}
#if HAVE_MPI
static unsigned mpi_rte_group_size(void *rte_group)
{
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
return size;
}
static unsigned mpi_rte_group_index(void *rte_group)
{
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return rank;
}
static void mpi_rte_barrier(void *rte_group, void (*progress)(void *arg),
void *arg)
{
int group_size, my_rank, i;
MPI_Request *reqs;
int nreqs = 0;
int dummy;
int flag;
#pragma omp master
/*
* Naive non-blocking barrier implementation over send/recv, to call user
* progress while waiting for completion.
* Not using MPI_Ibarrier to be compatible with MPI-1.
*/
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &group_size);
/* allocate maximal possible number of requests */
reqs = (MPI_Request*)alloca(sizeof(*reqs) * group_size);
if (my_rank == 0) {
/* root gathers "ping" from all other ranks */
for (i = 1; i < group_size; ++i) {
MPI_Irecv(&dummy, 0, MPI_INT,
i /* source */,
1 /* tag */,
MPI_COMM_WORLD,
&reqs[nreqs++]);
}
} else {
/* every non-root rank sends "ping" and waits for "pong" */
MPI_Send(&dummy, 0, MPI_INT,
0 /* dest */,
1 /* tag */,
MPI_COMM_WORLD);
MPI_Irecv(&dummy, 0, MPI_INT,
0 /* source */,
2 /* tag */,
MPI_COMM_WORLD,
&reqs[nreqs++]);
}
/* Waiting for receive requests */
do {
MPI_Testall(nreqs, reqs, &flag, MPI_STATUSES_IGNORE);
progress(arg);
} while (!flag);
if (my_rank == 0) {
/* root sends "pong" to all ranks */
for (i = 1; i < group_size; ++i) {
MPI_Send(&dummy, 0, MPI_INT,
i /* dest */,
2 /* tag */,
MPI_COMM_WORLD);
}
}
#pragma omp barrier
}
static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec,
int iovcnt, void **req)
{
int group_size;
int my_rank;
int dest, i;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &group_size);
for (dest = 0; dest < group_size; ++dest) {
if (dest == my_rank) {
continue;
}
for (i = 0; i < iovcnt; ++i) {
MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest,
i == (iovcnt - 1), /* Send last iov with tag == 1 */
MPI_COMM_WORLD);
}
}
*req = (void*)(uintptr_t)1;
}
static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max,
void *req)
{
MPI_Status status;
size_t offset;
int my_rank;
int count;
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if (src == my_rank) {
return;
}
offset = 0;
do {
ucs_assert_always(offset < max);
MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG,
MPI_COMM_WORLD, &status);
MPI_Get_count(&status, MPI_BYTE, &count);
offset += count;
} while (status.MPI_TAG != 1);
}
static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result,
void *arg, int is_final)
{
struct perftest_context *ctx = arg;
print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags,
is_final);
}
static ucx_perf_rte_t mpi_rte = {
.group_size = mpi_rte_group_size,
.group_index = mpi_rte_group_index,
.barrier = mpi_rte_barrier,
.post_vec = mpi_rte_post_vec,
.recv = mpi_rte_recv,
.exchange_vec = (void*)ucs_empty_function,
.report = mpi_rte_report,
};
#elif HAVE_RTE
static unsigned ext_rte_group_size(void *rte_group)
{
rte_group_t group = (rte_group_t)rte_group;
return rte_group_size(group);
}
static unsigned ext_rte_group_index(void *rte_group)
{
rte_group_t group = (rte_group_t)rte_group;
return rte_group_rank(group);
}
static void ext_rte_barrier(void *rte_group, void (*progress)(void *arg),
void *arg)
{
#pragma omp master
{
rte_group_t group = (rte_group_t)rte_group;
int rc;
rc = rte_barrier(group);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_barrier");
}
}
#pragma omp barrier
}
static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec,
int iovcnt, void **req)
{
rte_group_t group = (rte_group_t)rte_group;
rte_srs_session_t session;
rte_iovec_t *r_vec;
int i, rc;
rc = rte_srs_session_create(group, 0, &session);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_srs_session_create");
}
r_vec = calloc(iovcnt, sizeof(rte_iovec_t));
if (r_vec == NULL) {
return;
}
for (i = 0; i < iovcnt; ++i) {
r_vec[i].iov_base = iovec[i].iov_base;
r_vec[i].type = rte_datatype_uint8_t;
r_vec[i].count = iovec[i].iov_len;
}
rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_srs_set_data");
}
*req = session;
free(r_vec);
}
static void ext_rte_recv(void *rte_group, unsigned src, void *buffer,
size_t max, void *req)
{
rte_group_t group = (rte_group_t)rte_group;
rte_srs_session_t session = (rte_srs_session_t)req;
void *rte_buffer = NULL;
rte_iovec_t r_vec;
uint32_t offset;
int size;
int rc;
rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src),
"KEY_PERF", &rte_buffer, &size);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_srs_get_data");
return;
}
r_vec.iov_base = buffer;
r_vec.type = rte_datatype_uint8_t;
r_vec.count = max;
offset = 0;
rte_unpack(&r_vec, rte_buffer, &offset);
rc = rte_srs_session_destroy(session);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_srs_session_destroy");
}
free(rte_buffer);
}
static void ext_rte_exchange_vec(void *rte_group, void * req)
{
rte_srs_session_t session = (rte_srs_session_t)req;
int rc;
rc = rte_srs_exchange_data(session);
if (RTE_SUCCESS != rc) {
ucs_error("Failed to rte_srs_exchange_data");
}
}
static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result,
void *arg, int is_final)
{
struct perftest_context *ctx = arg;
print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags,
is_final);
}
static ucx_perf_rte_t ext_rte = {
.group_size = ext_rte_group_size,
.group_index = ext_rte_group_index,
.barrier = ext_rte_barrier,
.report = ext_rte_report,
.post_vec = ext_rte_post_vec,
.recv = ext_rte_recv,
.exchange_vec = ext_rte_exchange_vec,
};
#endif
static ucs_status_t setup_mpi_rte(struct perftest_context *ctx)
{
ucs_trace_func("");
#if HAVE_MPI
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size != 2) {
ucs_error("This test should run with exactly 2 processes (actual: %d)", size);
return UCS_ERR_INVALID_PARAM;
}
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 1) {
ctx->flags |= TEST_FLAG_PRINT_RESULTS;
}
ctx->params.rte_group = NULL;
ctx->params.rte = &mpi_rte;
ctx->params.report_arg = ctx;
#elif HAVE_RTE
rte_group_t group;
rte_init(NULL, NULL, &group);
if (1 == rte_group_rank(group)) {
ctx->flags |= TEST_FLAG_PRINT_RESULTS;
}
ctx->params.rte_group = group;
ctx->params.rte = &ext_rte;
ctx->params.report_arg = ctx;
#endif
return UCS_OK;
}
static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx)
{
#if HAVE_RTE
rte_finalize();
#endif
return UCS_OK;
}
static ucs_status_t check_system(struct perftest_context *ctx)
{
cpu_set_t cpuset;
unsigned i, count, nr_cpus;
int ret;
ucs_trace_func("");
ret = sysconf(_SC_NPROCESSORS_CONF);
if (ret < 0) {
ucs_error("failed to get local cpu count: %m");
return UCS_ERR_INVALID_PARAM;
}
nr_cpus = ret;
memset(&cpuset, 0, sizeof(cpuset));
if (ctx->flags & TEST_FLAG_SET_AFFINITY) {
if (ctx->cpu >= nr_cpus) {
ucs_error("cpu (%u) ot of range (0..%u)", ctx->cpu, nr_cpus - 1);
return UCS_ERR_INVALID_PARAM;
}
CPU_SET(ctx->cpu, &cpuset);
ret = sched_setaffinity(0, sizeof(cpuset), &cpuset);
if (ret) {
ucs_warn("sched_setaffinity() failed: %m");
return UCS_ERR_INVALID_PARAM;
}
} else {
ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
if (ret) {
ucs_warn("sched_getaffinity() failed: %m");
return UCS_ERR_INVALID_PARAM;
}
count = 0;
for (i = 0; i < CPU_SETSIZE; ++i) {
if (CPU_ISSET(i, &cpuset)) {
++count;
}
}
if (count > 2) {
ucs_warn("CPU affinity is not set (bound to %u cpus)."
" Performance may be impacted.", count);
}
}
return UCS_OK;
}
static void clone_params(ucx_perf_params_t *dest, const ucx_perf_params_t *src)
{
size_t msg_size_list_size;
*dest = *src;
msg_size_list_size = dest->msg_size_cnt * sizeof(*dest->msg_size_list);
dest->msg_size_list = malloc(msg_size_list_size);
memcpy(dest->msg_size_list, src->msg_size_list, msg_size_list_size);
}
static ucs_status_t run_test_recurs(struct perftest_context *ctx,
ucx_perf_params_t *parent_params,
unsigned depth)
{
ucx_perf_params_t params;
ucx_perf_result_t result;
ucs_status_t status;
FILE *batch_file;
int line_num;
ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files);
if (parent_params->api == UCX_PERF_API_UCP) {
if (strcmp(parent_params->uct.dev_name, TL_RESOURCE_NAME_NONE)) {
ucs_warn("-d '%s' ignored for UCP test; see NOTES section in help message",
parent_params->uct.dev_name);
}
if (strcmp(parent_params->uct.tl_name, TL_RESOURCE_NAME_NONE)) {
ucs_warn("-x '%s' ignored for UCP test; see NOTES section in help message",
parent_params->uct.tl_name);
}
}
if (depth >= ctx->num_batch_files) {
print_test_name(ctx);
return ucx_perf_run(parent_params, &result);
}
batch_file = fopen(ctx->batch_files[depth], "r");
if (batch_file == NULL) {
ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]);
return UCS_ERR_IO_ERROR;
}
clone_params(¶ms, parent_params);
line_num = 0;
while ((status = read_batch_file(batch_file, ctx->batch_files[depth],
&line_num, ¶ms,
&ctx->test_names[depth])) == UCS_OK) {
status = run_test_recurs(ctx, ¶ms, depth + 1);
free(params.msg_size_list);
free(ctx->test_names[depth]);
ctx->test_names[depth] = NULL;
clone_params(¶ms, parent_params);
}
free(params.msg_size_list);
fclose(batch_file);
return UCS_OK;
}
static ucs_status_t run_test(struct perftest_context *ctx)
{
ucs_status_t status;
ucs_trace_func("");
setlocale(LC_ALL, "en_US");
print_header(ctx);
status = run_test_recurs(ctx, &ctx->params, 0);
if (status != UCS_OK) {
ucs_error("Failed to run test: %s", ucs_status_string(status));
}
return status;
}
int main(int argc, char **argv)
{
struct perftest_context ctx;
ucs_status_t status;
int mpi_initialized;
int mpi_rte;
int ret;
#if HAVE_MPI
mpi_initialized = !isatty(0) && (MPI_Init(&argc, &argv) == 0);
#else
mpi_initialized = 0;
#endif
/* Parse command line */
status = parse_opts(&ctx, mpi_initialized, argc, argv);
if (status != UCS_OK) {
ret = (status == UCS_ERR_CANCELED) ? 0 : -127;
goto out;
}
#ifdef __COVERITY__
/* coverity[dont_call] */
mpi_rte = rand(); /* Shut up deadcode error */
#endif
if (ctx.mpi) {
mpi_rte = 1;
} else {
#if HAVE_RTE
mpi_rte = 1;
#else
mpi_rte = 0;
#endif
}
status = check_system(&ctx);
if (status != UCS_OK) {
ret = -1;
goto out;
}
/* Create RTE */
status = (mpi_rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx);
if (status != UCS_OK) {
ret = -1;
goto out;
}
/* Run the test */
status = run_test(&ctx);
if (status != UCS_OK) {
ret = -1;
goto out_cleanup_rte;
}
ret = 0;
out_cleanup_rte:
(mpi_rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx);
out:
if (ctx.params.msg_size_list) {
free(ctx.params.msg_size_list);
}
if (mpi_initialized) {
#if HAVE_MPI
MPI_Finalize();
#endif
}
return ret;
}
|
DRB002-antidep1-var-yes.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
*/
/*
A loop with loop-carried anti-dependence.
Data race pair: a[i+1]@67:10 vs. a[i]@67:5
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i;
int len = 1000;
if (argc>1)
len = atoi(argv[1]);
int a[len];
#pragma omp parallel for private(i)
for (i=0; i<len; i++)
a[i]= i;
for (i=0;i< len -1 ;i++)
a[i]=a[i+1]+1;
for (i=0; i<len; i++)
printf("%d\n", a[i]);
return 0;
}
|
par_gsmg.c | /******************************************************************************
* Copyright 1998-2019 Lawrence Livermore National Security, LLC and other
* HYPRE Project Developers. See the top-level COPYRIGHT file for details.
*
* SPDX-License-Identifier: (Apache-2.0 OR MIT)
******************************************************************************/
/******************************************************************************
*
* Geometrically smooth interpolation multigrid
*
*****************************************************************************/
#include <stdio.h>
#include <math.h>
#include "_hypre_parcsr_ls.h"
#include "par_amg.h"
#include "_hypre_lapack.h"
#ifndef ABS
#define ABS(x) ((x)>0 ? (x) : -(x))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
static HYPRE_Real mydnrm2(HYPRE_Int n, HYPRE_Real *x)
{
HYPRE_Real temp = 0.;
HYPRE_Int i;
for (i = 0; i < n; i++)
{
temp = temp + x[i] * x[i];
}
return sqrt(temp);
}
static void mydscal(HYPRE_Int n, HYPRE_Real a, HYPRE_Real *x)
{
HYPRE_Int i;
for (i = 0; i < n; i++)
{
x[i] = a * x[i];
}
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixFillSmooth
* - fill in smooth matrix
* - this function will scale the smooth vectors
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRMatrixFillSmooth(HYPRE_Int nsamples, HYPRE_Real *samples,
hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A,
HYPRE_Int num_functions, HYPRE_Int *dof_func)
{
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int n = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int i, j, k, ii, index, start;
HYPRE_Int num_cols_offd;
HYPRE_Int num_sends;
HYPRE_Int *dof_func_offd;
HYPRE_Int *int_buf_data;
HYPRE_Real temp;
HYPRE_Real *p;
HYPRE_Real *p_offd;
HYPRE_Real *p_ptr;
HYPRE_Real *buf_data;
HYPRE_Real nm;
#if 0
HYPRE_Real mx = 0., my = 1.e+10;
#endif
/* normalize each sample vector and divide by number of samples */
for (k = 0; k < nsamples; k++)
{
nm = mydnrm2(n, samples + k * n);
nm = 1. / nm / nsamples;
mydscal(n, nm, samples + k * n);
}
num_cols_offd = hypre_CSRMatrixNumCols(S_offd);
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
p_offd = hypre_CTAlloc(HYPRE_Real, nsamples * num_cols_offd, HYPRE_MEMORY_HOST);
p_ptr = p_offd;
p = samples;
for (k = 0; k < nsamples; k++)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
buf_data[index++]
= p[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data,
p_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
p = p + n;
p_offd = p_offd + num_cols_offd;
}
hypre_TFree(buf_data, HYPRE_MEMORY_HOST);
if (num_functions > 1)
{
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
}
for (i = 0; i < n; i++)
{
for (j = S_diag_i[i] + 1; j < S_diag_i[i + 1]; j++)
{
ii = S_diag_j[j];
/* only interpolate between like functions */
if (num_functions > 1 && dof_func[i] != dof_func[ii])
{
S_diag_data[j] = 0.;
continue;
}
/* explicit zeros */
if (A_diag_data[j] == 0.)
{
S_diag_data[j] = 0.;
continue;
}
temp = 0.;
p = samples;
for (k = 0; k < nsamples; k++)
{
temp = temp + ABS(p[i] - p[ii]);
p = p + n;
}
/* explicit zeros in matrix may cause this */
if (temp == 0.)
{
S_diag_data[j] = 0.;
continue;
}
temp = 1. / temp; /* reciprocal */
#if 0
my = hypre_min(my, temp);
mx = hypre_max(mx, temp);
#endif
S_diag_data[j] = temp;
}
for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++)
{
ii = S_offd_j[j];
/* only interpolate between like functions */
if (num_functions > 1 && dof_func[i] != dof_func_offd[ii])
{
S_offd_data[j] = 0.;
continue;
}
/* explicit zeros */
if (A_offd_data[j] == 0.)
{
S_offd_data[j] = 0.;
continue;
}
temp = 0.;
p = samples;
p_offd = p_ptr;
for (k = 0; k < nsamples; k++)
{
temp = temp + ABS(p[i] - p_offd[ii]);
p = p + n;
p_offd = p_offd + num_cols_offd;
}
/* explicit zeros in matrix may cause this */
if (temp == 0.)
{
S_offd_data[j] = 0.;
continue;
}
temp = 1. / temp; /* reciprocal */
#if 0
my = hypre_min(my, temp);
mx = hypre_max(mx, temp);
#endif
S_offd_data[j] = temp;
}
}
#if 0
hypre_printf("MIN, MAX: %f %f\n", my, mx);
#endif
hypre_TFree(p_ptr, HYPRE_MEMORY_HOST);
if (num_functions > 1)
{
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
}
return 0;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixChooseThresh
*--------------------------------------------------------------------------*/
HYPRE_Real
hypre_ParCSRMatrixChooseThresh(hypre_ParCSRMatrix *S)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag);
HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd);
HYPRE_Int n = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int i, j;
HYPRE_Real mx, minimax = 1.e+10;
HYPRE_Real minmin;
for (i = 0; i < n; i++)
{
mx = 0.;
for (j = S_diag_i[i]; j < S_diag_i[i + 1]; j++)
{
mx = hypre_max(mx, S_diag_data[j]);
}
for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++)
{
mx = hypre_max(mx, S_offd_data[j]);
}
if (mx != 0.)
{
minimax = hypre_min(minimax, mx);
}
}
hypre_MPI_Allreduce(&minimax, &minmin, 1, HYPRE_MPI_REAL, hypre_MPI_MIN, comm);
return minmin;
}
/*--------------------------------------------------------------------------
* hypre_ParCSRMatrixThreshold
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_ParCSRMatrixThreshold(hypre_ParCSRMatrix *A, HYPRE_Real thresh)
{
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag);
HYPRE_Int num_nonzeros_diag = A_diag_i[n];
HYPRE_Int num_nonzeros_offd = A_offd_i[n];
HYPRE_Int *S_diag_i;
HYPRE_Int *S_diag_j;
HYPRE_Real *S_diag_data;
HYPRE_Int *S_offd_i;
HYPRE_Int *S_offd_j;
HYPRE_Real *S_offd_data;
HYPRE_Int count, i, jS, jA;
/* first count the number of nonzeros we will need */
count = 0;
for (i = 0; i < num_nonzeros_diag; i++)
if (A_diag_data[i] >= thresh)
{
count++;
}
/* allocate vectors */
S_diag_i = hypre_CTAlloc(HYPRE_Int, n + 1, HYPRE_MEMORY_HOST);
S_diag_j = hypre_CTAlloc(HYPRE_Int, count, HYPRE_MEMORY_HOST);
S_diag_data = hypre_CTAlloc(HYPRE_Real, count, HYPRE_MEMORY_HOST);
jS = 0;
for (i = 0; i < n; i++)
{
S_diag_i[i] = jS;
for (jA = A_diag_i[i]; jA < A_diag_i[i + 1]; jA++)
{
if (A_diag_data[jA] >= thresh)
{
S_diag_data[jS] = A_diag_data[jA];
S_diag_j[jS] = A_diag_j[jA];
jS++;
}
}
}
S_diag_i[n] = jS;
hypre_CSRMatrixNumNonzeros(A_diag) = jS;
/* free the vectors we don't need */
hypre_TFree(A_diag_i, HYPRE_MEMORY_HOST);
hypre_TFree(A_diag_j, HYPRE_MEMORY_HOST);
hypre_TFree(A_diag_data, HYPRE_MEMORY_HOST);
/* assign the new vectors */
hypre_CSRMatrixI(A_diag) = S_diag_i;
hypre_CSRMatrixJ(A_diag) = S_diag_j;
hypre_CSRMatrixData(A_diag) = S_diag_data;
/*
* Offd part
*/
/* first count the number of nonzeros we will need */
count = 0;
for (i = 0; i < num_nonzeros_offd; i++)
if (A_offd_data[i] >= thresh)
{
count++;
}
/* allocate vectors */
S_offd_i = hypre_CTAlloc(HYPRE_Int, n + 1, HYPRE_MEMORY_HOST);
S_offd_j = hypre_CTAlloc(HYPRE_Int, count, HYPRE_MEMORY_HOST);
S_offd_data = hypre_CTAlloc(HYPRE_Real, count, HYPRE_MEMORY_HOST);
jS = 0;
for (i = 0; i < n; i++)
{
S_offd_i[i] = jS;
for (jA = A_offd_i[i]; jA < A_offd_i[i + 1]; jA++)
{
if (A_offd_data[jA] >= thresh)
{
S_offd_data[jS] = A_offd_data[jA];
S_offd_j[jS] = A_offd_j[jA];
jS++;
}
}
}
S_offd_i[n] = jS;
hypre_CSRMatrixNumNonzeros(A_offd) = jS;
/* free the vectors we don't need */
hypre_TFree(A_offd_i, HYPRE_MEMORY_HOST);
hypre_TFree(A_offd_j, HYPRE_MEMORY_HOST);
hypre_TFree(A_offd_data, HYPRE_MEMORY_HOST);
/* assign the new vectors */
hypre_CSRMatrixI(A_offd) = S_offd_i;
hypre_CSRMatrixJ(A_offd) = S_offd_j;
hypre_CSRMatrixData(A_offd) = S_offd_data;
return 0;
}
/*--------------------------------------------------------------------------
* CreateSmoothVecs
* - smoother depends on the level being used
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCreateSmoothVecs(void *data,
hypre_ParCSRMatrix *A,
HYPRE_Int num_sweeps,
HYPRE_Int level,
HYPRE_Real **SmoothVecs_p)
{
hypre_ParAMGData *amg_data = (hypre_ParAMGData*) data;
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
hypre_ParVector *Zero;
hypre_ParVector *Temp;
hypre_ParVector *U;
hypre_ParVector *Qtemp = NULL;
HYPRE_Int i;
HYPRE_BigInt n = hypre_ParCSRMatrixGlobalNumRows(A);
HYPRE_Int n_local = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt *starts = hypre_ParCSRMatrixRowStarts(A);
HYPRE_Int sample;
HYPRE_Int nsamples = hypre_ParAMGDataNumSamples(amg_data);
HYPRE_Int ret;
HYPRE_Real *datax, *bp, *p;
HYPRE_Int rlx_type;
HYPRE_Int smooth_type;
HYPRE_Int smooth_option = 0;
HYPRE_Int smooth_num_levels;
HYPRE_Solver *smoother;
HYPRE_Int debug_flag = hypre_ParAMGDataDebugFlag(amg_data);
HYPRE_Int num_threads;
num_threads = hypre_NumThreads();
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
if (debug_flag >= 1)
hypre_printf("Creating smooth dirs, %d sweeps, %d samples\n", num_sweeps,
nsamples);
smooth_type = hypre_ParAMGDataSmoothType(amg_data);
smooth_num_levels = hypre_ParAMGDataSmoothNumLevels(amg_data);
if (smooth_num_levels > level)
{
smooth_option = smooth_type;
smoother = hypre_ParAMGDataSmoother(amg_data);
num_sweeps = hypre_ParAMGDataSmoothNumSweeps(amg_data);
}
rlx_type = hypre_ParAMGDataGridRelaxType(amg_data)[0];
/* rlx_wt = hypre_ParAMGDataRelaxWeight(amg_data)[level]; */
/* omega = hypre_ParAMGDataOmega(amg_data)[level]; */
/* generate par vectors */
Zero = hypre_ParVectorCreate(comm, n, starts);
hypre_ParVectorInitialize(Zero);
datax = hypre_VectorData(hypre_ParVectorLocalVector(Zero));
for (i = 0; i < n_local; i++)
{
datax[i] = 0.;
}
Temp = hypre_ParVectorCreate(comm, n, starts);
hypre_ParVectorInitialize(Temp);
datax = hypre_VectorData(hypre_ParVectorLocalVector(Temp));
for (i = 0; i < n_local; i++)
{
datax[i] = 0.;
}
U = hypre_ParVectorCreate(comm, n, starts);
hypre_ParVectorInitialize(U);
datax = hypre_VectorData(hypre_ParVectorLocalVector(U));
if (num_threads > 1)
{
Qtemp = hypre_ParVectorCreate(comm, n, starts);
hypre_ParVectorInitialize(Qtemp);
}
/* allocate space for the vectors */
bp = hypre_CTAlloc(HYPRE_Real, nsamples * n_local, HYPRE_MEMORY_HOST);
p = bp;
/* generate random vectors */
for (sample = 0; sample < nsamples; sample++)
{
for (i = 0; i < n_local; i++)
{
datax[i] = hypre_Rand() - .5;
}
for (i = 0; i < num_sweeps; i++)
{
if (smooth_option == 6)
{
HYPRE_SchwarzSolve(smoother[level],
(HYPRE_ParCSRMatrix) A,
(HYPRE_ParVector) Zero,
(HYPRE_ParVector) U);
}
else
{
ret = hypre_BoomerAMGRelax(A, Zero, NULL /*CFmarker*/,
rlx_type, 0 /*rel pts*/, 1.0 /*weight*/,
1.0 /*omega*/, NULL, U, Temp,
Qtemp);
hypre_assert(ret == 0);
}
}
/* copy out the solution */
for (i = 0; i < n_local; i++)
{
*p++ = datax[i];
}
}
hypre_ParVectorDestroy(Zero);
hypre_ParVectorDestroy(Temp);
hypre_ParVectorDestroy(U);
if (num_threads > 1)
{
hypre_ParVectorDestroy(Qtemp);
}
*SmoothVecs_p = bp;
return 0;
}
/*--------------------------------------------------------------------------
* CreateSmoothDirs replaces CreateS in AMG
* - smoother depends on the level being used
* - in this version, CreateSmoothVecs must be called prior to this function
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGCreateSmoothDirs(void *data,
hypre_ParCSRMatrix *A,
HYPRE_Real *SmoothVecs,
HYPRE_Real thresh,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
hypre_ParCSRMatrix **S_ptr)
{
hypre_ParAMGData *amg_data = (hypre_ParAMGData*) data;
hypre_ParCSRMatrix *S;
HYPRE_Real minimax;
HYPRE_Int debug_flag = hypre_ParAMGDataDebugFlag(amg_data);
S = hypre_ParCSRMatrixClone(A, 0);
/* Traverse S and fill in differences */
hypre_ParCSRMatrixFillSmooth(
hypre_ParAMGDataNumSamples(amg_data), SmoothVecs,
S, A, num_functions, dof_func);
minimax = hypre_ParCSRMatrixChooseThresh(S);
if (debug_flag >= 1)
{
hypre_printf("Minimax chosen: %f\n", minimax);
}
/* Threshold and compress */
hypre_ParCSRMatrixThreshold(S, thresh * minimax);
*S_ptr = S;
return 0;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGNormalizeVecs
*
* Normalize the smooth vectors and also make the first vector the constant
* vector
*
* inputs:
* n = length of smooth vectors
* num = number of smooth vectors
* V = smooth vectors (array of length n*num), also an output
*
* output:
* V = adjusted smooth vectors
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGNormalizeVecs(HYPRE_Int n, HYPRE_Int num, HYPRE_Real *V)
{
HYPRE_Int i, j;
HYPRE_Real nrm;
/* change first vector to the constant vector */
for (i = 0; i < n; i++)
{
V[i] = 1.0;
}
for (j = 0; j < num; j++)
{
nrm = mydnrm2(n, &V[j * n]);
mydscal(n, 1. / nrm, &V[j * n]);
}
return 0;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGFitVectors
*
* Construct interpolation weights based on fitting smooth vectors
*
* inputs:
* ip = row number of row in P being processed (0-based)
* n = length of smooth vectors
* num = number of smooth vectors
* V = smooth vectors (array of length n*num), also an output
* nc = number of coarse grid points
* ind = indices of coarse grid points (0-based)
*
* output:
* val = interpolation weights for the coarse grid points
* V = smooth vectors; first one has been changed to constant vector;
* vectors have also been normalized; this is also an input
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGFitVectors(HYPRE_Int ip, HYPRE_Int n, HYPRE_Int num, const HYPRE_Real *V,
HYPRE_Int nc, const HYPRE_Int *ind, HYPRE_Real *val)
{
HYPRE_Real *a, *b;
HYPRE_Real *ap;
HYPRE_Int i, j;
HYPRE_Real *work;
HYPRE_Int work_size;
HYPRE_Int info;
HYPRE_Int temp;
/*
hypre_printf("Fit: row %d, n %d num %d, nc = %d ", ip, n, num, nc);
for (i=0; i<nc; i++)
hypre_printf("%d ", ind[i]);
hypre_printf("\n");
*/
if (nc == 0)
{
return 0;
}
work_size = 2000 * 64;
work = hypre_CTAlloc(HYPRE_Real, work_size, HYPRE_MEMORY_HOST);
a = hypre_CTAlloc(HYPRE_Real, num * nc, HYPRE_MEMORY_HOST);
ap = a;
for (j = 0; j < nc; j++)
{
for (i = 0; i < num; i++)
{
*ap = V[i * n + ind[j]];
ap++;
}
}
temp = MAX(nc, num);
b = hypre_CTAlloc(HYPRE_Real, temp, HYPRE_MEMORY_HOST);
for (i = 0; i < num; i++)
{
b[i] = V[i * n + ip];
}
{
char trans = 'N';
HYPRE_Int one = 1;
hypre_dgels(&trans, &num, &nc, &one, a, &num,
b, &temp, work, &work_size, &info);
if (info != 0)
{
hypre_error_w_msg(HYPRE_ERROR_GENERIC, "par_gsmg: dgels returned %d\n");
}
/* copy solution into output vector */
for (j = 0; j < nc; j++)
{
val[j] = b[j];
}
}
hypre_TFree(b, HYPRE_MEMORY_HOST);
hypre_TFree(a, HYPRE_MEMORY_HOST);
hypre_TFree(work, HYPRE_MEMORY_HOST);
return info;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildInterpLS
*
* Interpolation built from fitting smooth vectors
* - sequential version only
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildInterpLS( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int num_smooth,
HYPRE_Real *SmoothVecs,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
/* HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag); */
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
/* HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); */
HYPRE_Int num_cols_S_offd = hypre_CSRMatrixNumCols(S_offd);
/* HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(S); */
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *tmp_map_offd = NULL;
HYPRE_Int *CF_marker_offd;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *S_ext;
//HYPRE_Real *S_ext_data;
//HYPRE_Int *S_ext_i;
//HYPRE_BigInt *S_ext_j;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size;
HYPRE_Int P_offd_size;
HYPRE_Int *P_marker;
/* HYPRE_Int *P_marker_offd; */
HYPRE_Int jj_counter, jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
/* HYPRE_Int jj_begin_row,jj_begin_row_offd;
HYPRE_Int jj_end_row,jj_end_row_offd; */
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int *fine_to_coarse;
//HYPRE_BigInt *fine_to_coarse_offd;
HYPRE_Int *coarse_counter;
HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
HYPRE_Int num_cols_P_offd;
//HYPRE_BigInt my_first_cpt;
HYPRE_Int i, i1;
HYPRE_Int j, jl, jj;
HYPRE_Int start;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int *int_buf_data;
//HYPRE_BigInt *big_buf_data;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm, &my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[my_id];
total_global_cpts = num_cpts_global[num_procs];
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_S_offd)
{
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST);
}
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(S);
comm_pkg = hypre_ParCSRMatrixCommPkg(S);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*----------------------------------------------------------------------
* Get the ghost rows of S
*---------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
if (num_procs > 1)
{
S_ext = hypre_ParCSRMatrixExtractBExt(S, S, 1);
//S_ext_i = hypre_CSRMatrixI(S_ext);
//S_ext_j = hypre_CSRMatrixBigJ(S_ext);
//S_ext_data = hypre_CSRMatrixData(S_ext);
}
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 2 Get S_ext = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; }
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine / num_threads;
rest = n_fine - size * num_threads;
if (j < rest)
{
ns = j * size + j;
ne = (j + 1) * size + j + 1;
}
else
{
ns = j * size + rest;
ne = (j + 1) * size + rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] >= 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
/* removed */
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i = 0; i < num_threads - 1; i++)
{
coarse_counter[i + 1] += coarse_counter[i];
jj_count[i + 1] += jj_count[i];
jj_count_offd[i + 1] += jj_count_offd[i];
}
i = num_threads - 1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
/*fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_S_offd, HYPRE_MEMORY_HOST);
big_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
coarse_shift = 0;
if (j > 0) { coarse_shift = coarse_counter[j - 1]; }
size = n_fine / num_threads;
rest = n_fine - size * num_threads;
if (j < rest)
{
ns = j * size + j;
ne = (j + 1) * size + j + 1;
}
else
{
ns = j * size + rest;
ne = (j + 1) * size + rest;
}
for (i = ns; i < ne; i++)
{
fine_to_coarse[i] += coarse_shift;
}
}
/*index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
big_buf_data[index++]
= my_first_cpt+(HYPRE_BigInt)fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 21, comm_pkg, big_buf_data,
fine_to_coarse_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (debug_flag==4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n",
my_id, wall_time);
fflush(NULL);
}
if (debug_flag==4) wall_time = time_getWallclockSeconds();*/
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,jj,ns,ne,size,rest,P_marker,jj_counter,jj_counter_offd) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
size = n_fine / num_threads;
rest = n_fine - size * num_threads;
if (jl < rest)
{
ns = jl * size + jl;
ne = (jl + 1) * size + jl + 1;
}
else
{
ns = jl * size + rest;
ne = (jl + 1) * size + rest;
}
jj_counter = 0;
if (jl > 0) { jj_counter = jj_count[jl - 1]; }
jj_counter_offd = 0;
if (jl > 0) { jj_counter_offd = jj_count_offd[jl - 1]; }
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
HYPRE_Int kk;
HYPRE_Int indices[1000]; /* kludge */
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
kk = 0;
for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_diag_j[jj_counter] = fine_to_coarse[i1];
jj_counter++;
indices[kk] = i1;
kk++;
}
}
hypre_BoomerAMGFitVectors(i, n_fine, num_smooth, SmoothVecs,
kk, indices, &P_diag_data[P_diag_i[i]]);
/* Off-Diagonal part of P */
/* undone */
}
}
}
P_diag_i[i] = jj_counter; /* check that this is in right place for threads */
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(S),
total_global_cpts,
hypre_ParCSRMatrixColStarts(S),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, 0);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < P_offd_size; i++)
{
P_marker[i] = P_offd_j[i];
}
hypre_qsort0(P_marker, 0, P_offd_size - 1);
num_cols_P_offd = 1;
index = P_marker[0];
for (i = 1; i < P_offd_size; i++)
{
if (P_marker[i] > index)
{
index = P_marker[i];
P_marker[num_cols_P_offd++] = index;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
for (i = 0; i < num_cols_P_offd; i++)
{
tmp_map_offd[i] = P_marker[i];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P, S, fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
//hypre_TFree(big_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
if (num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); }
return (0);
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildInterpGSMG
*
* Difference with hypre_BoomerAMGBuildInterp is that S contains values
* and is used to build interpolation weights. Matrix A is not used.
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildInterpGSMG( hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
hypre_ParCSRMatrix **P_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int num_cols_S_offd = hypre_CSRMatrixNumCols(S_offd);
HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(S);
HYPRE_Int *tmp_map_offd = NULL;
hypre_ParCSRMatrix *P;
HYPRE_BigInt *col_map_offd_P;
HYPRE_Int *CF_marker_offd;
HYPRE_Int *dof_func_offd = NULL;
hypre_CSRMatrix *S_ext;
HYPRE_Real *S_ext_data;
HYPRE_Int *S_ext_i;
HYPRE_BigInt *S_ext_j;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data;
HYPRE_Int *P_diag_i;
HYPRE_Int *P_diag_j;
HYPRE_Real *P_offd_data;
HYPRE_Int *P_offd_i;
HYPRE_Int *P_offd_j;
HYPRE_Int P_diag_size, P_offd_size;
HYPRE_Int *P_marker, *P_marker_offd;
HYPRE_Int jj_counter, jj_counter_offd;
HYPRE_Int *jj_count, *jj_count_offd;
HYPRE_Int jj_begin_row, jj_begin_row_offd;
HYPRE_Int jj_end_row, jj_end_row_offd;
HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int strong_f_marker;
HYPRE_Int *fine_to_coarse;
HYPRE_Int *coarse_counter;
//HYPRE_Int coarse_shift;
HYPRE_BigInt total_global_cpts;
HYPRE_Int num_cols_P_offd;
//HYPRE_BigInt my_first_cpt;
HYPRE_BigInt big_i2;
HYPRE_Int i, i1, i2;
HYPRE_Int j, jl, jj, jj1;
HYPRE_Int start;
HYPRE_Int c_num;
HYPRE_Real sum;
HYPRE_Real distribute;
HYPRE_Real zero = 0.0;
HYPRE_Real one = 1.0;
HYPRE_Int my_id;
HYPRE_Int num_procs;
HYPRE_Int num_threads;
HYPRE_Int num_sends;
HYPRE_Int index;
HYPRE_Int ns, ne, size, rest;
HYPRE_Int *int_buf_data;
HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(S);
HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(S_diag);
HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows;
HYPRE_Real wall_time; /* for debugging instrumentation */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm, &my_id);
num_threads = hypre_NumThreads();
//my_first_cpt = num_cpts_global[0];
total_global_cpts = 0; /* we will set this later for the matrix in the setup */
/* if (myid == (num_procs -1)) total_global_cpts = coarse_pts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm);*/
/*-------------------------------------------------------------------
* Get the CF_marker data for the off-processor columns
*-------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST);
if (num_functions > 1 && num_cols_S_offd)
{
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST);
}
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(S);
comm_pkg = hypre_ParCSRMatrixCommPkg(S);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends), HYPRE_MEMORY_HOST);
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++)
int_buf_data[index++]
= dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)];
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data,
dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*----------------------------------------------------------------------
* Get the ghost rows of S
*---------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
if (num_procs > 1)
{
S_ext = hypre_ParCSRMatrixExtractBExt(S, S, 1);
S_ext_i = hypre_CSRMatrixI(S_ext);
S_ext_j = hypre_CSRMatrixBigJ(S_ext);
S_ext_data = hypre_CSRMatrixData(S_ext);
}
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Comm 2 Get S_ext = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* First Pass: Determine size of P and fill in fine_to_coarse mapping.
*-----------------------------------------------------------------------*/
/*-----------------------------------------------------------------------
* Intialize counters and allocate mapping vector.
*-----------------------------------------------------------------------*/
coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; }
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
/*-----------------------------------------------------------------------
* Loop over fine grid.
*-----------------------------------------------------------------------*/
/* RDF: this looks a little tricky, but doable */
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE
#endif
for (j = 0; j < num_threads; j++)
{
size = n_fine / num_threads;
rest = n_fine - size * num_threads;
if (j < rest)
{
ns = j * size + j;
ne = (j + 1) * size + j + 1;
}
else
{
ns = j * size + rest;
ne = (j + 1) * size + rest;
}
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a C-point, interpolation is the identity. Also set up
* mapping vector.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
jj_count[j]++;
fine_to_coarse[i] = coarse_counter[j];
coarse_counter[j]++;
}
/*--------------------------------------------------------------------
* If i is an F-point, interpolation is from the C-points that
* strongly influence i.
*--------------------------------------------------------------------*/
else
{
for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++)
{
i1 = S_diag_j[jj];
if (CF_marker[i1] >= 0)
{
jj_count[j]++;
}
}
if (num_procs > 1)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++)
{
i1 = S_offd_j[jj];
if (CF_marker_offd[i1] >= 0)
{
jj_count_offd[j]++;
}
}
}
}
}
}
/*-----------------------------------------------------------------------
* Allocate arrays.
*-----------------------------------------------------------------------*/
for (i = 0; i < num_threads - 1; i++)
{
coarse_counter[i + 1] += coarse_counter[i];
jj_count[i + 1] += jj_count[i];
jj_count_offd[i + 1] += jj_count_offd[i];
}
i = num_threads - 1;
jj_counter = jj_count[i];
jj_counter_offd = jj_count_offd[i];
P_diag_size = jj_counter;
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST);
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST);
P_diag_i[n_fine] = jj_counter;
P_offd_size = jj_counter_offd;
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST);
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST);
/*-----------------------------------------------------------------------
* Intialize some stuff.
*-----------------------------------------------------------------------*/
jj_counter = start_indexing;
jj_counter_offd = start_indexing;
if (debug_flag == 4)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Interp: Internal work 1 = %f\n",
my_id, wall_time);
fflush(NULL);
}
/*-----------------------------------------------------------------------
* Send and receive fine_to_coarse info.
*-----------------------------------------------------------------------*/
if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); }
/*-----------------------------------------------------------------------
* Loop over fine grid points.
*-----------------------------------------------------------------------*/
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i,j,jl,i1,i2,jj,jj1,ns,ne,size,rest,sum,distribute,P_marker,P_marker_offd,strong_f_marker,jj_counter,jj_counter_offd,c_num,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd) HYPRE_SMP_SCHEDULE
#endif
for (jl = 0; jl < num_threads; jl++)
{
size = n_fine / num_threads;
rest = n_fine - size * num_threads;
if (jl < rest)
{
ns = jl * size + jl;
ne = (jl + 1) * size + jl + 1;
}
else
{
ns = jl * size + rest;
ne = (jl + 1) * size + rest;
}
jj_counter = 0;
if (jl > 0) { jj_counter = jj_count[jl - 1]; }
jj_counter_offd = 0;
if (jl > 0) { jj_counter_offd = jj_count_offd[jl - 1]; }
P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST);
P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST);
for (i = 0; i < n_fine; i++)
{
P_marker[i] = -1;
}
for (i = 0; i < num_cols_S_offd; i++)
{
P_marker_offd[i] = -1;
}
strong_f_marker = -2;
for (i = ns; i < ne; i++)
{
/*--------------------------------------------------------------------
* If i is a c-point, interpolation is the identity.
*--------------------------------------------------------------------*/
if (CF_marker[i] >= 0)
{
P_diag_i[i] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i];
P_diag_data[jj_counter] = one;
jj_counter++;
}
/*--------------------------------------------------------------------
* If i is an F-point, build interpolation.
*--------------------------------------------------------------------*/
else
{
/* Diagonal part of P */
P_diag_i[i] = jj_counter;
jj_begin_row = jj_counter;
for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_diag_j
* and initialize interpolation weight to zero.
*--------------------------------------------------------------*/
if (CF_marker[i1] >= 0)
{
P_marker[i1] = jj_counter;
P_diag_j[jj_counter] = fine_to_coarse[i1];
P_diag_data[jj_counter] = zero;
jj_counter++;
}
/*--------------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*--------------------------------------------------------------*/
else
{
P_marker[i1] = strong_f_marker;
}
}
jj_end_row = jj_counter;
/* Off-Diagonal part of P */
P_offd_i[i] = jj_counter_offd;
jj_begin_row_offd = jj_counter_offd;
if (num_procs > 1)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++)
{
i1 = S_offd_j[jj];
/*-----------------------------------------------------------
* If neighbor i1 is a C-point, set column number in P_offd_j
* and initialize interpolation weight to zero.
*-----------------------------------------------------------*/
if (CF_marker_offd[i1] >= 0)
{
P_marker_offd[i1] = jj_counter_offd;
P_offd_j[jj_counter_offd] = i1;
P_offd_data[jj_counter_offd] = zero;
jj_counter_offd++;
}
/*-----------------------------------------------------------
* If neighbor i1 is an F-point, mark it as a strong F-point
* whose connection needs to be distributed.
*-----------------------------------------------------------*/
else
{
P_marker_offd[i1] = strong_f_marker;
}
}
}
jj_end_row_offd = jj_counter_offd;
/* Loop over ith row of S. First, the diagonal part of S */
for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++)
{
i1 = S_diag_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker[i1] >= jj_begin_row)
{
P_diag_data[P_marker[i1]] += S_diag_data[jj];
}
/*--------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
*--------------------------------------------------------------*/
else if (P_marker[i1] == strong_f_marker)
{
sum = zero;
/*-----------------------------------------------------------
* Loop over row of S for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*-----------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1 + 1]; jj1++)
{
i2 = S_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row)
{
sum += S_diag_data[jj1];
}
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1 + 1]; jj1++)
{
i2 = S_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd)
{
sum += S_offd_data[jj1];
}
}
}
if (sum != 0)
{
distribute = S_diag_data[jj] / sum;
/*-----------------------------------------------------------
* Loop over row of S for point i1 and do the distribution.
*-----------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1 + 1]; jj1++)
{
i2 = S_diag_j[jj1];
if (P_marker[i2] >= jj_begin_row)
P_diag_data[P_marker[i2]]
+= distribute * S_diag_data[jj1];
}
/* Off-Diagonal block part of row i1 */
if (num_procs > 1)
{
for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1 + 1]; jj1++)
{
i2 = S_offd_j[jj1];
if (P_marker_offd[i2] >= jj_begin_row_offd)
P_offd_data[P_marker_offd[i2]]
+= distribute * S_offd_data[jj1];
}
}
}
else
{
/* do nothing */
}
}
/*--------------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal.
*--------------------------------------------------------------*/
else
{
/* do nothing */
}
}
/*----------------------------------------------------------------
* Still looping over ith row of S. Next, loop over the
* off-diagonal part of S
*---------------------------------------------------------------*/
if (num_procs > 1)
{
for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++)
{
i1 = S_offd_j[jj];
/*--------------------------------------------------------------
* Case 1: neighbor i1 is a C-point and strongly influences i,
* accumulate a_{i,i1} into the interpolation weight.
*--------------------------------------------------------------*/
if (P_marker_offd[i1] >= jj_begin_row_offd)
{
P_offd_data[P_marker_offd[i1]] += S_offd_data[jj];
}
/*------------------------------------------------------------
* Case 2: neighbor i1 is an F-point and strongly influences i,
* distribute a_{i,i1} to C-points that strongly infuence i.
* Note: currently no distribution to the diagonal in this case.
*-----------------------------------------------------------*/
else if (P_marker_offd[i1] == strong_f_marker)
{
sum = zero;
/*---------------------------------------------------------
* Loop over row of S_ext for point i1 and calculate the sum
* of the connections to c-points that strongly influence i.
*---------------------------------------------------------*/
/* find row number */
c_num = S_offd_j[jj];
for (jj1 = S_ext_i[c_num]; jj1 < S_ext_i[c_num + 1]; jj1++)
{
big_i2 = S_ext_j[jj1];
if (big_i2 >= col_1 && big_i2 < col_n)
{
/* in the diagonal block */
if (P_marker[(HYPRE_Int)(big_i2 - col_1)] >= jj_begin_row)
{
sum += S_ext_data[jj1];
}
}
else
{
/* in the off_diagonal block */
j = hypre_BigBinarySearch(col_map_offd, big_i2, num_cols_S_offd);
if (j != -1)
{
if (P_marker_offd[j] >= jj_begin_row_offd)
{
sum += S_ext_data[jj1];
}
}
}
}
if (sum != 0)
{
distribute = S_offd_data[jj] / sum;
/*---------------------------------------------------------
* Loop over row of S_ext for point i1 and do
* the distribution.
*--------------------------------------------------------*/
/* Diagonal block part of row i1 */
for (jj1 = S_ext_i[c_num]; jj1 < S_ext_i[c_num + 1]; jj1++)
{
big_i2 = S_ext_j[jj1];
if (big_i2 >= col_1 && big_i2 < col_n) /* in the diagonal block */
{
if (P_marker[(HYPRE_Int)(big_i2 - col_1)] >= jj_begin_row)
P_diag_data[P_marker[(HYPRE_Int)(big_i2 - col_1)]]
+= distribute * S_ext_data[jj1];
}
else
{
/* check to see if it is in the off_diagonal block */
j = hypre_BigBinarySearch(col_map_offd, big_i2, num_cols_S_offd);
if (j != -1)
{
if (P_marker_offd[j] >= jj_begin_row_offd)
P_offd_data[P_marker_offd[j]]
+= distribute * S_ext_data[jj1];
}
}
}
}
else
{
/* do nothing */
}
}
/*-----------------------------------------------------------
* Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1}
* into the diagonal.
*-----------------------------------------------------------*/
else
{
/* do nothing */
}
}
}
/*-----------------------------------------------------------------
* Set interpolation weight by dividing by the diagonal.
*-----------------------------------------------------------------*/
sum = 0.;
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
sum += P_diag_data[jj];
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
sum += P_offd_data[jj];
}
for (jj = jj_begin_row; jj < jj_end_row; jj++)
{
P_diag_data[jj] /= sum;
}
for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++)
{
P_offd_data[jj] /= sum;
}
}
strong_f_marker--;
P_offd_i[i + 1] = jj_counter_offd;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST);
}
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(S),
total_global_cpts,
hypre_ParCSRMatrixColStarts(S),
num_cpts_global,
0,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0)
{
hypre_BoomerAMGInterpTruncation(P, trunc_factor, 0);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
}
num_cols_P_offd = 0;
if (P_offd_size)
{
P_marker = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < P_offd_size; i++)
{
P_marker[i] = P_offd_j[i];
}
hypre_qsort0(P_marker, 0, P_offd_size - 1);
num_cols_P_offd = 1;
index = P_marker[0];
for (i = 1; i < P_offd_size; i++)
{
if (P_marker[i] > index)
{
index = P_marker[i];
P_marker[num_cols_P_offd++] = index;
}
}
col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST);
tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
for (i = 0; i < num_cols_P_offd; i++)
{
tmp_map_offd[i] = P_marker[i];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i = 0; i < P_offd_size; i++)
P_offd_j[i] = hypre_BinarySearch(tmp_map_offd,
P_offd_j[i],
num_cols_P_offd);
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
}
if (num_cols_P_offd)
{
hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P;
hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd;
}
hypre_GetCommPkgRTFromCommPkgA(P, S, fine_to_coarse, tmp_map_offd);
*P_ptr = P;
hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST);
hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count, HYPRE_MEMORY_HOST);
hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST);
if (num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); }
return (0);
}
|
common.h | #ifndef LIGHTGBM_UTILS_COMMON_FUN_H_
#define LIGHTGBM_UTILS_COMMON_FUN_H_
#include <LightGBM/utils/log.h>
#include <LightGBM/utils/openmp_wrapper.h>
#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
#include <cstdint>
#include <algorithm>
#include <cmath>
#include <functional>
#include <memory>
#include <iterator>
#include <type_traits>
#include <iomanip>
#ifdef _MSC_VER
#include "intrin.h"
#endif
namespace LightGBM {
namespace Common {
inline static char tolower(char in) {
if (in <= 'Z' && in >= 'A')
return in - ('Z' - 'z');
return in;
}
inline static std::string Trim(std::string str) {
if (str.empty()) {
return str;
}
str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1);
str.erase(0, str.find_first_not_of(" \f\n\r\t\v"));
return str;
}
inline static std::string RemoveQuotationSymbol(std::string str) {
if (str.empty()) {
return str;
}
str.erase(str.find_last_not_of("'\"") + 1);
str.erase(0, str.find_first_not_of("'\""));
return str;
}
inline static bool StartsWith(const std::string& str, const std::string prefix) {
if (str.substr(0, prefix.size()) == prefix) {
return true;
} else {
return false;
}
}
inline static std::vector<std::string> Split(const char* c_str, char delimiter) {
std::vector<std::string> ret;
std::string str(c_str);
size_t i = 0;
size_t pos = 0;
while (pos < str.length()) {
if (str[pos] == delimiter) {
if (i < pos) {
ret.push_back(str.substr(i, pos - i));
}
++pos;
i = pos;
} else {
++pos;
}
}
if (i < pos) {
ret.push_back(str.substr(i));
}
return ret;
}
inline static std::vector<std::string> SplitLines(const char* c_str) {
std::vector<std::string> ret;
std::string str(c_str);
size_t i = 0;
size_t pos = 0;
while (pos < str.length()) {
if (str[pos] == '\n' || str[pos] == '\r') {
if (i < pos) {
ret.push_back(str.substr(i, pos - i));
}
// skip the line endings
while (str[pos] == '\n' || str[pos] == '\r') ++pos;
// new begin
i = pos;
} else {
++pos;
}
}
if (i < pos) {
ret.push_back(str.substr(i));
}
return ret;
}
inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) {
std::vector<std::string> ret;
std::string str(c_str);
size_t i = 0;
size_t pos = 0;
while (pos < str.length()) {
bool met_delimiters = false;
for (int j = 0; delimiters[j] != '\0'; ++j) {
if (str[pos] == delimiters[j]) {
met_delimiters = true;
break;
}
}
if (met_delimiters) {
if (i < pos) {
ret.push_back(str.substr(i, pos - i));
}
++pos;
i = pos;
} else {
++pos;
}
}
if (i < pos) {
ret.push_back(str.substr(i));
}
return ret;
}
template<typename T>
inline static const char* Atoi(const char* p, T* out) {
int sign;
T value;
while (*p == ' ') {
++p;
}
sign = 1;
if (*p == '-') {
sign = -1;
++p;
} else if (*p == '+') {
++p;
}
for (value = 0; *p >= '0' && *p <= '9'; ++p) {
value = value * 10 + (*p - '0');
}
*out = static_cast<T>(sign * value);
while (*p == ' ') {
++p;
}
return p;
}
template<typename T>
inline static double Pow(T base, int power) {
if (power < 0) {
return 1.0 / Pow(base, -power);
} else if (power == 0) {
return 1;
} else if (power % 2 == 0) {
return Pow(base*base, power / 2);
} else if (power % 3 == 0) {
return Pow(base*base*base, power / 3);
} else {
return base * Pow(base, power - 1);
}
}
inline static const char* Atof(const char* p, double* out) {
int frac;
double sign, value, scale;
*out = NAN;
// Skip leading white space, if any.
while (*p == ' ') {
++p;
}
// Get sign, if any.
sign = 1.0;
if (*p == '-') {
sign = -1.0;
++p;
} else if (*p == '+') {
++p;
}
// is a number
if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') {
// Get digits before decimal point or exponent, if any.
for (value = 0.0; *p >= '0' && *p <= '9'; ++p) {
value = value * 10.0 + (*p - '0');
}
// Get digits after decimal point, if any.
if (*p == '.') {
double right = 0.0;
int nn = 0;
++p;
while (*p >= '0' && *p <= '9') {
right = (*p - '0') + right * 10.0;
++nn;
++p;
}
value += right / Pow(10.0, nn);
}
// Handle exponent, if any.
frac = 0;
scale = 1.0;
if ((*p == 'e') || (*p == 'E')) {
uint32_t expon;
// Get sign of exponent, if any.
++p;
if (*p == '-') {
frac = 1;
++p;
} else if (*p == '+') {
++p;
}
// Get digits of exponent, if any.
for (expon = 0; *p >= '0' && *p <= '9'; ++p) {
expon = expon * 10 + (*p - '0');
}
if (expon > 308) expon = 308;
// Calculate scaling factor.
while (expon >= 50) { scale *= 1E50; expon -= 50; }
while (expon >= 8) { scale *= 1E8; expon -= 8; }
while (expon > 0) { scale *= 10.0; expon -= 1; }
}
// Return signed and scaled floating point result.
*out = sign * (frac ? (value / scale) : (value * scale));
} else {
size_t cnt = 0;
while (*(p + cnt) != '\0' && *(p + cnt) != ' '
&& *(p + cnt) != '\t' && *(p + cnt) != ','
&& *(p + cnt) != '\n' && *(p + cnt) != '\r'
&& *(p + cnt) != ':') {
++cnt;
}
if (cnt > 0) {
std::string tmp_str(p, cnt);
std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower);
if (tmp_str == std::string("na") || tmp_str == std::string("nan") ||
tmp_str == std::string("null")) {
*out = NAN;
} else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) {
*out = sign * 1e308;
} else {
Log::Fatal("Unknown token %s in data file", tmp_str.c_str());
}
p += cnt;
}
}
while (*p == ' ') {
++p;
}
return p;
}
inline static bool AtoiAndCheck(const char* p, int* out) {
const char* after = Atoi(p, out);
if (*after != '\0') {
return false;
}
return true;
}
inline static bool AtofAndCheck(const char* p, double* out) {
const char* after = Atof(p, out);
if (*after != '\0') {
return false;
}
return true;
}
inline static unsigned CountDecimalDigit32(uint32_t n) {
#if defined(_MSC_VER) || defined(__GNUC__)
static const uint32_t powers_of_10[] = {
0,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000
};
#ifdef _MSC_VER
unsigned long i = 0;
_BitScanReverse(&i, n | 1);
uint32_t t = (i + 1) * 1233 >> 12;
#elif __GNUC__
uint32_t t = (32 - __builtin_clz(n | 1)) * 1233 >> 12;
#endif
return t - (n < powers_of_10[t]) + 1;
#else
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
return 10;
#endif
}
inline static void Uint32ToStr(uint32_t value, char* buffer) {
const char kDigitsLut[200] = {
'0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',
'1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',
'2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',
'3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',
'4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',
'5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',
'6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',
'7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',
'8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',
'9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'
};
unsigned digit = CountDecimalDigit32(value);
buffer += digit;
*buffer = '\0';
while (value >= 100) {
const unsigned i = (value % 100) << 1;
value /= 100;
*--buffer = kDigitsLut[i + 1];
*--buffer = kDigitsLut[i];
}
if (value < 10) {
*--buffer = char(value) + '0';
}
else {
const unsigned i = value << 1;
*--buffer = kDigitsLut[i + 1];
*--buffer = kDigitsLut[i];
}
}
inline static void Int32ToStr(int32_t value, char* buffer) {
uint32_t u = static_cast<uint32_t>(value);
if (value < 0) {
*buffer++ = '-';
u = ~u + 1;
}
Uint32ToStr(u, buffer);
}
inline static void DoubleToStr(double value, char* buffer, size_t
#ifdef _MSC_VER
buffer_len
#endif
) {
#ifdef _MSC_VER
sprintf_s(buffer, buffer_len, "%.17g", value);
#else
sprintf(buffer, "%.17g", value);
#endif
}
inline static const char* SkipSpaceAndTab(const char* p) {
while (*p == ' ' || *p == '\t') {
++p;
}
return p;
}
inline static const char* SkipReturn(const char* p) {
while (*p == '\n' || *p == '\r' || *p == ' ') {
++p;
}
return p;
}
template<typename T, typename T2>
inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) {
std::vector<T2> ret(arr.size());
for (size_t i = 0; i < arr.size(); ++i) {
ret[i] = static_cast<T2>(arr[i]);
}
return ret;
}
template<typename T, bool is_float, bool is_unsign>
struct __TToStringHelperFast {
void operator()(T value, char* buffer, size_t ) const {
Int32ToStr(value, buffer);
}
};
template<typename T>
struct __TToStringHelperFast<T, true, false> {
void operator()(T value, char* buffer, size_t
#ifdef _MSC_VER
buf_len
#endif
) const {
#ifdef _MSC_VER
sprintf_s(buffer, buf_len, "%g", value);
#else
sprintf(buffer, "%g", value);
#endif
}
};
template<typename T>
struct __TToStringHelperFast<T, false, true> {
void operator()(T value, char* buffer, size_t ) const {
Uint32ToStr(value, buffer);
}
};
template<typename T>
inline static std::string ArrayToStringFast(const std::vector<T>& arr, size_t n) {
if (arr.empty() || n == 0) {
return std::string("");
}
__TToStringHelperFast<T, std::is_floating_point<T>::value, std::is_unsigned<T>::value> helper;
const size_t buf_len = 16;
std::vector<char> buffer(buf_len);
std::stringstream str_buf;
helper(arr[0], buffer.data(), buf_len);
str_buf << buffer.data();
for (size_t i = 1; i < std::min(n, arr.size()); ++i) {
helper(arr[i], buffer.data(), buf_len);
str_buf << ' ' << buffer.data();
}
return str_buf.str();
}
inline static std::string ArrayToString(const std::vector<double>& arr, size_t n) {
if (arr.empty() || n == 0) {
return std::string("");
}
const size_t buf_len = 32;
std::vector<char> buffer(buf_len);
std::stringstream str_buf;
DoubleToStr(arr[0], buffer.data(), buf_len);
str_buf << buffer.data();
for (size_t i = 1; i < std::min(n, arr.size()); ++i) {
DoubleToStr(arr[i], buffer.data(), buf_len);
str_buf << ' ' << buffer.data();
}
return str_buf.str();
}
template<typename T, bool is_float>
struct __StringToTHelper {
T operator()(const std::string& str) const {
T ret = 0;
Atoi(str.c_str(), &ret);
return ret;
}
};
template<typename T>
struct __StringToTHelper<T, true> {
T operator()(const std::string& str) const {
return static_cast<T>(std::stod(str));
}
};
template<typename T>
inline static std::vector<T> StringToArray(const std::string& str, char delimiter) {
std::vector<std::string> strs = Split(str.c_str(), delimiter);
std::vector<T> ret;
ret.reserve(strs.size());
__StringToTHelper<T, std::is_floating_point<T>::value> helper;
for (const auto& s : strs) {
ret.push_back(helper(s));
}
return ret;
}
template<typename T>
inline static std::vector<T> StringToArray(const std::string& str, int n) {
if (n == 0) {
return std::vector<T>();
}
std::vector<std::string> strs = Split(str.c_str(), ' ');
CHECK(strs.size() == static_cast<size_t>(n));
std::vector<T> ret;
ret.reserve(strs.size());
__StringToTHelper<T, std::is_floating_point<T>::value> helper;
for (const auto& s : strs) {
ret.push_back(helper(s));
}
return ret;
}
template<typename T, bool is_float>
struct __StringToTHelperFast {
const char* operator()(const char*p, T* out) const {
return Atoi(p, out);
}
};
template<typename T>
struct __StringToTHelperFast<T, true> {
const char* operator()(const char*p, T* out) const {
double tmp = 0.0f;
auto ret = Atof(p, &tmp);
*out= static_cast<T>(tmp);
return ret;
}
};
template<typename T>
inline static std::vector<T> StringToArrayFast(const std::string& str, int n) {
if (n == 0) {
return std::vector<T>();
}
auto p_str = str.c_str();
__StringToTHelperFast<T, std::is_floating_point<T>::value> helper;
std::vector<T> ret(n);
for (int i = 0; i < n; ++i) {
p_str = helper(p_str, &ret[i]);
}
return ret;
}
template<typename T>
inline static std::string Join(const std::vector<T>& strs, const char* delimiter) {
if (strs.empty()) {
return std::string("");
}
std::stringstream str_buf;
str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
str_buf << strs[0];
for (size_t i = 1; i < strs.size(); ++i) {
str_buf << delimiter;
str_buf << strs[i];
}
return str_buf.str();
}
template<typename T>
inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) {
if (end - start <= 0) {
return std::string("");
}
start = std::min(start, static_cast<size_t>(strs.size()) - 1);
end = std::min(end, static_cast<size_t>(strs.size()));
std::stringstream str_buf;
str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2);
str_buf << strs[start];
for (size_t i = start + 1; i < end; ++i) {
str_buf << delimiter;
str_buf << strs[i];
}
return str_buf.str();
}
inline static int64_t Pow2RoundUp(int64_t x) {
int64_t t = 1;
for (int i = 0; i < 64; ++i) {
if (t >= x) {
return t;
}
t <<= 1;
}
return 0;
}
/*!
* \brief Do inplace softmax transformaton on p_rec
* \param p_rec The input/output vector of the values.
*/
inline static void Softmax(std::vector<double>* p_rec) {
std::vector<double> &rec = *p_rec;
double wmax = rec[0];
for (size_t i = 1; i < rec.size(); ++i) {
wmax = std::max(rec[i], wmax);
}
double wsum = 0.0f;
for (size_t i = 0; i < rec.size(); ++i) {
rec[i] = std::exp(rec[i] - wmax);
wsum += rec[i];
}
for (size_t i = 0; i < rec.size(); ++i) {
rec[i] /= static_cast<double>(wsum);
}
}
inline static void Softmax(const double* input, double* output, int len) {
double wmax = input[0];
for (int i = 1; i < len; ++i) {
wmax = std::max(input[i], wmax);
}
double wsum = 0.0f;
for (int i = 0; i < len; ++i) {
output[i] = std::exp(input[i] - wmax);
wsum += output[i];
}
for (int i = 0; i < len; ++i) {
output[i] /= static_cast<double>(wsum);
}
}
template<typename T>
std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) {
std::vector<const T*> ret;
for (size_t i = 0; i < input.size(); ++i) {
ret.push_back(input.at(i).get());
}
return ret;
}
template<typename T1, typename T2>
inline static void SortForPair(std::vector<T1>& keys, std::vector<T2>& values, size_t start, bool is_reverse = false) {
std::vector<std::pair<T1, T2>> arr;
for (size_t i = start; i < keys.size(); ++i) {
arr.emplace_back(keys[i], values[i]);
}
if (!is_reverse) {
std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) {
return a.first < b.first;
});
} else {
std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) {
return a.first > b.first;
});
}
for (size_t i = start; i < arr.size(); ++i) {
keys[i] = arr[i].first;
values[i] = arr[i].second;
}
}
template <typename T>
inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>& data) {
std::vector<T*> ptr(data.size());
for (size_t i = 0; i < data.size(); ++i) {
ptr[i] = data[i].data();
}
return ptr;
}
template <typename T>
inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) {
std::vector<int> ret(data.size());
for (size_t i = 0; i < data.size(); ++i) {
ret[i] = static_cast<int>(data[i].size());
}
return ret;
}
inline static double AvoidInf(double x) {
if (x >= 1e300) {
return 1e300;
} else if(x <= -1e300) {
return -1e300;
} else {
return x;
}
}
inline static float AvoidInf(float x) {
if (x >= 1e38) {
return 1e38f;
} else if (x <= -1e38) {
return -1e38f;
} else {
return x;
}
}
template<typename _Iter> inline
static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) {
return (0);
}
template<typename _RanIt, typename _Pr, typename _VTRanIt> inline
static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) {
size_t len = _Last - _First;
const size_t kMinInnerLen = 1024;
int num_threads = 1;
#pragma omp parallel
#pragma omp master
{
num_threads = omp_get_num_threads();
}
if (len <= kMinInnerLen || num_threads <= 1) {
std::sort(_First, _Last, _Pred);
return;
}
size_t inner_size = (len + num_threads - 1) / num_threads;
inner_size = std::max(inner_size, kMinInnerLen);
num_threads = static_cast<int>((len + inner_size - 1) / inner_size);
#pragma omp parallel for schedule(static,1)
for (int i = 0; i < num_threads; ++i) {
size_t left = inner_size*i;
size_t right = left + inner_size;
right = std::min(right, len);
if (right > left) {
std::sort(_First + left, _First + right, _Pred);
}
}
// Buffer for merge.
std::vector<_VTRanIt> temp_buf(len);
_RanIt buf = temp_buf.begin();
size_t s = inner_size;
// Recursive merge
while (s < len) {
int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2));
#pragma omp parallel for schedule(static,1)
for (int i = 0; i < loop_size; ++i) {
size_t left = i * 2 * s;
size_t mid = left + s;
size_t right = mid + s;
right = std::min(len, right);
if (mid >= right) { continue; }
std::copy(_First + left, _First + mid, buf + left);
std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred);
}
s *= 2;
}
}
template<typename _RanIt, typename _Pr> inline
static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) {
return ParallelSort(_First, _Last, _Pred, IteratorValType(_First));
}
// Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not
template <typename T>
inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) {
auto fatal_msg = [&y, &ymin, &ymax, &callername](int i) {
std::ostringstream os;
os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]";
Log::Fatal(os.str().c_str(), callername, i);
};
for (int i = 1; i < ny; i += 2) {
if (y[i - 1] < y[i]) {
if (y[i - 1] < ymin) {
fatal_msg(i - 1);
} else if (y[i] > ymax) {
fatal_msg(i);
}
} else {
if (y[i - 1] > ymax) {
fatal_msg(i - 1);
} else if (y[i] < ymin) {
fatal_msg(i);
}
}
}
if (ny & 1) { // odd
if (y[ny - 1] < ymin || y[ny - 1] > ymax) {
fatal_msg(ny - 1);
}
}
}
// One-pass scan over array w with nw elements: find min, max and sum of elements;
// this is useful for checking weight requirements.
template <typename T1, typename T2>
inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) {
T1 minw;
T1 maxw;
T1 sumw;
int i;
if (nw & 1) { // odd
minw = w[0];
maxw = w[0];
sumw = w[0];
i = 2;
} else { // even
if (w[0] < w[1]) {
minw = w[0];
maxw = w[1];
} else {
minw = w[1];
maxw = w[0];
}
sumw = w[0] + w[1];
i = 3;
}
for (; i < nw; i += 2) {
if (w[i - 1] < w[i]) {
minw = std::min(minw, w[i - 1]);
maxw = std::max(maxw, w[i]);
} else {
minw = std::min(minw, w[i]);
maxw = std::max(maxw, w[i - 1]);
}
sumw += w[i - 1] + w[i];
}
if (mi != nullptr) {
*mi = minw;
}
if (ma != nullptr) {
*ma = maxw;
}
if (su != nullptr) {
*su = static_cast<T2>(sumw);
}
}
template<typename T>
inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) {
std::vector<uint32_t> ret;
for (int i = 0; i < n; ++i) {
int i1 = vals[i] / 32;
int i2 = vals[i] % 32;
if (static_cast<int>(ret.size()) < i1 + 1) {
ret.resize(i1 + 1, 0);
}
ret[i1] |= (1 << i2);
}
return ret;
}
template<typename T>
inline static bool FindInBitset(const uint32_t* bits, int n, T pos) {
int i1 = pos / 32;
if (i1 >= n) {
return false;
}
int i2 = pos % 32;
return (bits[i1] >> i2) & 1;
}
inline static bool CheckDoubleEqualOrdered(double a, double b) {
double upper = std::nextafter(a, INFINITY);
return b <= upper;
}
inline static double GetDoubleUpperBound(double a) {
return std::nextafter(a, INFINITY);;
}
inline static size_t GetLine(const char* str) {
auto start = str;
while (*str != '\0' && *str != '\n' && *str != '\r') {
++str;
}
return str - start;
}
inline static const char* SkipNewLine(const char* str) {
if (*str == '\r') {
++str;
}
if (*str == '\n') {
++str;
}
return str;
}
template <typename T>
static int Sign(T x) {
return (x > T(0)) - (x < T(0));
}
} // namespace Common
} // namespace LightGBM
#endif // LightGBM_UTILS_COMMON_FUN_H_
|
polygonalsurface_texcoordparameterization_accel_ops.h | #ifdef _MSC_VER
#define PSTCPAOPS_INLINE __inline
#include <float.h>
#define PSTCPAOPS_ISNAN _isnan
#define PSTCPAOPS_ALLOCA _alloca
#else
#define PSTCPAOPS_INLINE inline
#define PSTCPAOPS_ISNAN isnan
#define PSTCPAOPS_ALLOCA alloca
#endif
static PSTCPAOPS_INLINE size_t enclosed_or_intersecting_polygons_2d_c(int32_t *polypool,
size_t polypoollen,
float64_t *texcoord,
uint32_t *vertexidx_indices,
uint32_t num_3d_polygons,
int32_t *texcoordidx,
uint32_t *numvertices,
uint32_t *texcoordredundant_numcopies,
uint32_t *texcoordredundant_polystartindexes,
uint32_t *texcoordredundant_polystartpolynum,
int32_t *texcoordredundant_texcoordidx,
float64_t minu,
float64_t minv,
float64_t maxu,
float64_t maxv,
int32_t *retpolys,
uint32_t *num_fully_enclosed) // Returns # of polygons actually returned in retpolys
{
// retpolys assumed to be at least as big as polypool
size_t num_returned_polys=0;
size_t poolidx;
int32_t idx;
size_t firstidx;
int32_t *vertexidxs;
size_t numvertexidxs;
int polygon_fully_enclosed;
uint32_t polynum;
float64_t box_v0[2];
float64_t box_v1[2];
(*num_fully_enclosed)=0;
box_v0[0]=minu;
box_v0[1]=minv;
box_v1[0]=maxu;
box_v1[1]=maxv;
for (poolidx=0;poolidx < polypoollen;poolidx++) {
idx=polypool[poolidx];
if (idx < 0) {
// masked out polygon
continue;
}
if (idx < num_3d_polygons) {
firstidx=vertexidx_indices[idx];
vertexidxs=&texcoordidx[firstidx];
numvertexidxs=numvertices[idx];
polygon_fully_enclosed = vertices_in_box_2d(texcoord,vertexidxs,numvertexidxs,box_v0,box_v1);
} else {
// redundant texcoords
firstidx=texcoordredundant_polystartindexes[idx-num_3d_polygons];
polynum=texcoordredundant_polystartpolynum[idx-num_3d_polygons];
vertexidxs = &texcoordredundant_texcoordidx[firstidx];
numvertexidxs=numvertices[polynum];
polygon_fully_enclosed = vertices_in_box_2d(texcoord,vertexidxs,numvertexidxs,box_v0,box_v1);
}
if (polygon_fully_enclosed) {
retpolys[num_returned_polys]=idx;
num_returned_polys++;
// if it's fully enclosed, nothing else need look at at, so we filter it here from the broader sibling pool
polypool[poolidx] = -1; // mask out polygon
(*num_fully_enclosed)++;
} else {
/* not polygon_fully_enclosed */
// does it intersect?
if (polygon_intersects_box_2d_c(box_v0,box_v1,texcoord,vertexidxs,numvertexidxs)) {
retpolys[num_returned_polys]=idx;
num_returned_polys++;
//Don't filter it out in this case because it must
// intersect with a sibiling too
}
else if (box_inside_polygon_2d_c(box_v0,box_v1,texcoord,vertexidxs,numvertexidxs)) {
// What if the box is entirely inside the polygon?
// Then we should return it also
retpolys[num_returned_polys]=idx;
num_returned_polys++;
}
}
}
return num_returned_polys;
}
static PSTCPAOPS_INLINE int test_polynum_uv_c(uint32_t *vertexidx_indices,
size_t num_3d_polys,
uint32_t *numvertices,
int32_t *texcoordidx,
uint32_t *texcoordredundant_polystartindexes,
uint32_t *texcoordredundant_polystartpolynum,
int32_t *texcoordredundant_texcoordidx,
float64_t *texcoord,
float64_t u,
float64_t v,
size_t polynum)
{
// Find whether our (u,v) coordinate is inside this polygon
// ... is our (u,v) point inside this polygon?
size_t firstidx;
size_t numpoints;
size_t polysurf_polynum;
int32_t *vertexidxs;
size_t cnt;
if (polynum < num_3d_polys) {
firstidx=vertexidx_indices[polynum];
numpoints=numvertices[polynum];
vertexidxs=&texcoordidx[firstidx]; // :(firstidx+numpoints)]
}
else {
firstidx=texcoordredundant_polystartindexes[polynum-num_3d_polys];
polysurf_polynum=texcoordredundant_polystartpolynum[polynum-num_3d_polys];
numpoints=numvertices[polysurf_polynum];
vertexidxs = &texcoordredundant_texcoordidx[firstidx]; //:(firstidx+polysurf.numvertices[polysurf_polynum])]
}
{
float64_t *vertices_rel_point;
vertices_rel_point=PSTCPAOPS_ALLOCA(sizeof(*vertices_rel_point)*2*numpoints);
for (cnt=0;cnt < numpoints;cnt++) {
vertices_rel_point[cnt*2+0] = texcoord[vertexidxs[cnt]*2+0]-u;
vertices_rel_point[cnt*2+1] = texcoord[vertexidxs[cnt]*2+1]-v;
}
return point_in_polygon_2d_c(vertices_rel_point,numpoints);
}
}
#define BOXES_COLUMNS 6
static PSTCPAOPS_INLINE int32_t identify_polynum_uv_c(uint32_t *vertexidx_indices,
size_t num_3d_polys,
uint32_t *numvertices,
int32_t *texcoordidx,
uint32_t *texcoordredundant_polystartindexes,
uint32_t *texcoordredundant_polystartpolynum,
int32_t *texcoordredundant_texcoordidx,
float64_t *texcoord,
int32_t *boxes,
int32_t *boxpolys,
float64_t *boxcoords,
float64_t u,
float64_t v,
int32_t candidate_polynum,
int32_t *boxpool_mem,
size_t boxpool_mem_nelem)
//int32_t *polypool_mem,
//size_t polypool_mem_size)
{
int point_in_poly;
// size_t num_candidate_polys; // # used in polypool_mem
size_t num_boxes_to_test; // # used in boxpool_mem
// int32_t *candidatepolys;
int32_t *boxes_to_test;
int32_t curbox;
int32_t *children;
int32_t polys_in_curbox_idx;
int32_t polys_in_curbox_num;
size_t cnt;
if (candidate_polynum >= 0) {
point_in_poly=test_polynum_uv_c(vertexidx_indices,
num_3d_polys,
numvertices,
texcoordidx,
texcoordredundant_polystartindexes,
texcoordredundant_polystartpolynum,
texcoordredundant_texcoordidx,
texcoord,
u,v,candidate_polynum);
if (point_in_poly) return candidate_polynum;
}
// Search boxes to find candidate polygons
//candidatepolys=polypool_mem;
//num_candidatepolys=0;
boxes_to_test=boxpool_mem;
boxes_to_test[0]=0; // Always test grandfather box
num_boxes_to_test=1;
while (num_boxes_to_test > 0) {
curbox=boxes_to_test[num_boxes_to_test-1];
num_boxes_to_test--;
//fprintf(stderr,"curbox=%d\n",(int)curbox);
if (u >= boxcoords[curbox*4+0] &&
v >= boxcoords[curbox*4+1] &&
u <= boxcoords[curbox*4+2] &&
v <= boxcoords[curbox*4+3]) {
// we are inside box
children=&boxes[curbox*BOXES_COLUMNS]; // children is length 4
if (children[0] >= 0) {
// got children... add to boxes_to_test
for (cnt=0;cnt < 4;cnt++) {
if (num_boxes_to_test >= boxpool_mem_nelem) {
// Storage overflow
assert(0);
return -1;
}
//fprintf(stderr,"add child =%d\n",(int)children[cnt]);
boxes_to_test[num_boxes_to_test]=children[cnt];
num_boxes_to_test++;
}
}
if (boxes[curbox*BOXES_COLUMNS+4] >= 0) {
polys_in_curbox_idx=boxes[curbox*BOXES_COLUMNS+4];
polys_in_curbox_num=boxes[curbox*BOXES_COLUMNS+5];
//// Add these polygons to candidatepolys
//for (cnt=0;cnt < polys_in_curbox_num;cnt++) {
// candidatepolys[num_candidatepolys]=boxpolys[polys_in_curbox_idx+cnt];
// num_candidatepolys++;
//}
// Test these polygons
// (if we went back to storing a list,
// we could potentially optimize by
// removing duplicates
for (cnt=0;cnt < polys_in_curbox_num;cnt++) {
point_in_poly=test_polynum_uv_c(vertexidx_indices,
num_3d_polys,
numvertices,
texcoordidx,
texcoordredundant_polystartindexes,
texcoordredundant_polystartpolynum,
texcoordredundant_texcoordidx,
texcoord,
u,v,boxpolys[polys_in_curbox_idx+cnt]);
if (point_in_poly) return boxpolys[polys_in_curbox_idx+cnt];
}
}
}
} // If we got this far, the search failed!
return -1;
}
static PSTCPAOPS_INLINE void evaluate_curvature_c(uint32_t *vertexidx_indices,
size_t num_3d_polys,
uint32_t *numvertices,
int32_t *vertexidx,
float64_t *vertices,
float64_t *refpoints,
uint32_t *texcoordredundant_polystartpolynum,
float64_t *inplanemats,
float64_t *inplane2texcoords,
float64_t *texcoord2inplane,
float64_t *principal_curvatures,
float64_t *curvature_tangent_axes,
size_t polynum,float64_t u, float64_t v,
float64_t *curvmatout)
{
// Evaluate the curvature, within polygon # polynum
// at (u,v) coordinates... (u,v) in texture coordinate
// range [0...1]
size_t polysurf_polynum,firstidx,numpoints;
float64_t *To2D,*AijMatInv,*centroid;
float64_t u_v_one[3],TexUVExt[3],Tex3D[3];
size_t cnt,rowcnt,colcnt,sumcnt,sumcnt2,vertexcnt,axiscnt,princcurvcnt;
int axis;
float64_t dist,distssquared,maxdistsquared,eps,sumval;
float64_t avgcurvmatrix[2*2];
float64_t asymmetry,totalweights,normval,sumsq,normfactor;
if (polynum >= num_3d_polys) {
// This polynum corresponds to a redundant texture
polysurf_polynum=texcoordredundant_polystartpolynum[polynum];
} else {
polysurf_polynum=polynum;
}
To2D=&inplanemats[polysurf_polynum*2*3]; // To2D is 2x3
AijMatInv=&texcoord2inplane[polynum*3*3]; //texcoord2inplane is 3x3
// Note Capital UV represent the texture parameterization
// of the in-plane 3D space of this facet.
//TexUVExt = np.inner(AijMatInv,np.array((u,v,1.0)))
u_v_one[0]=u;
u_v_one[1]=v;
u_v_one[2]=1.0;
multmatvec3(AijMatInv,u_v_one,TexUVExt);
//TexUVExt /= TexUVExt[2] # normalize inhomogeneous coordinates
TexUVExt[0] /= TexUVExt[2];
TexUVExt[1] /= TexUVExt[2];
// These coordinates of this (u,v) of this facet are relative to its centroid,
// and are in terms of the basis vectors in To2D
// TexUV = TexUVExt[:2]
// TexUV equivalent in C context to TexUVExt
// Get 3D coordinates relative to centroid
//Tex3D = np.inner(To2D.T,TexUV)
multvecmat23(TexUVExt,To2D,Tex3D);
// Need to evaluate 3D vertex coords, relative to centroid,
// Use them to weight the vertex curvatures
// according to distance from our point.
centroid = &refpoints[polysurf_polynum*3]; // Centroied in 3d coords
firstidx=vertexidx_indices[polysurf_polynum];
numpoints=numvertices[polysurf_polynum];
// Check to see if we have curvatures at all vertices:
for (cnt=0; cnt < numpoints; cnt++) {
if (PSTCPAOPS_ISNAN(principal_curvatures[vertexidx[firstidx+cnt]*2+0])) {
// Curvature not given... abort and return NaN
curvmatout[0]=curvmatout[1]=curvmatout[2]=curvmatout[3]=my_infnan(0);
return;
}
}
{
// For this facet, the 3D coords of the vertices relative to the centroid are coordvals
float64_t *coordvals=PSTCPAOPS_ALLOCA(sizeof(*coordvals)*numpoints*3);
float64_t *dists=PSTCPAOPS_ALLOCA(sizeof(*dists)*numpoints);
float64_t *rawweights=PSTCPAOPS_ALLOCA(sizeof(*rawweights)*numpoints);
float64_t *weights=PSTCPAOPS_ALLOCA(sizeof(*weights)*numpoints);
//float64_t *coordvals2d=PSTCPAOPS_ALLOCA(sizeof(*coordvals2d)*numpoints*2);
float64_t *CTA_2D=PSTCPAOPS_ALLOCA(sizeof(*CTA_2D)*2*numpoints*2);
float64_t *curvmatrices=PSTCPAOPS_ALLOCA(sizeof(*curvmatrices)*numpoints*2*2);
float64_t *weightedcurvmatrices=PSTCPAOPS_ALLOCA(sizeof(*weightedcurvmatrices)*numpoints*2*2);
for (cnt=0;cnt < numpoints;cnt++) {
for (axis=0;axis < 3; axis++) {
coordvals[cnt*3+axis]=vertices[vertexidx[firstidx+cnt]*3+axis]-centroid[axis];
}
}
// coordvals is the coordinates relative to centroid, numpoints x 3 (transpose of version in Python code
// Now coordvals is numvertices x 3, coordinates of the vertices
// relative to centroid
// Tex3D is 3 vector, coordinates of our (u,v) location
// relative to centroid.
// Perform weighted average
// dists = vecnorm(Tex3D.reshape(3,1) - coordvals,axis=0)
maxdistsquared=0.0;
for (cnt=0;cnt < numpoints;cnt++) {
distssquared=0;
for (axis=0;axis < 3; axis++) {
dist=coordvals[cnt*3+axis]-Tex3D[axis];
distssquared += pow(dist,2.0);
}
if (distssquared > maxdistsquared) {
maxdistsquared=distssquared;
}
dists[cnt]=sqrt(distssquared);
}
//eps = np.max(dists)/10000.0 # small number, so we don't divide by 0
eps = sqrt(maxdistsquared)/10000.0;
// rawweights=1.0/(dists+eps)
// totalweights=np.sum(rawweights)
totalweights=0.0;
for (cnt=0;cnt < numpoints;cnt++) {
rawweights[cnt]=1.0/(dists[cnt]+eps);
totalweights += rawweights[cnt];
}
// weights=rawweights/totalweights
for (cnt=0;cnt < numpoints;cnt++) {
weights[cnt]=rawweights[cnt]/totalweights;
}
// The 2D coords of the vertices are
//coordvals2d = np.dot(To2D,coordvals) # 2 rows by numpoints cols... in 2D basis relative to centroid (not used!) (remember our coordvals transposed compared to Python code)
// Likewise 2D coords of the curvature_tangent_axes
// CTA_2D = np.inner(To2D,polysurf.curvature_tangent_axes[polysurf.vertexidx[firstidx:(firstidx+numpoints)],:,:]).transpose(1,0,2) # Transpose to keep broadcast axis to the left. Pre-transpose axes lengths are: 2 (2D axes) by # of vertices by 2 (principal curvature)
// *** C implementation does not do transpose
// so axes are 2 (2d axes) by # of vertices by 2 (principal curvature)
for (axiscnt=0;axiscnt < 2;axiscnt++) {
for (vertexcnt=0; vertexcnt < numpoints; vertexcnt++) {
for(princcurvcnt=0;princcurvcnt < 2; princcurvcnt++) {
sumval=0.0;
for (sumcnt=0;sumcnt < 3;sumcnt++) {
sumval+=To2D[axiscnt*3+sumcnt]*curvature_tangent_axes[vertexidx[firstidx+vertexcnt]*2*3 + princcurvcnt*3 + sumcnt];
}
CTA_2D[axiscnt*2*numpoints + vertexcnt*2 + princcurvcnt]=sumval;
}
}
}
// Normalize curvature_tangent_axes (should be unit length)
//CTA_2D /= vecnormkeepshape(CTA_2D,0) # Axis is axis 0 because it came from To2D
for (vertexcnt=0; vertexcnt < numpoints; vertexcnt++) {
for(princcurvcnt=0;princcurvcnt < 2; princcurvcnt++) {
sumsq=0.0;
for (axiscnt=0;axiscnt < 2;axiscnt++) {
sumsq += pow(CTA_2D[axiscnt*numpoints*2 + vertexcnt*2 + princcurvcnt],2);
}
normfactor=1.0/sqrt(sumsq);
for (axiscnt=0;axiscnt < 2;axiscnt++) {
CTA_2D[axiscnt*numpoints*2 + vertexcnt*2 + princcurvcnt] *= normfactor;
}
}
}
// Construct curvature matrices ...
// Need to construct V*K*V', broadcasting over which vertex
// curvmatrices=np.einsum('...ij,...j,...jk->...ik', CTA_2D,polysurf.principal_curvatures[polysurf.vertexidx[firstidx:(firstidx+numpoints)],:],CTA_2D.transpose(0,2,1)) # result is # of vertices by 2x2 curvature matrix
for (vertexcnt=0;vertexcnt < numpoints;vertexcnt++) { // vertexcnt represented by ellipsis, above
for (axiscnt=0;axiscnt < 2; axiscnt++) { // axiscnt represented by i, above
for(princcurvcnt=0;princcurvcnt < 2; princcurvcnt++) { //princcurvcnt represented by k, above
sumval=0.0;
for (sumcnt=0;sumcnt < 2;sumcnt++) { // sumcnt represented by j, above
sumval+=CTA_2D[axiscnt*numpoints*2 + vertexcnt*2 + sumcnt]*principal_curvatures[vertexidx[firstidx+vertexcnt]*2+sumcnt]*CTA_2D[princcurvcnt*numpoints*2 + vertexcnt*2 + sumcnt];
}
curvmatrices[vertexcnt*2*2 + axiscnt*2 + princcurvcnt] = sumval;
}
}
}
// Weighting of vertices relative to our point (u,v)
// weightedcurvmatrices = weights.reshape(numpoints,1,1)*curvmatrices
for (vertexcnt=0;vertexcnt < numpoints;vertexcnt++) {
for (axiscnt=0;axiscnt < 2; axiscnt++) {
for(princcurvcnt=0;princcurvcnt < 2; princcurvcnt++) {
weightedcurvmatrices[vertexcnt*2*2 + axiscnt*2 + princcurvcnt] = curvmatrices[vertexcnt*2*2 + axiscnt*2 + princcurvcnt] * weights[vertexcnt];
}
}
}
// avgcurvmatrix (weighted average)
// avgcurvmatrix = weightedcurvmatrices.sum(axis=0)
avgcurvmatrix[0*2+0]=avgcurvmatrix[0*2+1]=avgcurvmatrix[1*2+0]=avgcurvmatrix[1*2+1]=0.0;
for (vertexcnt=0;vertexcnt < numpoints;vertexcnt++) {
for (axiscnt=0;axiscnt < 2; axiscnt++) {
for(princcurvcnt=0;princcurvcnt < 2; princcurvcnt++) {
avgcurvmatrix[axiscnt*2+princcurvcnt]+=weightedcurvmatrices[vertexcnt*2*2 + axiscnt*2 + princcurvcnt] ;
}
}
}
// avgcurvmatrix is a 2x2 which should be close to symmetric
asymmetry = avgcurvmatrix[1*2+0]-avgcurvmatrix[0*2+1];
// if abs(asymmetry) > 0.1*np.linalg.norm(avgcurvmatrix):
normval=0.0;
for (cnt=0; cnt < 4;cnt++) {
// Accumulate frobenius norm
normval+=pow(avgcurvmatrix[cnt],2);
}
normval=sqrt(normval);
if (fabs(asymmetry) > 0.1*normval) {
fprintf(stderr,"evaluate_curvature_c(): WARNING Large asymmetry in mean curvature matrix at (u,v) = (%lg,%lg). Matrix = [ %lg %lg ; %lg %lg ]\n",u,v,avgcurvmatrix[0],avgcurvmatrix[1],avgcurvmatrix[2],avgcurvmatrix[3]);
}
// correct asymmetry
avgcurvmatrix[1*2+0] -= asymmetry/2.0;
avgcurvmatrix[0*2+1] += asymmetry/2.0;
// avgcurvmatrix is in the polysurf.inplanemats (i.e. To2D)
// orthonormal basis, with units of meters
// We want to return 2D vectors in the AijMat i.e. self.inplane2texcoords) frame
// with units of texcoords.
//i.e. AijMat * avgcurv * inv(AijMat)
//
// NOTE: AijMat is in inhomogeneous coordinates
// ... avgcurvmatrix represents vectors, not coords
// so use only first two rows
//return np.dot(self.inplane2texcoords[polynum,:,:2],np.dot(avgcurvmatrix,self.texcoord2inplane[polynum,:2,:2]))
// i.e ret_il = AijBjkCkl
for (rowcnt=0;rowcnt < 2;rowcnt++) {
for (colcnt=0;colcnt < 2; colcnt++) {
sumval=0.0;
for (sumcnt=0;sumcnt < 2;sumcnt++) {
for (sumcnt2=0;sumcnt2 < 2;sumcnt2++) {
sumval += inplane2texcoords[polynum*2*3+rowcnt*3+sumcnt]*avgcurvmatrix[sumcnt*2+sumcnt2]*texcoord2inplane[polynum*3*3+sumcnt2*3+colcnt];
}
}
curvmatout[rowcnt*2+colcnt]=sumval;
}
}
}
}
static PSTCPAOPS_INLINE void linelength_sumcurvature_c_one(
// This operatex on (u,v) in texcoord [0-1] values
uint32_t *vertexidx_indices,
size_t num_3d_polys,
uint32_t *numvertices,
int32_t *vertexidx,
float64_t *vertices,
float64_t *refpoints,
int32_t *texcoordidx,
uint32_t *texcoordredundant_polystartindexes,
uint32_t *texcoordredundant_polystartpolynum,
int32_t *texcoordredundant_texcoordidx,
float64_t *texcoord,
int32_t *boxes,
int32_t *boxpolys,
float64_t *boxcoords,
float64_t *inplanemats,
float64_t *inplane2texcoords,
float64_t *texcoords2inplane,
float64_t *principal_curvatures,
float64_t *curvature_tangent_axes,
float64_t du, // nominal resolution in u
float64_t dv, // nominal resolution in v
float64_t u1,
float64_t v1,
float64_t u2,
float64_t v2,
int32_t *boxpool_mem,
size_t boxpool_mem_nelem,
float64_t *linelengthout,
float64_t *sumcurvatureout)
{
// Add up the physical length of all the line segments in the straight line
// (in u,v space) from u1,v1 to u2,v2. Assumes that the straight line is
// the shortest path, which isn't true in general. (shortest path
// would be the geodesic.)
float64_t udist_dus,vdist_dvs,uvdist;
size_t numsteps,stepnum;
float64_t linevec_uv[2],lineunitvec_uv[2],stepsize_uv[2];
float64_t segmidu,segmidv; //,stepmag_uv;
float64_t dXdstep,dYdstep,dRdstep;
float64_t dR,curvaccum;
int32_t polynum=-1;
float64_t curvmat[2*2];
float64_t curvtempvec[2];
udist_dus = (u2-u1)/du;
vdist_dvs = (v2-v1)/dv;
numsteps = (size_t)(1+sqrt(pow(udist_dus,2)+pow(vdist_dvs,2)));
linevec_uv[0]=(u2-u1);
linevec_uv[1]=(v2-v1);
// Distance in uv space
uvdist = normvec2(linevec_uv);
//stepmag_uv = uvdist/(numsteps);
//// unit vector in uv space
// (avoid this because can be NaN if dist is zero)
lineunitvec_uv[0]=linevec_uv[0]/uvdist;
lineunitvec_uv[1]=linevec_uv[1]/uvdist;
//// step size
//stepsize_uv[0]=stepmag_uv*lineunitvec_uv[0];
//stepsize_uv[1]=stepmag_uv*lineunitvec_uv[1];
stepsize_uv[0]=linevec_uv[0]/numsteps;
stepsize_uv[1]=linevec_uv[1]/numsteps;
// we split line into a bunch of segments and for each segment
// just find the midpoint of the segment
// and use that value as representative...
curvaccum=0.0;
dR=0.0;
for (stepnum=0,polynum=-1;
stepnum < numsteps;
stepnum++) {
//segstartu=u1 + stepsize_uv[0]*stepnum;
//segstartv=v1 + stepsize_uv[1]*stepnum;
//segendu=u1 + stepsize_uv[0]*(stepnum+1);
//segendv=v1 + stepsize_uv[1]*(stepnum+1);
segmidu = u1 + stepsize_uv[0]*(stepnum+0.5); /* segment midpoint in u */
segmidv = v1 + stepsize_uv[1]*(stepnum+0.5); /* segment midpoint in v */
polynum=identify_polynum_uv_c(vertexidx_indices,
num_3d_polys,
numvertices,
texcoordidx,
texcoordredundant_polystartindexes,
texcoordredundant_polystartpolynum,
texcoordredundant_texcoordidx,
texcoord,
boxes,
boxpolys,
boxcoords,
segmidu,
segmidv,
polynum,
boxpool_mem,
boxpool_mem_nelem);
if (polynum < 0) {
*linelengthout = my_infnan(0);
*sumcurvatureout = my_infnan(0);
return;
}
// dRdstep=np.linalg.norm(np.dot(self.texcoords2inplane[polynum,:2,:2],stepsize_uv)
dXdstep = (texcoords2inplane[polynum*3*3 + 0*3 + 0]*stepsize_uv[0] +
texcoords2inplane[polynum*3*3 + 0*3 + 1]*stepsize_uv[1]);
dYdstep = (texcoords2inplane[polynum*3*3 + 1*3 + 0]*stepsize_uv[0] +
texcoords2inplane[polynum*3*3 + 1*3 + 1]*stepsize_uv[1]);
dRdstep = sqrt(pow(dXdstep,2)+pow(dYdstep,2));
evaluate_curvature_c(vertexidx_indices,
num_3d_polys,
numvertices,
vertexidx,
vertices,
refpoints,
texcoordredundant_polystartpolynum,
inplanemats,
inplane2texcoords,
texcoords2inplane,
principal_curvatures,
curvature_tangent_axes,
polynum,
segmidu,
segmidv,
curvmat);
// curvmat is a 2x2 in (u,v)...
// (u,v) are not necessarily orthogonal in real space
// Really, curvmat is a shape operator.
// To get a curvature along a line,
// multiply on the left and right by a tangent vector that maps
// to 1 meter physical length. The result will be
// the curvature along that tangent vector (in 1/m).
// ... But since it's the same vector on the
// left and right, the scalings will be reciprocals,
// so we can just multiply on the left and right by unit vectors
// This then gives us the curvature along the line segment
// in m^-1
// So we accumulate a weighted average of the curvatures
// of the line segments.
if (!PSTCPAOPS_ISNAN(lineunitvec_uv[0]) && !PSTCPAOPS_ISNAN(lineunitvec_uv[1])) {
// (If either of these are NaN then our step length is zero so
// we really don'nt need to accumulate)
multmatvec2(curvmat,lineunitvec_uv,curvtempvec);
// dot product is evaluated curvature. dRdstep is weighting factor
curvaccum += dotvecvec2(lineunitvec_uv,curvtempvec) * dRdstep;
}
// Curvature is positive when surface is concave,
// negative when convex... by outward directed
// selected in curvature calculation code by normal.
dR += dRdstep;
}
*linelengthout=dR;
*sumcurvatureout=curvaccum; // divide out sum of weights
}
static PSTCPAOPS_INLINE void linelength_avgcurvature_c_array(
uint32_t *vertexidx_indices,
size_t num_3d_polys,
uint32_t *numvertices,
int32_t *vertexidx,
float64_t *vertices,
float64_t *refpoints,
int32_t *texcoordidx,
uint32_t *texcoordredundant_polystartindexes,
uint32_t *texcoordredundant_polystartpolynum,
int32_t *texcoordredundant_texcoordidx,
float64_t *texcoord,
int32_t *boxes,
size_t nboxes,
int32_t *boxpolys,
float64_t *boxcoords,
float64_t *inplanemats,
float64_t *inplane2texcoords,
float64_t *texcoords2inplane,
float64_t *principal_curvatures,
float64_t *curvature_tangent_axes,
float64_t du,float64_t dv,
float64_t *u1,
float64_t *v1,
float64_t *u2,
float64_t *v2,
size_t numlines,
float64_t *linelengthout,
float64_t *avgcurvatureout)
{
size_t linecnt;
int32_t *boxpool_mem;
float64_t sumcurvature;
boxpool_mem=malloc(sizeof(*boxpool_mem)*nboxes);
// this loop can be freely parallelized, but each thread
// will need its own boxpool_mem
for (linecnt=0;linecnt < numlines;linecnt++) {
linelength_sumcurvature_c_one(
vertexidx_indices,
num_3d_polys,
numvertices,
vertexidx,
vertices,
refpoints,
texcoordidx,
texcoordredundant_polystartindexes,
texcoordredundant_polystartpolynum,
texcoordredundant_texcoordidx,
texcoord,
boxes,
boxpolys,
boxcoords,
inplanemats,
inplane2texcoords,
texcoords2inplane,
principal_curvatures,
curvature_tangent_axes,
du,dv,
u1[linecnt],
v1[linecnt],
u2[linecnt],
v2[linecnt],
boxpool_mem,
nboxes,
&linelengthout[linecnt],
&sumcurvature);
avgcurvatureout[linecnt]=sumcurvature/linelengthout[linecnt];
/***!!! FIXME ... Should handle linelengthout==0 case
like mesh based implementation, gracefully degrading
to local curvature ****/
}
free(boxpool_mem);
}
static PSTCPAOPS_INLINE void linelength_sumcurvature_meshbased_c_one(
// This operatex on (u,v) in texcoord [0-1] values
float32_t *curvmats, // indexed c-style (v,u,2,2) ... must cover entire range of [0,1] texture coordinates
float32_t *stepsizearray, // step sizes interpreted as distance per pixel in stepsizearray
size_t nv, // number of v steps in curvmats or stepsizearray
size_t nu, // number of u steps in curvmats or stepsizearray
float64_t param_lowerleft_meaningfulunits_u,
float64_t param_lowerleft_meaningfulunits_v,
float64_t param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
float64_t param_stepsize_v,
float64_t du, // nominal desired resolution in u, meaning desired step size
float64_t dv, // nominal desired resolution in v, desired step size, in texcoord [0-1] units
float64_t u1,
float64_t v1,
float64_t u2,
float64_t v2,
float64_t *linelengthout,
float64_t *sumcurvatureout,
float64_t *sumcrosscurvatureout)
{
// Add up the physical length of all the line segments in the straight line
// (in u,v space) from u1,v1 to u2,v2. Assumes that the straight line is
// the shortest path, which isn't true in general. (shortest path
// would be the geodesic.)
float64_t udist_dus,vdist_dvs,uvdist;
size_t numsteps,stepnum;
float64_t linevec_uv[2],lineunitvec_uv[2],stepsize_uv[2];
float64_t segmidu,segmidv;// ,stepmag_uv;
float64_t dRdstep;
float64_t dR,curvaccum,crosscurvaccum;
uint32_t uidx,vidx;
float64_t curvtempvec[2];
float64_t curvmat[4];
float64_t crossunitvec[2];
udist_dus = (u2-u1)/du;
vdist_dvs = (v2-v1)/dv;
numsteps = (size_t)(1+sqrt(pow(udist_dus,2)+pow(vdist_dvs,2)));
linevec_uv[0]=(u2-u1);
linevec_uv[1]=(v2-v1);
// Distance in uv space
uvdist = normvec2(linevec_uv);
//stepmag_uv = uvdist/(numsteps);
if (uvdist==0.0) {
*linelengthout=0.0;
*sumcurvatureout=0.0; // end-user needs to divide out sum of weights
*sumcrosscurvatureout=0.0;
return;
}
//// unit vector in uv space
// (avoid using this because can be NaN if dist is zero)
lineunitvec_uv[0]=linevec_uv[0]/uvdist;
lineunitvec_uv[1]=linevec_uv[1]/uvdist;
// step size
//stepsize_uv[0]=stepmag_uv*lineunitvec_uv[0];
//stepsize_uv[1]=stepmag_uv*lineunitvec_uv[1];
stepsize_uv[0]=linevec_uv[0]/numsteps;
stepsize_uv[1]=linevec_uv[1]/numsteps;
// we split line into a bunch of segments and for each segment
// just find the midpoint of the segment
// and use that value as representative...
curvaccum=0.0;
crosscurvaccum=0.0; // curvature cross-ways (perpendicular) to the path
dR=0.0;
for (stepnum=0;
stepnum < numsteps;
stepnum++) {
//segstartu=u1 + stepsize_uv[0]*stepnum;
//segstartv=v1 + stepsize_uv[1]*stepnum;
//segendu=u1 + stepsize_uv[0]*(stepnum+1);
//segendv=v1 + stepsize_uv[1]*(stepnum+1);
segmidu = u1 + stepsize_uv[0]*(stepnum+0.5); /* segment midpoint in u */
segmidv = v1 + stepsize_uv[1]*(stepnum+0.5); /* segment midpoint in v */
//curvmatpoints are centered at (param_lowerleft_meaningfulunits_u + param_stepsize_u/2 + uidx*param_stepsize_u, ... same in v
// solve segmidu = lowerleft + stepsize/2 +uidx*stepsize
// uidx = (segmidu-lowerleft)/stepsize -0.5
// uidx = round((segmidu-lowerleft)/stepsize -0.5)
// uidx = floor((segmidu-lowerleft)/stepsize - 0.5 + 0.5)
uidx = (uint32_t)((segmidu-param_lowerleft_meaningfulunits_u)/param_stepsize_u);
vidx = (uint32_t)((segmidv-param_lowerleft_meaningfulunits_v)/param_stepsize_v);
if (uidx < 0 || uidx >= nu || vidx < 0 || vidx >= nv || segmidu < param_lowerleft_meaningfulunits_u || segmidv < param_lowerleft_meaningfulunits_v) {
/* off the world. Assume no curvature, but measure reasonable dR */
dRdstep = sqrt(stepsize_uv[0]*stepsize_uv[0] + stepsize_uv[1]*stepsize_uv[1]);
//*sumcurvatureout=0.0;
// *sumcrosscurvatureout=0.0;
//// NaN
//*linelengthout = my_infnan(0);
//*sumcurvatureout = my_infnan(0);
//*sumcrosscurvatureout = my_infnan(0);
//return;
} else {
dRdstep = sqrt(pow(stepsizearray[ vidx*nu*2 + uidx*2 + 0]*stepsize_uv[0]/param_stepsize_u,2.0) + pow(stepsizearray[ vidx*nu*2 + uidx*2 + 1]*stepsize_uv[1]/param_stepsize_v,2.0));
// &curvmats[vidx*nu*2*2 + uidx*2*2] is a 2x2 curvature matrix in (u,v)...
// (u,v) are not necessarily orthogonal in real space
curvmat[0]=curvmats[vidx*nu*2*2+uidx*2*2+0];
curvmat[1]=curvmats[vidx*nu*2*2+uidx*2*2+1];
curvmat[2]=curvmats[vidx*nu*2*2+uidx*2*2+2];
curvmat[3]=curvmats[vidx*nu*2*2+uidx*2*2+3];
// Really, curvmat is a shape operator.
// To get a curvature along a line,
// multiply on the left and right by a tangent vector that maps
// to 1 meter physical length. The result will be
// the curvature along that tangent vector (in 1/m).
// ... But since it's the same vector on the
// left and right, the scalings will be reciprocals,
// so we can just multiply on the left and right by unit vectors
// This then gives us the curvature along the line segment
// in m^-1
// So we accumulate a weighted average of the curvatures
// of the line segments.
if (!PSTCPAOPS_ISNAN(lineunitvec_uv[0]) && !PSTCPAOPS_ISNAN(lineunitvec_uv[1])) {
// (If either of these are NaN then our step length is zero so
// we really don'nt need to accumulate)
multmatvec2(curvmat,lineunitvec_uv,curvtempvec);
// dot product is evaluated curvature. dRdstep is weighting factor
curvaccum += dotvecvec2(lineunitvec_uv,curvtempvec) * dRdstep;
// cross-curvature:
// perpendicular vector in 2D can be found by interchanging
// the elements and negating one fothem
crossunitvec[0]=lineunitvec_uv[1];
crossunitvec[1]=-lineunitvec_uv[0]
;
multmatvec2(curvmat,crossunitvec,curvtempvec);
crosscurvaccum += dotvecvec2(crossunitvec,curvtempvec) * dRdstep;
}
// Curvature is positive when surface is concave,
// negative when convex... by outward directed
// selected in curvature calculation code by normal.
}
dR += dRdstep;
}
*linelengthout=dR;
*sumcurvatureout=curvaccum; // end-user needs to divide out sum of weights
*sumcrosscurvatureout=crosscurvaccum;
}
// Linelength for a mirrored box in (u,v) space. Line is
// presumed to start from (u1,v1) inside the box, and
// connects (u2,v2) which
// may be outside the box.
// Locations outside the box are interpreted as mirrored
// replicas of what is in the box
static PSTCPAOPS_INLINE void linelength_avgcurvature_mirroredbox_meshbased_c_one(
// This operatex on (u,v) in texcoord [0-1] values
float32_t *curvmats, // indexed c-style (v,u,2,2) ... must cover entire range of [0,1] texture coordinates
float32_t *stepsizearray,
size_t nv, // number of v steps in curvmats or stepsizearray
size_t nu, // number of u steps in curvmats or stepsizearray
float64_t param_lowerleft_meaningfulunits_u,
float64_t param_lowerleft_meaningfulunits_v,
float64_t param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
float64_t param_stepsize_v,
float64_t boxu1,
float64_t boxv1,
float64_t boxu2,
float64_t boxv2,
float64_t du, // nominal resolution in u, meaning desired step size
float64_t dv, // nominal resolution in v, desired step size, in texcoord [0-1] units
float64_t u1,
float64_t v1,
float64_t u2,
float64_t v2,
float64_t *linelengthout,
float64_t *avgcurvatureout,
float64_t *avgcrosscurvatureout,
float64_t *thetaout) // theta=0 means the line is parallel to u at point #2, theta = pi/2 means parallel to v at point #2
{
// Add up the physical length of all the line segments in the straight line
// (in u,v space) from u1,v1 to u2,v2. Assumes that the straight line is
// the shortest path, which isn't true in general. (shortest path
// would be the geodesic.)
float64_t segstart_u,segstart_v;
float64_t segstart_mirrored_u,segstart_mirrored_v;
float64_t segmid_u,segmid_v;
float64_t segend_u,segend_v;
float64_t segend_mirrored_u,segend_mirrored_v;
float64_t segment_linelength;
float64_t segment_sumcurvature;
float64_t segment_sumcrosscurvature;
float64_t total_linelength;
float64_t sumcurvature;
float64_t sumcrosscurvature;
float64_t t_bu1,t_bu2,t_bv1,t_bv2;
uint32_t uidx,vidx;
// Find intersections between the line from (u1,v1) to (u2,v2)
// and each of the box boundaries
// parameterize line segment from (u1,v1) to (u2,v2)
// as u = u1 + t*(u2-u1)
// and v = v1 + t*(v2-v1) ... segment goes from t=0..1
// intersections are at u= boxu1, u=boxu2, v=boxv1 and v=boxv2
//
// e.g boxu1 = u1 + t*(u2-u1)
// solve for t
// boxu1-u1 = t*(u2-u1)
// t_bu1 = (boxu1-u1)/(u2-u1) intersectnum==0
// t_bu2 = (boxu2-u1)/(u2-u1) intersectnum==1
// t_bv1 = (boxv1-u1)/(v2-v1) intersect
// t_bv2 = (boxv2-v1)/(v2-v1)
// up to 4 intersections so 6 times, including 0 and 1
float64_t times[6];
float64_t temp;
int interchangeflag=1;
int numtimes=1;
int cnt,segnum;
float32_t curv_evals[2];
times[0]=0.0;
// (u1,v1) is supposed to be inside the box (don't think we actually rely on this
assert(u1 >= boxu1 && u1 <= boxu2 && v1 >= boxv1 && v1 <= boxv2);
// ... but won't work if an end is farther than one width from the box edge
if (u2 != u1) {
t_bu1 = (boxu1-u1)/(u2-u1);
if (t_bu1 >= 0.0 && t_bu1 <= 1.0) {
times[numtimes]=t_bu1;
numtimes++;
}
t_bu2 = (boxu2-u1)/(u2-u1);
if (t_bu2 >= 0.0 && t_bu2 <= 1.0) {
times[numtimes]=t_bu2;
numtimes++;
}
}
if (v2 != v1) {
t_bv1 = (boxv1-v1)/(v2-v1);
if (t_bv1 >= 0.0 && t_bv1 <= 1.0) {
times[numtimes]=t_bv1;
numtimes++;
}
t_bv2 = (boxv2-v1)/(v2-v1);
if (t_bv2 >= 0.0 && t_bv2 <= 1.0) {
times[numtimes]=t_bv2;
numtimes++;
}
}
times[numtimes]=1.0; /* omit final increment */
/* sort times... bubble sort */
do {
interchangeflag=0;
for (cnt=1; cnt < numtimes-1; cnt++) {
if (times[cnt+1] < times[cnt]) {
/* out of order... interchange */
temp=times[cnt+1];
times[cnt+1]=times[cnt];
times[cnt]=temp;
interchangeflag=1;
}
}
} while (interchangeflag);
/* Ok... now we have the segments */
total_linelength=0.0;
sumcurvature=0.0;
sumcrosscurvature=0.0;
for (segnum=0,segstart_u = u1,segstart_v = v1;
segnum < numtimes;
segnum++,segstart_u=segend_u,segstart_v=segend_v) {
segend_u = u1 + (u2-u1)*times[segnum+1];
segend_v = v1 + (v2-v1)*times[segnum+1];
segmid_u = (segstart_u + segend_u)/2.0;
segmid_v = (segstart_v + segend_v)/2.0;
segstart_mirrored_u=segstart_u;
segstart_mirrored_v=segstart_v;
segend_mirrored_u=segend_u;
segend_mirrored_v=segend_v;
// segment midpoint tells us where we are...
if (segmid_u > boxu2) {
// mirrored around boxu2
segstart_mirrored_u = boxu2 - (segstart_mirrored_u-boxu2);
segend_mirrored_u = boxu2 - (segend_mirrored_u-boxu2);
}
if (segmid_u < boxu1) {
// mirrored around boxu1
segstart_mirrored_u = boxu1 + (boxu1-segstart_mirrored_u);
segend_mirrored_u = boxu1 + (boxu1-segend_mirrored_u);
}
if (segmid_v > boxv2) {
// mirrored around boxv2
segstart_mirrored_v = boxv2 - (segstart_mirrored_v-boxv2);
segend_mirrored_v = boxv2 - (segend_mirrored_v-boxv2);
}
if (segmid_v < boxv1) {
// mirrored around boxv1
segstart_mirrored_v = boxv1 + (boxv1-segstart_mirrored_v);
segend_mirrored_v = boxv1 + (boxv1-segend_mirrored_v);
}
/* calculate distance based on mirrored copy */
linelength_sumcurvature_meshbased_c_one(curvmats,
stepsizearray,
nv, nu,
param_lowerleft_meaningfulunits_u,
param_lowerleft_meaningfulunits_v,
param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
param_stepsize_v,
du, dv,
segstart_mirrored_u,
segstart_mirrored_v,
segend_mirrored_u,
segend_mirrored_v,
&segment_linelength,
&segment_sumcurvature,
&segment_sumcrosscurvature);
total_linelength += segment_linelength;
sumcurvature += segment_sumcurvature;
sumcrosscurvature += segment_sumcrosscurvature;
}
// simple approximation for theta assuming coordinate axes are all straight
*thetaout=atan2(v2-v1,u2-u1);
*linelengthout=total_linelength;
*avgcurvatureout=sumcurvature/total_linelength; // divide out sum of weights
*avgcrosscurvatureout=sumcrosscurvature/total_linelength; // divide out sum of weights
if ((PSTCPAOPS_ISNAN(*avgcurvatureout) && !PSTCPAOPS_ISNAN(sumcurvature) && !PSTCPAOPS_ISNAN(total_linelength)) ||
(PSTCPAOPS_ISNAN(*avgcrosscurvatureout) && !PSTCPAOPS_ISNAN(sumcrosscurvature) && !PSTCPAOPS_ISNAN(total_linelength))) {
// This would be the case if total linelength is about zero.
// i.e. we have a point, not a line
// ... But what direction?
// Evaluate the principal curvatures at this point.
// assign (arbitrarily) one as avgcurvature and the other as avgcrosscurvature
//curvmatpoints are centered at (param_lowerleft_meaningfulunits_u + param_stepsize_u/2 + uidx*param_stepsize_u, ... same in v
// solve segmidu = lowerleft + stepsize/2 +uidx*stepsize
// uidx = (segmidu-lowerleft)/stepsize -0.5
// uidx = round((segmidu-lowerleft)/stepsize -0.5)
// uidx = floor((segmidu-lowerleft)/stepsize - 0.5 + 0.5)
uidx = (uint32_t)((u1-param_lowerleft_meaningfulunits_u)/param_stepsize_u);
vidx = (uint32_t)((v1-param_lowerleft_meaningfulunits_v)/param_stepsize_v);
if (uidx < 0 || uidx >= nu || vidx < 0 || vidx >= nv || u1 < param_lowerleft_meaningfulunits_u || v1 < param_lowerleft_meaningfulunits_v) {
// NaN
*avgcurvatureout = my_infnan(0);
*avgcrosscurvatureout = my_infnan(0);
} else {
eigvals_2d_float(&curvmats[vidx*nu*2*2 + uidx*2*2],curv_evals);
*avgcurvatureout= curv_evals[0];
*avgcrosscurvatureout = curv_evals[1];
}
}
}
static PSTCPAOPS_INLINE void linelength_avgcurvature_meshbased_c_array(
// This operatex on (u,v) in texcoord [0-1] values
float32_t *curvmats, // indexed c-style (v,u,2,2) ... must cover entire range of [0,1] texture coordinates
float32_t *stepsizearray,
size_t nv, // number of v steps in curvmats or stepsizearray
size_t nu, // number of u steps in curvmats or stepsizearray
float64_t param_lowerleft_meaningfulunits_u,
float64_t param_lowerleft_meaningfulunits_v,
float64_t param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
float64_t param_stepsize_v,
float64_t du, // nominal resolution in u, meaning desired step size
float64_t dv, // nominal resolution in v, desired step size, in texcoord [0-1] units
float64_t *u1,
float64_t *v1,
float64_t *u2,
float64_t *v2,
size_t numlines,
float64_t *linelengthout,
float64_t *avgcurvatureout,
float64_t *avgcrosscurvatureout)
{
int64_t linecnt; // must be signed (e.g. not size_t) for MSVC compatibility
float64_t sumcurvature,sumcrosscurvature;
// this loop can be freely parallelized
#pragma omp parallel default(shared) private(linecnt)
#pragma omp for
for (linecnt=0;linecnt < numlines;linecnt++) {
float32_t curv_evals[2];
uint32_t uidx,vidx;
linelength_sumcurvature_meshbased_c_one(
curvmats,
stepsizearray,
nv,nu,
param_lowerleft_meaningfulunits_u,
param_lowerleft_meaningfulunits_v,
param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
param_stepsize_v,
du,dv,
u1[linecnt],
v1[linecnt],
u2[linecnt],
v2[linecnt],
&linelengthout[linecnt],
&sumcurvature,
&sumcrosscurvature);
avgcurvatureout[linecnt]=sumcurvature/linelengthout[linecnt];
avgcrosscurvatureout[linecnt]=sumcrosscurvature/linelengthout[linecnt];
if ((PSTCPAOPS_ISNAN(avgcurvatureout[linecnt]) && !PSTCPAOPS_ISNAN(sumcurvature) && !PSTCPAOPS_ISNAN(linelengthout[linecnt])) ||
(PSTCPAOPS_ISNAN(avgcrosscurvatureout[linecnt]) && !PSTCPAOPS_ISNAN(sumcrosscurvature) && !PSTCPAOPS_ISNAN(linelengthout[linecnt]))) {
// This would be the case if total linelength is about zero.
// i.e. we have a point, not a line
// ... But what direction?
// Evaluate the maximum principal curvature at this point.
// ***!!!! When we start implmenting tangential curvatures
// we should supply one curvature as max principal
// and the other as min principal ********
//curvmatpoints are centered at (param_lowerleft_meaningfulunits_u + param_stepsize_u/2 + uidx*param_stepsize_u, ... same in v
// solve segmidu = lowerleft + stepsize/2 +uidx*stepsize
// uidx = (segmidu-lowerleft)/stepsize -0.5
// uidx = round((segmidu-lowerleft)/stepsize -0.5)
// uidx = floor((segmidu-lowerleft)/stepsize - 0.5 + 0.5)
uidx = (uint32_t)((u1[linecnt]-param_lowerleft_meaningfulunits_u)/param_stepsize_u);
vidx = (uint32_t)((v1[linecnt]-param_lowerleft_meaningfulunits_v)/param_stepsize_v);
if (uidx < 0 || uidx >= nu || vidx < 0 || vidx >= nv || u1[linecnt] < param_lowerleft_meaningfulunits_u || v1[linecnt] < param_lowerleft_meaningfulunits_v) {
// NaN
avgcurvatureout[linecnt] = my_infnan(0);
avgcrosscurvatureout[linecnt] = my_infnan(0);
} else {
eigvals_2d_float(&curvmats[vidx*nu*2*2 + uidx*2*2],curv_evals);
avgcurvatureout[linecnt] = curv_evals[0];
avgcrosscurvatureout[linecnt] = curv_evals[1];
}
}
}
}
static PSTCPAOPS_INLINE void linelength_avgcurvature_mirroredbox_meshbased_c_array(
// This operatex on (u,v) in texcoord [0-1] values
float32_t *curvmats, // indexed c-style (v,u,2,2) ... must cover entire range of [0,1] texture coordinates
float32_t *stepsizearray,
size_t nv, // number of v steps in curvmats or stepsizearray
size_t nu, // number of u steps in curvmats or stepsizearray
float64_t param_lowerleft_meaningfulunits_u,
float64_t param_lowerleft_meaningfulunits_v,
float64_t param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
float64_t param_stepsize_v,
float64_t boxu1,
float64_t boxv1,
float64_t boxu2,
float64_t boxv2,
float64_t du, // nominal resolution in u, meaning desired step size
float64_t dv, // nominal resolution in v, desired step size, in texcoord [0-1] units
float64_t *u1,
float64_t *v1,
float64_t *u2,
float64_t *v2,
size_t numlines,
float64_t *linelengthout,
float64_t *avgcurvatureout,
float64_t *avgcrosscurvatureout,
float64_t *thetaout)
{
int64_t linecnt; // must be signed (e.g. not size_t) for MSVC compatibility
// this loop can be freely parallelized
#pragma omp parallel default(shared) private(linecnt)
#pragma omp for
for (linecnt=0;linecnt < numlines;linecnt++) {
linelength_avgcurvature_mirroredbox_meshbased_c_one(
curvmats,
stepsizearray,
nv,nu,
param_lowerleft_meaningfulunits_u,
param_lowerleft_meaningfulunits_v,
param_stepsize_u, /* meaningful unit stepsize for curvmats/stepsizearray (nominal value), used to measure u1,v1,etc. */
param_stepsize_v,
boxu1,
boxv1,
boxu2,
boxv2,
du,dv,
u1[linecnt],
v1[linecnt],
u2[linecnt],
v2[linecnt],
&linelengthout[linecnt],
&avgcurvatureout[linecnt],
&avgcrosscurvatureout[linecnt],
&thetaout[linecnt]);
}
}
|
GB_binop__isgt_fp64.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__isgt_fp64
// A.*B function (eWiseMult): GB_AemultB__isgt_fp64
// A*D function (colscale): GB_AxD__isgt_fp64
// D*A function (rowscale): GB_DxB__isgt_fp64
// C+=B function (dense accum): GB_Cdense_accumB__isgt_fp64
// C+=b function (dense accum): GB_Cdense_accumb__isgt_fp64
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isgt_fp64
// C=scalar+B GB_bind1st__isgt_fp64
// C=scalar+B' GB_bind1st_tran__isgt_fp64
// C=A+scalar GB_bind2nd__isgt_fp64
// C=A'+scalar GB_bind2nd_tran__isgt_fp64
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = (aij > bij)
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// 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) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double 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) ;
// 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_ISGT || GxB_NO_FP64 || GxB_NO_ISGT_FP64)
//------------------------------------------------------------------------------
// 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__isgt_fp64
(
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__isgt_fp64
(
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__isgt_fp64
(
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 double
double bwork = (*((double *) 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__isgt_fp64
(
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
double *GB_RESTRICT Cx = (double *) 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__isgt_fp64
(
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
double *GB_RESTRICT Cx = (double *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#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__isgt_fp64
(
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__isgt_fp64
(
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__isgt_fp64
(
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
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) 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 ;
double 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__isgt_fp64
(
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 ;
double *Cx = (double *) Cx_output ;
double *Ax = (double *) Ax_input ;
double y = (*((double *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
double 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) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (x > aij) ; \
}
GrB_Info GB_bind1st_tran__isgt_fp64
(
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 \
double
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double x = (*((const double *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
double
}
//------------------------------------------------------------------------------
// 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) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = (aij > y) ; \
}
GrB_Info GB_bind2nd_tran__isgt_fp64
(
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
double y = (*((const double *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
convolution_3x3_pack1to4_bf16s.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 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 conv3x3s1_pack1to4_bf16s_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;
#if __ARM_NEON && __aarch64__
Mat top_blob_fp32(outw, outh, opt.num_threads, (size_t)4u * 4 * 2, 4 * 2, opt.workspace_allocator);
#else
Mat top_blob_fp32(outw, outh, opt.num_threads, (size_t)4u * 4, 4, opt.workspace_allocator);
#endif
const float* bias = _bias;
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob_fp32.channel(get_omp_thread_num());
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f);
float32x4_t _bias1 = bias ? vld1q_f32((const float*)bias + (p+1) * 4) : vdupq_n_f32(0.f);
{
float* ptr = (float*)out0;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias0);
vst1q_f32(ptr+8, _bias0);
vst1q_f32(ptr+12, _bias0);
vst1q_f32(ptr+16, _bias1);
vst1q_f32(ptr+20, _bias1);
vst1q_f32(ptr+24, _bias1);
vst1q_f32(ptr+28, _bias1);
ptr += 32;
}
for (; j+1<outw; j+=2)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias0);
vst1q_f32(ptr+8, _bias1);
vst1q_f32(ptr+12, _bias1);
ptr += 16;
}
for (; j<outw; j++)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias1);
ptr += 8;
}
}
}
const unsigned short* k0 = kernel.channel(p);
const unsigned short* k1 = kernel.channel(p+1);
int q=0;
for (; q<inch-1; q++)
{
float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
float32x4_t _k00_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1), 16));
float32x4_t _k01_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+4), 16));
float32x4_t _k02_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+8), 16));
float32x4_t _k10_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+12), 16));
float32x4_t _k11_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+16), 16));
float32x4_t _k12_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+20), 16));
float32x4_t _k20_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+24), 16));
float32x4_t _k21_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+28), 16));
float32x4_t _k22_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
asm volatile(
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1], #8 \n"
"ld1 {v1.s}[0], [%1] \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%0] \n"
"fmla v24.4s, %8.4s, v0.s[0] \n"
"fmla v25.4s, %8.4s, v0.s[1] \n"
"fmla v26.4s, %8.4s, v0.s[2] \n"
"fmla v27.4s, %8.4s, v0.s[3] \n"
"fmla v28.4s, %17.4s, v0.s[0] \n"
"fmla v29.4s, %17.4s, v0.s[1] \n"
"fmla v30.4s, %17.4s, v0.s[2] \n"
"fmla v31.4s, %17.4s, v0.s[3] \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v2.4h}, [%2], #8 \n"
"ld1 {v3.s}[0], [%2] \n"
"fmla v24.4s, %9.4s, v0.s[1] \n"
"fmla v25.4s, %9.4s, v0.s[2] \n"
"fmla v26.4s, %9.4s, v0.s[3] \n"
"fmla v27.4s, %9.4s, v1.s[0] \n"
"fmla v28.4s, %18.4s, v0.s[1] \n"
"fmla v29.4s, %18.4s, v0.s[2] \n"
"fmla v30.4s, %18.4s, v0.s[3] \n"
"fmla v31.4s, %18.4s, v1.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v24.4s, %10.4s, v0.s[2] \n"
"fmla v25.4s, %10.4s, v0.s[3] \n"
"fmla v26.4s, %10.4s, v1.s[0] \n"
"fmla v27.4s, %10.4s, v1.s[1] \n"
"fmla v28.4s, %19.4s, v0.s[2] \n"
"fmla v29.4s, %19.4s, v0.s[3] \n"
"fmla v30.4s, %19.4s, v1.s[0] \n"
"fmla v31.4s, %19.4s, v1.s[1] \n"
"fmla v24.4s, %11.4s, v2.s[0] \n"
"fmla v25.4s, %11.4s, v2.s[1] \n"
"fmla v26.4s, %11.4s, v2.s[2] \n"
"fmla v27.4s, %11.4s, v2.s[3] \n"
"fmla v28.4s, %20.4s, v2.s[0] \n"
"fmla v29.4s, %20.4s, v2.s[1] \n"
"fmla v30.4s, %20.4s, v2.s[2] \n"
"fmla v31.4s, %20.4s, v2.s[3] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"ld1 {v1.s}[0], [%3] \n"
"fmla v24.4s, %12.4s, v2.s[1] \n"
"fmla v25.4s, %12.4s, v2.s[2] \n"
"fmla v26.4s, %12.4s, v2.s[3] \n"
"fmla v27.4s, %12.4s, v3.s[0] \n"
"fmla v28.4s, %21.4s, v2.s[1] \n"
"fmla v29.4s, %21.4s, v2.s[2] \n"
"fmla v30.4s, %21.4s, v2.s[3] \n"
"fmla v31.4s, %21.4s, v3.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %13.4s, v2.s[2] \n"
"fmla v25.4s, %13.4s, v2.s[3] \n"
"fmla v26.4s, %13.4s, v3.s[0] \n"
"fmla v27.4s, %13.4s, v3.s[1] \n"
"fmla v28.4s, %22.4s, v2.s[2] \n"
"fmla v29.4s, %22.4s, v2.s[3] \n"
"fmla v30.4s, %22.4s, v3.s[0] \n"
"fmla v31.4s, %22.4s, v3.s[1] \n"
"fmla v24.4s, %14.4s, v0.s[0] \n"
"fmla v25.4s, %14.4s, v0.s[1] \n"
"fmla v26.4s, %14.4s, v0.s[2] \n"
"fmla v27.4s, %14.4s, v0.s[3] \n"
"fmla v28.4s, %23.4s, v0.s[0] \n"
"fmla v29.4s, %23.4s, v0.s[1] \n"
"fmla v30.4s, %23.4s, v0.s[2] \n"
"fmla v31.4s, %23.4s, v0.s[3] \n"
"fmla v24.4s, %15.4s, v0.s[1] \n"
"fmla v25.4s, %15.4s, v0.s[2] \n"
"fmla v26.4s, %15.4s, v0.s[3] \n"
"fmla v27.4s, %15.4s, v1.s[0] \n"
"fmla v28.4s, %24.4s, v0.s[1] \n"
"fmla v29.4s, %24.4s, v0.s[2] \n"
"fmla v30.4s, %24.4s, v0.s[3] \n"
"fmla v31.4s, %24.4s, v1.s[0] \n"
"sub %0, %0, #64 \n"
"fmla v24.4s, %16.4s, v0.s[2] \n"
"fmla v25.4s, %16.4s, v0.s[3] \n"
"fmla v26.4s, %16.4s, v1.s[0] \n"
"fmla v27.4s, %16.4s, v1.s[1] \n"
"fmla v28.4s, %25.4s, v0.s[2] \n"
"fmla v29.4s, %25.4s, v0.s[3] \n"
"fmla v30.4s, %25.4s, v1.s[0] \n"
"fmla v31.4s, %25.4s, v1.s[1] \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00_0), // %8
"w"(_k01_0), // %9
"w"(_k02_0), // %10
"w"(_k10_0), // %11
"w"(_k11_0), // %12
"w"(_k12_0), // %13
"w"(_k20_0), // %14
"w"(_k21_0), // %15
"w"(_k22_0), // %16
"w"(_k00_1), // %17
"w"(_k01_1), // %18
"w"(_k02_1), // %19
"w"(_k10_1), // %20
"w"(_k11_1), // %21
"w"(_k12_1), // %22
"w"(_k20_1), // %23
"w"(_k21_1), // %24
"w"(_k22_1) // %25
: "memory", "v0", "v1", "v2", "v3", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; j+1<outw; j+=2)
{
asm volatile(
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1] \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v24.4s, %8.4s, v0.s[0] \n"
"fmla v25.4s, %8.4s, v0.s[1] \n"
"fmla v26.4s, %17.4s, v0.s[0] \n"
"fmla v27.4s, %17.4s, v0.s[1] \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v1.4h}, [%2] \n"
"fmla v24.4s, %9.4s, v0.s[1] \n"
"fmla v25.4s, %9.4s, v0.s[2] \n"
"fmla v26.4s, %18.4s, v0.s[1] \n"
"fmla v27.4s, %18.4s, v0.s[2] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %10.4s, v0.s[2] \n"
"fmla v25.4s, %10.4s, v0.s[3] \n"
"fmla v26.4s, %19.4s, v0.s[2] \n"
"fmla v27.4s, %19.4s, v0.s[3] \n"
"fmla v24.4s, %11.4s, v1.s[0] \n"
"fmla v25.4s, %11.4s, v1.s[1] \n"
"fmla v26.4s, %20.4s, v1.s[0] \n"
"fmla v27.4s, %20.4s, v1.s[1] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3] \n"
"fmla v24.4s, %12.4s, v1.s[1] \n"
"fmla v25.4s, %12.4s, v1.s[2] \n"
"fmla v26.4s, %21.4s, v1.s[1] \n"
"fmla v27.4s, %21.4s, v1.s[2] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v24.4s, %13.4s, v1.s[2] \n"
"fmla v25.4s, %13.4s, v1.s[3] \n"
"fmla v26.4s, %22.4s, v1.s[2] \n"
"fmla v27.4s, %22.4s, v1.s[3] \n"
"fmla v24.4s, %14.4s, v0.s[0] \n"
"fmla v25.4s, %14.4s, v0.s[1] \n"
"fmla v26.4s, %23.4s, v0.s[0] \n"
"fmla v27.4s, %23.4s, v0.s[1] \n"
"add %1, %1, #8 \n"
"fmla v24.4s, %15.4s, v0.s[1] \n"
"fmla v25.4s, %15.4s, v0.s[2] \n"
"fmla v26.4s, %24.4s, v0.s[1] \n"
"fmla v27.4s, %24.4s, v0.s[2] \n"
"add %2, %2, #8 \n"
"fmla v24.4s, %16.4s, v0.s[2] \n"
"fmla v25.4s, %16.4s, v0.s[3] \n"
"fmla v26.4s, %25.4s, v0.s[2] \n"
"fmla v27.4s, %25.4s, v0.s[3] \n"
"add %3, %3, #8 \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00_0), // %8
"w"(_k01_0), // %9
"w"(_k02_0), // %10
"w"(_k10_0), // %11
"w"(_k11_0), // %12
"w"(_k12_0), // %13
"w"(_k20_0), // %14
"w"(_k21_0), // %15
"w"(_k22_0), // %16
"w"(_k00_1), // %17
"w"(_k01_1), // %18
"w"(_k02_1), // %19
"w"(_k10_1), // %20
"w"(_k11_1), // %21
"w"(_k12_1), // %22
"w"(_k20_1), // %23
"w"(_k21_1), // %24
"w"(_k22_1) // %25
: "memory", "v0", "v1", "v24", "v25", "v26", "v27"
);
}
for (; j<outw; j++)
{
float32x4_t _sum00 = vld1q_f32(outptr0);
float32x4_t _sum10 = vld1q_f32(outptr0+4);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
_sum00 = vfmaq_laneq_f32(_sum00, _k00_0, _r0, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k01_0, _r0, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k02_0, _r0, 2);
_sum00 = vfmaq_laneq_f32(_sum00, _k10_0, _r1, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k11_0, _r1, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k12_0, _r1, 2);
_sum00 = vfmaq_laneq_f32(_sum00, _k20_0, _r2, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k21_0, _r2, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k22_0, _r2, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k00_1, _r0, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k01_1, _r0, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k02_1, _r0, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k10_1, _r1, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k11_1, _r1, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k12_1, _r1, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k20_1, _r2, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k21_1, _r2, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k22_1, _r2, 2);
vst1q_f32(outptr0, _sum00);
vst1q_f32(outptr0+4, _sum10);
r0 += 1;
r1 += 1;
r2 += 1;
outptr0 += 8;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
k0 += 9*4;
k1 += 9*4;
}
for (; q<inch; q++)
{
unsigned short* outptr0_bf16 = top_blob.channel(p);
unsigned short* outptr1_bf16 = top_blob.channel(p+1);
const float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
float32x4_t _k00_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1), 16));
float32x4_t _k01_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+4), 16));
float32x4_t _k02_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+8), 16));
float32x4_t _k10_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+12), 16));
float32x4_t _k11_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+16), 16));
float32x4_t _k12_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+20), 16));
float32x4_t _k20_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+24), 16));
float32x4_t _k21_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+28), 16));
float32x4_t _k22_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
asm volatile(
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"ld1 {v1.s}[0], [%3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n"
"fmla v24.4s, %12.4s, v0.s[0] \n"
"fmla v25.4s, %12.4s, v0.s[1] \n"
"fmla v26.4s, %12.4s, v0.s[2] \n"
"fmla v27.4s, %12.4s, v0.s[3] \n"
"fmla v28.4s, %21.4s, v0.s[0] \n"
"fmla v29.4s, %21.4s, v0.s[1] \n"
"fmla v30.4s, %21.4s, v0.s[2] \n"
"fmla v31.4s, %21.4s, v0.s[3] \n"
"fmla v24.4s, %13.4s, v0.s[1] \n"
"fmla v25.4s, %13.4s, v0.s[2] \n"
"fmla v26.4s, %13.4s, v0.s[3] \n"
"fmla v27.4s, %13.4s, v1.s[0] \n"
"fmla v28.4s, %22.4s, v0.s[1] \n"
"fmla v29.4s, %22.4s, v0.s[2] \n"
"fmla v30.4s, %22.4s, v0.s[3] \n"
"fmla v31.4s, %22.4s, v1.s[0] \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v2.4h}, [%4], #8 \n"
"ld1 {v3.s}[0], [%4] \n"
"fmla v24.4s, %14.4s, v0.s[2] \n"
"fmla v25.4s, %14.4s, v0.s[3] \n"
"fmla v26.4s, %14.4s, v1.s[0] \n"
"fmla v27.4s, %14.4s, v1.s[1] \n"
"fmla v28.4s, %23.4s, v0.s[2] \n"
"fmla v29.4s, %23.4s, v0.s[3] \n"
"fmla v30.4s, %23.4s, v1.s[0] \n"
"fmla v31.4s, %23.4s, v1.s[1] \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v24.4s, %15.4s, v2.s[0] \n"
"fmla v25.4s, %15.4s, v2.s[1] \n"
"fmla v26.4s, %15.4s, v2.s[2] \n"
"fmla v27.4s, %15.4s, v2.s[3] \n"
"fmla v28.4s, %24.4s, v2.s[0] \n"
"fmla v29.4s, %24.4s, v2.s[1] \n"
"fmla v30.4s, %24.4s, v2.s[2] \n"
"fmla v31.4s, %24.4s, v2.s[3] \n"
"fmla v24.4s, %16.4s, v2.s[1] \n"
"fmla v25.4s, %16.4s, v2.s[2] \n"
"fmla v26.4s, %16.4s, v2.s[3] \n"
"fmla v27.4s, %16.4s, v3.s[0] \n"
"fmla v28.4s, %25.4s, v2.s[1] \n"
"fmla v29.4s, %25.4s, v2.s[2] \n"
"fmla v30.4s, %25.4s, v2.s[3] \n"
"fmla v31.4s, %25.4s, v3.s[0] \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"ld1 {v1.s}[0], [%5] \n"
"fmla v24.4s, %17.4s, v2.s[2] \n"
"fmla v25.4s, %17.4s, v2.s[3] \n"
"fmla v26.4s, %17.4s, v3.s[0] \n"
"fmla v27.4s, %17.4s, v3.s[1] \n"
"fmla v28.4s, %26.4s, v2.s[2] \n"
"fmla v29.4s, %26.4s, v2.s[3] \n"
"fmla v30.4s, %26.4s, v3.s[0] \n"
"fmla v31.4s, %26.4s, v3.s[1] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %18.4s, v0.s[0] \n"
"fmla v25.4s, %18.4s, v0.s[1] \n"
"fmla v26.4s, %18.4s, v0.s[2] \n"
"fmla v27.4s, %18.4s, v0.s[3] \n"
"fmla v28.4s, %27.4s, v0.s[0] \n"
"fmla v29.4s, %27.4s, v0.s[1] \n"
"fmla v30.4s, %27.4s, v0.s[2] \n"
"fmla v31.4s, %27.4s, v0.s[3] \n"
"fmla v24.4s, %19.4s, v0.s[1] \n"
"fmla v25.4s, %19.4s, v0.s[2] \n"
"fmla v26.4s, %19.4s, v0.s[3] \n"
"fmla v27.4s, %19.4s, v1.s[0] \n"
"fmla v28.4s, %28.4s, v0.s[1] \n"
"fmla v29.4s, %28.4s, v0.s[2] \n"
"fmla v30.4s, %28.4s, v0.s[3] \n"
"fmla v31.4s, %28.4s, v1.s[0] \n"
"fmla v24.4s, %20.4s, v0.s[2] \n"
"fmla v25.4s, %20.4s, v0.s[3] \n"
"fmla v26.4s, %20.4s, v1.s[0] \n"
"fmla v27.4s, %20.4s, v1.s[1] \n"
"fmla v28.4s, %29.4s, v0.s[2] \n"
"fmla v29.4s, %29.4s, v0.s[3] \n"
"fmla v30.4s, %29.4s, v1.s[0] \n"
"fmla v31.4s, %29.4s, v1.s[1] \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"shrn v30.4h, v30.4s, #16 \n"
"shrn v31.4h, v31.4s, #16 \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%0], #32 \n"
"st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%1], #32 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr1_bf16), // %1
"=r"(outptr0), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(outptr0_bf16),
"1"(outptr1_bf16),
"2"(outptr0),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00_0), // %12
"w"(_k01_0), // %13
"w"(_k02_0), // %14
"w"(_k10_0), // %15
"w"(_k11_0), // %16
"w"(_k12_0), // %17
"w"(_k20_0), // %18
"w"(_k21_0), // %19
"w"(_k22_0), // %20
"w"(_k00_1), // %21
"w"(_k01_1), // %22
"w"(_k02_1), // %23
"w"(_k10_1), // %24
"w"(_k11_1), // %25
"w"(_k12_1), // %26
"w"(_k20_1), // %27
"w"(_k21_1), // %28
"w"(_k22_1) // %29
: "memory", "v0", "v1", "v2", "v3", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
for (; j+1<outw; j+=2)
{
asm volatile(
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3] \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v24.4s, %12.4s, v0.s[0] \n"
"fmla v25.4s, %12.4s, v0.s[1] \n"
"fmla v26.4s, %21.4s, v0.s[0] \n"
"fmla v27.4s, %21.4s, v0.s[1] \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v1.4h}, [%4] \n"
"fmla v24.4s, %13.4s, v0.s[1] \n"
"fmla v25.4s, %13.4s, v0.s[2] \n"
"fmla v26.4s, %22.4s, v0.s[1] \n"
"fmla v27.4s, %22.4s, v0.s[2] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %14.4s, v0.s[2] \n"
"fmla v25.4s, %14.4s, v0.s[3] \n"
"fmla v26.4s, %23.4s, v0.s[2] \n"
"fmla v27.4s, %23.4s, v0.s[3] \n"
"fmla v24.4s, %15.4s, v1.s[0] \n"
"fmla v25.4s, %15.4s, v1.s[1] \n"
"fmla v26.4s, %24.4s, v1.s[0] \n"
"fmla v27.4s, %24.4s, v1.s[1] \n"
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5] \n"
"fmla v24.4s, %16.4s, v1.s[1] \n"
"fmla v25.4s, %16.4s, v1.s[2] \n"
"fmla v26.4s, %25.4s, v1.s[1] \n"
"fmla v27.4s, %25.4s, v1.s[2] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v24.4s, %17.4s, v1.s[2] \n"
"fmla v25.4s, %17.4s, v1.s[3] \n"
"fmla v26.4s, %26.4s, v1.s[2] \n"
"fmla v27.4s, %26.4s, v1.s[3] \n"
"fmla v24.4s, %18.4s, v0.s[0] \n"
"fmla v25.4s, %18.4s, v0.s[1] \n"
"fmla v26.4s, %27.4s, v0.s[0] \n"
"fmla v27.4s, %27.4s, v0.s[1] \n"
"fmla v24.4s, %19.4s, v0.s[1] \n"
"fmla v25.4s, %19.4s, v0.s[2] \n"
"fmla v26.4s, %28.4s, v0.s[1] \n"
"fmla v27.4s, %28.4s, v0.s[2] \n"
"add %3, %3, #8 \n"
"fmla v24.4s, %20.4s, v0.s[2] \n"
"fmla v25.4s, %20.4s, v0.s[3] \n"
"fmla v26.4s, %29.4s, v0.s[2] \n"
"fmla v27.4s, %29.4s, v0.s[3] \n"
"add %4, %4, #8 \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"add %5, %5, #8 \n"
"st1 {v24.4h, v25.4h}, [%0], #16 \n"
"st1 {v26.4h, v27.4h}, [%1], #16 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr1_bf16), // %1
"=r"(outptr0), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(outptr0_bf16),
"1"(outptr1_bf16),
"2"(outptr0),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00_0), // %12
"w"(_k01_0), // %13
"w"(_k02_0), // %14
"w"(_k10_0), // %15
"w"(_k11_0), // %16
"w"(_k12_0), // %17
"w"(_k20_0), // %18
"w"(_k21_0), // %19
"w"(_k22_0), // %20
"w"(_k00_1), // %21
"w"(_k01_1), // %22
"w"(_k02_1), // %23
"w"(_k10_1), // %24
"w"(_k11_1), // %25
"w"(_k12_1), // %26
"w"(_k20_1), // %27
"w"(_k21_1), // %28
"w"(_k22_1) // %29
: "memory", "v0", "v1", "v24", "v25", "v26", "v27"
);
}
for (; j<outw; j++)
{
float32x4_t _sum00 = vld1q_f32(outptr0);
float32x4_t _sum10 = vld1q_f32(outptr0+4);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
_sum00 = vfmaq_laneq_f32(_sum00, _k00_0, _r0, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k01_0, _r0, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k02_0, _r0, 2);
_sum00 = vfmaq_laneq_f32(_sum00, _k10_0, _r1, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k11_0, _r1, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k12_0, _r1, 2);
_sum00 = vfmaq_laneq_f32(_sum00, _k20_0, _r2, 0);
_sum00 = vfmaq_laneq_f32(_sum00, _k21_0, _r2, 1);
_sum00 = vfmaq_laneq_f32(_sum00, _k22_0, _r2, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k00_1, _r0, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k01_1, _r0, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k02_1, _r0, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k10_1, _r1, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k11_1, _r1, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k12_1, _r1, 2);
_sum10 = vfmaq_laneq_f32(_sum10, _k20_1, _r2, 0);
_sum10 = vfmaq_laneq_f32(_sum10, _k21_1, _r2, 1);
_sum10 = vfmaq_laneq_f32(_sum10, _k22_1, _r2, 2);
vst1_u16(outptr0_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum00), 16));
vst1_u16(outptr1_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum10), 16));
r0 += 1;
r1 += 1;
r2 += 1;
outptr0 += 8;
outptr0_bf16 += 4;
outptr1_bf16 += 4;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
k0 += 9*4;
k1 += 9*4;
}
}
#endif // __ARM_NEON && __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob_fp32.channel(get_omp_thread_num());
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f);
out0.fill(_bias0);
const unsigned short* k0 = kernel.channel(p);
int q=0;
for (; q<inch-1; q++)
{
float* outptr0 = out0.row(0);
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<unsigned short>(0);
const unsigned short* r1 = img0.row<unsigned short>(1);
const unsigned short* r2 = img0.row<unsigned short>(2);
float32x4_t _k00 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
#if __aarch64__
for (; j+7<outw; j+=8)
{
asm volatile(
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
// "prfm pldl1keep, [%0, #512] \n"
"ld1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%0] \n"
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v0.4h, v1.4h}, [%1], #16 \n"
"ld1 {v2.s}[0], [%1] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %8.4s, v0.s[0] \n"
"fmla v25.4s, %8.4s, v0.s[1] \n"
"fmla v26.4s, %8.4s, v0.s[2] \n"
"fmla v27.4s, %8.4s, v0.s[3] \n"
"fmla v28.4s, %8.4s, v1.s[0] \n"
"fmla v29.4s, %8.4s, v1.s[1] \n"
"fmla v30.4s, %8.4s, v1.s[2] \n"
"fmla v31.4s, %8.4s, v1.s[3] \n"
"fmla v24.4s, %9.4s, v0.s[1] \n"
"fmla v25.4s, %9.4s, v0.s[2] \n"
"fmla v26.4s, %9.4s, v0.s[3] \n"
"fmla v27.4s, %9.4s, v1.s[0] \n"
"fmla v28.4s, %9.4s, v1.s[1] \n"
"fmla v29.4s, %9.4s, v1.s[2] \n"
"fmla v30.4s, %9.4s, v1.s[3] \n"
"fmla v31.4s, %9.4s, v2.s[0] \n"
"fmla v24.4s, %10.4s, v0.s[2] \n"
"fmla v25.4s, %10.4s, v0.s[3] \n"
"fmla v26.4s, %10.4s, v1.s[0] \n"
"fmla v27.4s, %10.4s, v1.s[1] \n"
"fmla v28.4s, %10.4s, v1.s[2] \n"
"fmla v29.4s, %10.4s, v1.s[3] \n"
"fmla v30.4s, %10.4s, v2.s[0] \n"
"fmla v31.4s, %10.4s, v2.s[1] \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v4.4h, v5.4h}, [%2], #16 \n"
"ld1 {v2.s}[0], [%2] \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %11.4s, v4.s[0] \n"
"fmla v25.4s, %11.4s, v4.s[1] \n"
"fmla v26.4s, %11.4s, v4.s[2] \n"
"fmla v27.4s, %11.4s, v4.s[3] \n"
"fmla v28.4s, %11.4s, v5.s[0] \n"
"fmla v29.4s, %11.4s, v5.s[1] \n"
"fmla v30.4s, %11.4s, v5.s[2] \n"
"fmla v31.4s, %11.4s, v5.s[3] \n"
"fmla v24.4s, %12.4s, v4.s[1] \n"
"fmla v25.4s, %12.4s, v4.s[2] \n"
"fmla v26.4s, %12.4s, v4.s[3] \n"
"fmla v27.4s, %12.4s, v5.s[0] \n"
"fmla v28.4s, %12.4s, v5.s[1] \n"
"fmla v29.4s, %12.4s, v5.s[2] \n"
"fmla v30.4s, %12.4s, v5.s[3] \n"
"fmla v31.4s, %12.4s, v2.s[0] \n"
"fmla v24.4s, %13.4s, v4.s[2] \n"
"fmla v25.4s, %13.4s, v4.s[3] \n"
"fmla v26.4s, %13.4s, v5.s[0] \n"
"fmla v27.4s, %13.4s, v5.s[1] \n"
"fmla v28.4s, %13.4s, v5.s[2] \n"
"fmla v29.4s, %13.4s, v5.s[3] \n"
"fmla v30.4s, %13.4s, v2.s[0] \n"
"fmla v31.4s, %13.4s, v2.s[1] \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4h, v1.4h}, [%3], #16 \n"
"ld1 {v2.s}[0], [%3] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %14.4s, v0.s[0] \n"
"fmla v25.4s, %14.4s, v0.s[1] \n"
"fmla v26.4s, %14.4s, v0.s[2] \n"
"fmla v27.4s, %14.4s, v0.s[3] \n"
"fmla v28.4s, %14.4s, v1.s[0] \n"
"fmla v29.4s, %14.4s, v1.s[1] \n"
"fmla v30.4s, %14.4s, v1.s[2] \n"
"fmla v31.4s, %14.4s, v1.s[3] \n"
"fmla v24.4s, %15.4s, v0.s[1] \n"
"fmla v25.4s, %15.4s, v0.s[2] \n"
"fmla v26.4s, %15.4s, v0.s[3] \n"
"fmla v27.4s, %15.4s, v1.s[0] \n"
"fmla v28.4s, %15.4s, v1.s[1] \n"
"fmla v29.4s, %15.4s, v1.s[2] \n"
"fmla v30.4s, %15.4s, v1.s[3] \n"
"fmla v31.4s, %15.4s, v2.s[0] \n"
"sub %0, %0, #64 \n"
"fmla v24.4s, %16.4s, v0.s[2] \n"
"fmla v25.4s, %16.4s, v0.s[3] \n"
"fmla v26.4s, %16.4s, v1.s[0] \n"
"fmla v27.4s, %16.4s, v1.s[1] \n"
"fmla v28.4s, %16.4s, v1.s[2] \n"
"fmla v29.4s, %16.4s, v1.s[3] \n"
"fmla v30.4s, %16.4s, v2.s[0] \n"
"fmla v31.4s, %16.4s, v2.s[1] \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
"st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v4", "v5", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
#endif // __aarch64__
for (; j+3<outw; j+=4)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1], #8 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0] \n"
"shll v0.4s, v0.4h, #16 \n"
"ld1 {v1.s}[0], [%1] \n"
"fmla v24.4s, %8.4s, v0.s[0] \n"
"fmla v25.4s, %8.4s, v0.s[1] \n"
"fmla v26.4s, %8.4s, v0.s[2] \n"
"fmla v27.4s, %8.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %9.4s, v0.s[1] \n"
"fmla v25.4s, %9.4s, v0.s[2] \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v2.4h}, [%2], #8 \n"
"fmla v26.4s, %9.4s, v0.s[3] \n"
"fmla v27.4s, %9.4s, v1.s[0] \n"
"ld1 {v3.s}[0], [%2] \n"
"fmla v24.4s, %10.4s, v0.s[2] \n"
"fmla v25.4s, %10.4s, v0.s[3] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v26.4s, %10.4s, v1.s[0] \n"
"fmla v27.4s, %10.4s, v1.s[1] \n"
"fmla v24.4s, %11.4s, v2.s[0] \n"
"fmla v25.4s, %11.4s, v2.s[1] \n"
"fmla v26.4s, %11.4s, v2.s[2] \n"
"fmla v27.4s, %11.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v24.4s, %12.4s, v2.s[1] \n"
"fmla v25.4s, %12.4s, v2.s[2] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"fmla v26.4s, %12.4s, v2.s[3] \n"
"fmla v27.4s, %12.4s, v3.s[0] \n"
"ld1 {v1.s}[0], [%3] \n"
"fmla v24.4s, %13.4s, v2.s[2] \n"
"fmla v25.4s, %13.4s, v2.s[3] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v26.4s, %13.4s, v3.s[0] \n"
"fmla v27.4s, %13.4s, v3.s[1] \n"
"fmla v24.4s, %14.4s, v0.s[0] \n"
"fmla v25.4s, %14.4s, v0.s[1] \n"
"fmla v26.4s, %14.4s, v0.s[2] \n"
"fmla v27.4s, %14.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %15.4s, v0.s[1] \n"
"fmla v25.4s, %15.4s, v0.s[2] \n"
"fmla v26.4s, %15.4s, v0.s[3] \n"
"fmla v27.4s, %15.4s, v1.s[0] \n"
"fmla v24.4s, %16.4s, v0.s[2] \n"
"fmla v25.4s, %16.4s, v0.s[3] \n"
"fmla v26.4s, %16.4s, v1.s[0] \n"
"fmla v27.4s, %16.4s, v1.s[1] \n"
"st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v2", "v3", "v24", "v25", "v26", "v27"
);
#else // __aarch64__
asm volatile(
"pld [%0, #512] \n"
"vldm %0, {d24-d31} \n"
"pld [%1, #64] \n"
"vld1.u16 {d1}, [%1]! \n"
"vld1.u16 {d2[0]}, [%1] \n"
"vshll.u16 q0, d1, #16 \n"
"vshl.u32 d2, d2, #16 \n"
"vmla.f32 q12, %q8, d0[0] \n"
"vmla.f32 q13, %q8, d0[1] \n"
"vmla.f32 q14, %q8, d1[0] \n"
"vmla.f32 q15, %q8, d1[1] \n"
"vmla.f32 q12, %q9, d0[1] \n"
"vmla.f32 q13, %q9, d1[0] \n"
"vmla.f32 q14, %q9, d1[1] \n"
"vmla.f32 q15, %q9, d2[0] \n"
"vmla.f32 q12, %q10, d1[0] \n"
"vmla.f32 q13, %q10, d1[1] \n"
"vmla.f32 q14, %q10, d2[0] \n"
"vmla.f32 q15, %q10, d2[1] \n"
"pld [%2, #64] \n"
"vld1.u16 {d5}, [%2]! \n"
"vld1.u16 {d3[0]}, [%2] \n"
"vshll.u16 q2, d5, #16 \n"
"vshl.u32 d3, d3, #16 \n"
"vmla.f32 q12, %q11, d4[0] \n"
"vmla.f32 q13, %q11, d4[1] \n"
"vmla.f32 q14, %q11, d5[0] \n"
"vmla.f32 q15, %q11, d5[1] \n"
"vmla.f32 q12, %q12, d4[1] \n"
"vmla.f32 q13, %q12, d5[0] \n"
"vmla.f32 q14, %q12, d5[1] \n"
"vmla.f32 q15, %q12, d3[0] \n"
"vmla.f32 q12, %q13, d5[0] \n"
"vmla.f32 q13, %q13, d5[1] \n"
"vmla.f32 q14, %q13, d3[0] \n"
"vmla.f32 q15, %q13, d3[1] \n"
"pld [%3, #64] \n"
"vld1.u16 {d1}, [%3]! \n"
"vld1.u16 {d2[0]}, [%3] \n"
"vshll.u16 q0, d1, #16 \n"
"vshl.u32 d2, d2, #16 \n"
"vmla.f32 q12, %q14, d0[0] \n"
"vmla.f32 q13, %q14, d0[1] \n"
"vmla.f32 q14, %q14, d1[0] \n"
"vmla.f32 q15, %q14, d1[1] \n"
"vmla.f32 q12, %q15, d0[1] \n"
"vmla.f32 q13, %q15, d1[0] \n"
"vmla.f32 q14, %q15, d1[1] \n"
"vmla.f32 q15, %q15, d2[0] \n"
"vmla.f32 q12, %q16, d1[0] \n"
"vmla.f32 q13, %q16, d1[1] \n"
"vmla.f32 q14, %q16, d2[0] \n"
"vmla.f32 q15, %q16, d2[1] \n"
"vstm %0!, {d24-d31} \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "q0", "q1", "q2", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; j+1<outw; j+=2)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1] \n"
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v28.4s, v29.4s}, [%0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmul v24.4s, %8.4s, v0.s[0] \n"
"fmul v25.4s, %8.4s, v0.s[1] \n"
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v1.4h}, [%2] \n"
"fmul v26.4s, %9.4s, v0.s[1] \n"
"fmul v27.4s, %9.4s, v0.s[2] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v28.4s, %10.4s, v0.s[2] \n"
"fmla v29.4s, %10.4s, v0.s[3] \n"
"fmla v24.4s, %11.4s, v1.s[0] \n"
"fmla v25.4s, %11.4s, v1.s[1] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3] \n"
"fmla v26.4s, %12.4s, v1.s[1] \n"
"fmla v27.4s, %12.4s, v1.s[2] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v28.4s, %13.4s, v1.s[2] \n"
"fmla v29.4s, %13.4s, v1.s[3] \n"
"fmla v24.4s, %14.4s, v0.s[0] \n"
"fmla v25.4s, %14.4s, v0.s[1] \n"
"fmla v26.4s, %15.4s, v0.s[1] \n"
"fmla v27.4s, %15.4s, v0.s[2] \n"
"fmla v28.4s, %16.4s, v0.s[2] \n"
"fmla v29.4s, %16.4s, v0.s[3] \n"
"add %1, %1, #8 \n"
"fadd v24.4s, v24.4s, v26.4s \n"
"fadd v25.4s, v25.4s, v27.4s \n"
"add %2, %2, #8 \n"
"fadd v28.4s, v28.4s, v24.4s \n"
"fadd v29.4s, v29.4s, v25.4s \n"
"add %3, %3, #8 \n"
"st1 {v28.4s, v29.4s}, [%0], #32 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "v0", "v1", "v24", "v25", "v26", "v27", "v28", "v29"
);
#else // __aarch64__
asm volatile(
"pld [%1, #64] \n"
"vld1.u16 {d1}, [%1] \n"
"pld [%0, #256] \n"
"vld1.f32 {d24-d27}, [%0 :128] \n"
"vshll.u16 q0, d1, #16 \n"
"vmul.f32 q14, %q8, d0[0] \n"
"vmul.f32 q15, %q8, d0[1] \n"
"vmla.f32 q12, %q9, d0[1] \n"
"vmla.f32 q13, %q9, d1[0] \n"
"pld [%2, #64] \n"
"vld1.u16 {d3}, [%2] \n"
"vmla.f32 q14, %q10, d1[0] \n"
"vmla.f32 q15, %q10, d1[1] \n"
"vshll.u16 q1, d3, #16 \n"
"vmla.f32 q12, %q11, d2[0] \n"
"vmla.f32 q13, %q11, d2[1] \n"
"vmla.f32 q14, %q12, d2[1] \n"
"vmla.f32 q15, %q12, d3[0] \n"
"pld [%3, #64] \n"
"vld1.u16 {d1}, [%3] \n"
"vmla.f32 q12, %q13, d3[0] \n"
"vmla.f32 q13, %q13, d3[1] \n"
"vshll.u16 q0, d1, #16 \n"
"vmla.f32 q14, %q14, d0[0] \n"
"vmla.f32 q15, %q14, d0[1] \n"
"vmla.f32 q12, %q15, d0[1] \n"
"vmla.f32 q13, %q15, d1[0] \n"
"add %1, %1, #8 \n"
"vmla.f32 q14, %q16, d1[0] \n"
"vmla.f32 q15, %q16, d1[1] \n"
"add %2, %2, #8 \n"
"vadd.f32 q12, q12, q14 \n"
"vadd.f32 q13, q13, q15 \n"
"add %3, %3, #8 \n"
"vst1.f32 {d24-d27}, [%0 :128]! \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "memory", "q0", "q1", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
#if __aarch64__
_sum0 = vfmaq_laneq_f32(_sum0, _k00, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22, _r2, 2);
#else
_sum0 = vmlaq_lane_f32(_sum0, _k00, vget_low_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k01, vget_low_f32(_r0), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k02, vget_high_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k10, vget_low_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k11, vget_low_f32(_r1), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k12, vget_high_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k20, vget_low_f32(_r2), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k21, vget_low_f32(_r2), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k22, vget_high_f32(_r2), 0);
#endif
vst1q_f32(outptr0, _sum0);
r0 += 1;
r1 += 1;
r2 += 1;
outptr0 += 4;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
k0 += 9*4;
}
for (; q<inch; q++)
{
unsigned short* outptr0_bf16 = top_blob.channel(p);
const float* outptr0 = out0.row(0);
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<unsigned short>(0);
const unsigned short* r1 = img0.row<unsigned short>(1);
const unsigned short* r2 = img0.row<unsigned short>(2);
float32x4_t _k00 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
#if __aarch64__
for (; j+7<outw; j+=8)
{
asm volatile(
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%1], #64 \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%1], #64 \n"
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4h, v1.4h}, [%2], #16 \n"
"ld1 {v2.s}[0], [%2] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %10.4s, v0.s[0] \n"
"fmla v25.4s, %10.4s, v0.s[1] \n"
"fmla v26.4s, %10.4s, v0.s[2] \n"
"fmla v27.4s, %10.4s, v0.s[3] \n"
"fmla v28.4s, %10.4s, v1.s[0] \n"
"fmla v29.4s, %10.4s, v1.s[1] \n"
"fmla v30.4s, %10.4s, v1.s[2] \n"
"fmla v31.4s, %10.4s, v1.s[3] \n"
"fmla v24.4s, %11.4s, v0.s[1] \n"
"fmla v25.4s, %11.4s, v0.s[2] \n"
"fmla v26.4s, %11.4s, v0.s[3] \n"
"fmla v27.4s, %11.4s, v1.s[0] \n"
"fmla v28.4s, %11.4s, v1.s[1] \n"
"fmla v29.4s, %11.4s, v1.s[2] \n"
"fmla v30.4s, %11.4s, v1.s[3] \n"
"fmla v31.4s, %11.4s, v2.s[0] \n"
"fmla v24.4s, %12.4s, v0.s[2] \n"
"fmla v25.4s, %12.4s, v0.s[3] \n"
"fmla v26.4s, %12.4s, v1.s[0] \n"
"fmla v27.4s, %12.4s, v1.s[1] \n"
"fmla v28.4s, %12.4s, v1.s[2] \n"
"fmla v29.4s, %12.4s, v1.s[3] \n"
"fmla v30.4s, %12.4s, v2.s[0] \n"
"fmla v31.4s, %12.4s, v2.s[1] \n"
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v4.4h, v5.4h}, [%3], #16 \n"
"ld1 {v2.s}[0], [%3] \n"
"shll v4.4s, v4.4h, #16 \n"
"shll v5.4s, v5.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %13.4s, v4.s[0] \n"
"fmla v25.4s, %13.4s, v4.s[1] \n"
"fmla v26.4s, %13.4s, v4.s[2] \n"
"fmla v27.4s, %13.4s, v4.s[3] \n"
"fmla v28.4s, %13.4s, v5.s[0] \n"
"fmla v29.4s, %13.4s, v5.s[1] \n"
"fmla v30.4s, %13.4s, v5.s[2] \n"
"fmla v31.4s, %13.4s, v5.s[3] \n"
"fmla v24.4s, %14.4s, v4.s[1] \n"
"fmla v25.4s, %14.4s, v4.s[2] \n"
"fmla v26.4s, %14.4s, v4.s[3] \n"
"fmla v27.4s, %14.4s, v5.s[0] \n"
"fmla v28.4s, %14.4s, v5.s[1] \n"
"fmla v29.4s, %14.4s, v5.s[2] \n"
"fmla v30.4s, %14.4s, v5.s[3] \n"
"fmla v31.4s, %14.4s, v2.s[0] \n"
"fmla v24.4s, %15.4s, v4.s[2] \n"
"fmla v25.4s, %15.4s, v4.s[3] \n"
"fmla v26.4s, %15.4s, v5.s[0] \n"
"fmla v27.4s, %15.4s, v5.s[1] \n"
"fmla v28.4s, %15.4s, v5.s[2] \n"
"fmla v29.4s, %15.4s, v5.s[3] \n"
"fmla v30.4s, %15.4s, v2.s[0] \n"
"fmla v31.4s, %15.4s, v2.s[1] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v0.4h, v1.4h}, [%4], #16 \n"
"ld1 {v2.s}[0], [%4] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v24.4s, %16.4s, v0.s[0] \n"
"fmla v25.4s, %16.4s, v0.s[1] \n"
"fmla v26.4s, %16.4s, v0.s[2] \n"
"fmla v27.4s, %16.4s, v0.s[3] \n"
"fmla v28.4s, %16.4s, v1.s[0] \n"
"fmla v29.4s, %16.4s, v1.s[1] \n"
"fmla v30.4s, %16.4s, v1.s[2] \n"
"fmla v31.4s, %16.4s, v1.s[3] \n"
"fmla v24.4s, %17.4s, v0.s[1] \n"
"fmla v25.4s, %17.4s, v0.s[2] \n"
"fmla v26.4s, %17.4s, v0.s[3] \n"
"fmla v27.4s, %17.4s, v1.s[0] \n"
"fmla v28.4s, %17.4s, v1.s[1] \n"
"fmla v29.4s, %17.4s, v1.s[2] \n"
"fmla v30.4s, %17.4s, v1.s[3] \n"
"fmla v31.4s, %17.4s, v2.s[0] \n"
"fmla v24.4s, %18.4s, v0.s[2] \n"
"fmla v25.4s, %18.4s, v0.s[3] \n"
"fmla v26.4s, %18.4s, v1.s[0] \n"
"fmla v27.4s, %18.4s, v1.s[1] \n"
"fmla v28.4s, %18.4s, v1.s[2] \n"
"fmla v29.4s, %18.4s, v1.s[3] \n"
"fmla v30.4s, %18.4s, v2.s[0] \n"
"fmla v31.4s, %18.4s, v2.s[1] \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"shrn v30.4h, v30.4s, #16 \n"
"shrn v31.4h, v31.4s, #16 \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%0], #32 \n"
"st1 {v28.4h, v29.4h, v30.4h, v31.4h}, [%0], #32 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "memory", "v0", "v1", "v2", "v4", "v5", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
);
}
#endif // __aarch64__
for (; j+3<outw; j+=4)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v0.4h}, [%2], #8 \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%1], #64 \n"
"shll v0.4s, v0.4h, #16 \n"
"ld1 {v1.s}[0], [%2] \n"
"fmla v24.4s, %10.4s, v0.s[0] \n"
"fmla v25.4s, %10.4s, v0.s[1] \n"
"fmla v26.4s, %10.4s, v0.s[2] \n"
"fmla v27.4s, %10.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %11.4s, v0.s[1] \n"
"fmla v25.4s, %11.4s, v0.s[2] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v2.4h}, [%3], #8 \n"
"fmla v26.4s, %11.4s, v0.s[3] \n"
"fmla v27.4s, %11.4s, v1.s[0] \n"
"ld1 {v3.s}[0], [%3] \n"
"fmla v24.4s, %12.4s, v0.s[2] \n"
"fmla v25.4s, %12.4s, v0.s[3] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v26.4s, %12.4s, v1.s[0] \n"
"fmla v27.4s, %12.4s, v1.s[1] \n"
"fmla v24.4s, %13.4s, v2.s[0] \n"
"fmla v25.4s, %13.4s, v2.s[1] \n"
"fmla v26.4s, %13.4s, v2.s[2] \n"
"fmla v27.4s, %13.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v24.4s, %14.4s, v2.s[1] \n"
"fmla v25.4s, %14.4s, v2.s[2] \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v0.4h}, [%4], #8 \n"
"fmla v26.4s, %14.4s, v2.s[3] \n"
"fmla v27.4s, %14.4s, v3.s[0] \n"
"ld1 {v1.s}[0], [%4] \n"
"fmla v24.4s, %15.4s, v2.s[2] \n"
"fmla v25.4s, %15.4s, v2.s[3] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v26.4s, %15.4s, v3.s[0] \n"
"fmla v27.4s, %15.4s, v3.s[1] \n"
"fmla v24.4s, %16.4s, v0.s[0] \n"
"fmla v25.4s, %16.4s, v0.s[1] \n"
"fmla v26.4s, %16.4s, v0.s[2] \n"
"fmla v27.4s, %16.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v24.4s, %17.4s, v0.s[1] \n"
"fmla v25.4s, %17.4s, v0.s[2] \n"
"fmla v26.4s, %17.4s, v0.s[3] \n"
"fmla v27.4s, %17.4s, v1.s[0] \n"
"fmla v24.4s, %18.4s, v0.s[2] \n"
"fmla v25.4s, %18.4s, v0.s[3] \n"
"fmla v26.4s, %18.4s, v1.s[0] \n"
"fmla v27.4s, %18.4s, v1.s[1] \n"
"shrn v24.4h, v24.4s, #16 \n"
"shrn v25.4h, v25.4s, #16 \n"
"shrn v26.4h, v26.4s, #16 \n"
"shrn v27.4h, v27.4s, #16 \n"
"st1 {v24.4h, v25.4h, v26.4h, v27.4h}, [%0], #32 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "memory", "v0", "v1", "v2", "v3", "v24", "v25", "v26", "v27"
);
#else // __aarch64__
asm volatile(
"pld [%1, #512] \n"
"vldm %1!, {d24-d31} \n"
"pld [%2, #64] \n"
"vld1.u16 {d1}, [%2]! \n"
"vld1.u16 {d2[0]}, [%2] \n"
"vshll.u16 q0, d1, #16 \n"
"vshl.u32 d2, d2, #16 \n"
"vmla.f32 q12, %q10, d0[0] \n"
"vmla.f32 q13, %q10, d0[1] \n"
"vmla.f32 q14, %q10, d1[0] \n"
"vmla.f32 q15, %q10, d1[1] \n"
"vmla.f32 q12, %q11, d0[1] \n"
"vmla.f32 q13, %q11, d1[0] \n"
"vmla.f32 q14, %q11, d1[1] \n"
"vmla.f32 q15, %q11, d2[0] \n"
"vmla.f32 q12, %q12, d1[0] \n"
"vmla.f32 q13, %q12, d1[1] \n"
"vmla.f32 q14, %q12, d2[0] \n"
"vmla.f32 q15, %q12, d2[1] \n"
"pld [%3, #64] \n"
"vld1.u16 {d5}, [%3]! \n"
"vld1.u16 {d3[0]}, [%3] \n"
"vshll.u16 q2, d5, #16 \n"
"vshl.u32 d3, d3, #16 \n"
"vmla.f32 q12, %q13, d4[0] \n"
"vmla.f32 q13, %q13, d4[1] \n"
"vmla.f32 q14, %q13, d5[0] \n"
"vmla.f32 q15, %q13, d5[1] \n"
"vmla.f32 q12, %q14, d4[1] \n"
"vmla.f32 q13, %q14, d5[0] \n"
"vmla.f32 q14, %q14, d5[1] \n"
"vmla.f32 q15, %q14, d3[0] \n"
"vmla.f32 q12, %q15, d5[0] \n"
"vmla.f32 q13, %q15, d5[1] \n"
"vmla.f32 q14, %q15, d3[0] \n"
"vmla.f32 q15, %q15, d3[1] \n"
"pld [%4, #64] \n"
"vld1.u16 {d1}, [%4]! \n"
"vld1.u16 {d2[0]}, [%4] \n"
"vshll.u16 q0, d1, #16 \n"
"vshl.u32 d2, d2, #16 \n"
"vmla.f32 q12, %q16, d0[0] \n"
"vmla.f32 q13, %q16, d0[1] \n"
"vmla.f32 q14, %q16, d1[0] \n"
"vmla.f32 q15, %q16, d1[1] \n"
"vmla.f32 q12, %q17, d0[1] \n"
"vmla.f32 q13, %q17, d1[0] \n"
"vmla.f32 q14, %q17, d1[1] \n"
"vmla.f32 q15, %q17, d2[0] \n"
"vmla.f32 q12, %q18, d1[0] \n"
"vmla.f32 q13, %q18, d1[1] \n"
"vmla.f32 q14, %q18, d2[0] \n"
"vmla.f32 q15, %q18, d2[1] \n"
"vshrn.s32 d24, q12, #16 \n"
"vshrn.s32 d25, q13, #16 \n"
"vshrn.s32 d26, q14, #16 \n"
"vshrn.s32 d27, q15, #16 \n"
"vstm %0!, {d24-d27} \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "memory", "q0", "q1", "q2", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; j+1<outw; j+=2)
{
#if __aarch64__
asm volatile(
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v0.4h}, [%2] \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v28.4s, v29.4s}, [%1], #32 \n"
"shll v0.4s, v0.4h, #16 \n"
"fmul v24.4s, %10.4s, v0.s[0] \n"
"fmul v25.4s, %10.4s, v0.s[1] \n"
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v1.4h}, [%3] \n"
"fmul v26.4s, %11.4s, v0.s[1] \n"
"fmul v27.4s, %11.4s, v0.s[2] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v28.4s, %12.4s, v0.s[2] \n"
"fmla v29.4s, %12.4s, v0.s[3] \n"
"fmla v24.4s, %13.4s, v1.s[0] \n"
"fmla v25.4s, %13.4s, v1.s[1] \n"
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v0.4h}, [%4] \n"
"fmla v26.4s, %14.4s, v1.s[1] \n"
"fmla v27.4s, %14.4s, v1.s[2] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v28.4s, %15.4s, v1.s[2] \n"
"fmla v29.4s, %15.4s, v1.s[3] \n"
"fmla v24.4s, %16.4s, v0.s[0] \n"
"fmla v25.4s, %16.4s, v0.s[1] \n"
"fmla v26.4s, %17.4s, v0.s[1] \n"
"fmla v27.4s, %17.4s, v0.s[2] \n"
"fmla v28.4s, %18.4s, v0.s[2] \n"
"fmla v29.4s, %18.4s, v0.s[3] \n"
"add %1, %1, #8 \n"
"fadd v24.4s, v24.4s, v26.4s \n"
"fadd v25.4s, v25.4s, v27.4s \n"
"add %2, %2, #8 \n"
"fadd v28.4s, v28.4s, v24.4s \n"
"fadd v29.4s, v29.4s, v25.4s \n"
"add %3, %3, #8 \n"
"shrn v28.4h, v28.4s, #16 \n"
"shrn v29.4h, v29.4s, #16 \n"
"st1 {v28.4h, v29.4h}, [%0], #16 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "memory", "v0", "v1", "v24", "v25", "v26", "v27", "v28", "v29"
);
#else // __aarch64__
asm volatile(
"pld [%2, #64] \n"
"vld1.u16 {d1}, [%2] \n"
"pld [%1, #256] \n"
"vld1.f32 {d24-d27}, [%1 :128] \n"
"vshll.u16 q0, d1, #16 \n"
"vmul.f32 q14, %q10, d0[0] \n"
"vmul.f32 q15, %q10, d0[1] \n"
"vmla.f32 q12, %q11, d0[1] \n"
"vmla.f32 q13, %q11, d1[0] \n"
"pld [%3, #64] \n"
"vld1.u16 {d3}, [%3] \n"
"vmla.f32 q14, %q12, d1[0] \n"
"vmla.f32 q15, %q12, d1[1] \n"
"vshll.u16 q1, d3, #16 \n"
"vmla.f32 q12, %q13, d2[0] \n"
"vmla.f32 q13, %q13, d2[1] \n"
"vmla.f32 q14, %q14, d2[1] \n"
"vmla.f32 q15, %q14, d3[0] \n"
"pld [%4, #64] \n"
"vld1.u16 {d1}, [%4] \n"
"vmla.f32 q12, %q15, d3[0] \n"
"vmla.f32 q13, %q15, d3[1] \n"
"vshll.u16 q0, d1, #16 \n"
"vmla.f32 q14, %q16, d0[0] \n"
"vmla.f32 q15, %q16, d0[1] \n"
"vmla.f32 q12, %q17, d0[1] \n"
"vmla.f32 q13, %q17, d1[0] \n"
"add %2, %2, #8 \n"
"vmla.f32 q14, %q18, d1[0] \n"
"vmla.f32 q15, %q18, d1[1] \n"
"add %3, %3, #8 \n"
"vadd.f32 q12, q12, q14 \n"
"vadd.f32 q13, q13, q15 \n"
"add %4, %4, #8 \n"
"vshrn.s32 d24, q12, #16 \n"
"vshrn.s32 d25, q13, #16 \n"
"vst1.f32 {d24-d25}, [%0 :64]! \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "memory", "q0", "q1", "q12", "q13", "q14", "q15"
);
#endif // __aarch64__
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
#if __aarch64__
_sum0 = vfmaq_laneq_f32(_sum0, _k00, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22, _r2, 2);
#else
_sum0 = vmlaq_lane_f32(_sum0, _k00, vget_low_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k01, vget_low_f32(_r0), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k02, vget_high_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k10, vget_low_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k11, vget_low_f32(_r1), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k12, vget_high_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k20, vget_low_f32(_r2), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k21, vget_low_f32(_r2), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k22, vget_high_f32(_r2), 0);
#endif
vst1_u16(outptr0_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum0), 16));
r0 += 1;
r1 += 1;
r2 += 1;
outptr0 += 4;
outptr0_bf16 += 4;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
k0 += 9*4;
}
}
}
static void conv3x3s2_pack1to4_bf16s_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;
#if __ARM_NEON && __aarch64__
Mat top_blob_fp32(outw, outh, opt.num_threads, (size_t)4u * 4 * 2, 4 * 2, opt.workspace_allocator);
#else
Mat top_blob_fp32(outw, outh, opt.num_threads, (size_t)4u * 4, 4, opt.workspace_allocator);
#endif
const int tailstep = w - 2*outw + w;
const float* bias = _bias;
int nn_outch = 0;
int remain_outch_start = 0;
#if __ARM_NEON && __aarch64__
nn_outch = outch >> 1;
remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob_fp32.channel(get_omp_thread_num());
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f);
float32x4_t _bias1 = bias ? vld1q_f32((const float*)bias + (p+1) * 4) : vdupq_n_f32(0.f);
{
float* ptr = (float*)out0;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias0);
vst1q_f32(ptr+8, _bias0);
vst1q_f32(ptr+12, _bias0);
vst1q_f32(ptr+16, _bias1);
vst1q_f32(ptr+20, _bias1);
vst1q_f32(ptr+24, _bias1);
vst1q_f32(ptr+28, _bias1);
ptr += 32;
}
for (; j+1<outw; j+=2)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias0);
vst1q_f32(ptr+8, _bias1);
vst1q_f32(ptr+12, _bias1);
ptr += 16;
}
for (; j<outw; j++)
{
vst1q_f32(ptr, _bias0);
vst1q_f32(ptr+4, _bias1);
ptr += 8;
}
}
}
const unsigned short* k0 = kernel.channel(p);
const unsigned short* k1 = kernel.channel(p+1);
int q=0;
for (; q<inch-1; q++)
{
float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
float32x4_t _k00_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1), 16));
float32x4_t _k01_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+4), 16));
float32x4_t _k02_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+8), 16));
float32x4_t _k10_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+12), 16));
float32x4_t _k11_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+16), 16));
float32x4_t _k12_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+20), 16));
float32x4_t _k20_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+24), 16));
float32x4_t _k21_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+28), 16));
float32x4_t _k22_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
asm volatile(
// r0
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v0.4h, v1.4h}, [%1], #16 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%0], #64 \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
// "prfm pldl1keep, [%0, #512] \n"
"ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%0] \n"// sum1
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %8.4s, v0.s[0] \n"
"fmla v7.4s, %8.4s, v0.s[2] \n"
"fmla v8.4s, %8.4s, v1.s[0] \n"
"fmla v9.4s, %8.4s, v1.s[2] \n"
"fmla v10.4s, %17.4s, v0.s[0] \n"
"fmla v11.4s, %17.4s, v0.s[2] \n"
"fmla v12.4s, %17.4s, v1.s[0] \n"
"fmla v13.4s, %17.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%1] \n"
"fmla v6.4s, %9.4s, v0.s[1] \n"
"fmla v7.4s, %9.4s, v0.s[3] \n"
"fmla v8.4s, %9.4s, v1.s[1] \n"
"fmla v9.4s, %9.4s, v1.s[3] \n"
"fmla v10.4s, %18.4s, v0.s[1] \n"
"fmla v11.4s, %18.4s, v0.s[3] \n"
"fmla v12.4s, %18.4s, v1.s[1] \n"
"fmla v13.4s, %18.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
// r1
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v2.4h, v3.4h}, [%2], #16 \n"
"fmla v6.4s, %10.4s, v0.s[2] \n"
"fmla v7.4s, %10.4s, v1.s[0] \n"
"fmla v8.4s, %10.4s, v1.s[2] \n"
"fmla v9.4s, %10.4s, v4.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v10.4s, %19.4s, v0.s[2] \n"
"fmla v11.4s, %19.4s, v1.s[0] \n"
"fmla v12.4s, %19.4s, v1.s[2] \n"
"fmla v13.4s, %19.4s, v4.s[0] \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v6.4s, %11.4s, v2.s[0] \n"
"fmla v7.4s, %11.4s, v2.s[2] \n"
"fmla v8.4s, %11.4s, v3.s[0] \n"
"fmla v9.4s, %11.4s, v3.s[2] \n"
"fmla v10.4s, %20.4s, v2.s[0] \n"
"fmla v11.4s, %20.4s, v2.s[2] \n"
"fmla v12.4s, %20.4s, v3.s[0] \n"
"fmla v13.4s, %20.4s, v3.s[2] \n"
"ld1 {v5.h}[0], [%2] \n"
"fmla v6.4s, %12.4s, v2.s[1] \n"
"fmla v7.4s, %12.4s, v2.s[3] \n"
"fmla v8.4s, %12.4s, v3.s[1] \n"
"fmla v9.4s, %12.4s, v3.s[3] \n"
"shll v5.4s, v5.4h, #16 \n"
"fmla v10.4s, %21.4s, v2.s[1] \n"
"fmla v11.4s, %21.4s, v2.s[3] \n"
"fmla v12.4s, %21.4s, v3.s[1] \n"
"fmla v13.4s, %21.4s, v3.s[3] \n"
// r2
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4h, v1.4h}, [%3], #16 \n"
"fmla v6.4s, %13.4s, v2.s[2] \n"
"fmla v7.4s, %13.4s, v3.s[0] \n"
"fmla v8.4s, %13.4s, v3.s[2] \n"
"fmla v9.4s, %13.4s, v5.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %22.4s, v2.s[2] \n"
"fmla v11.4s, %22.4s, v3.s[0] \n"
"fmla v12.4s, %22.4s, v3.s[2] \n"
"fmla v13.4s, %22.4s, v5.s[0] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %14.4s, v0.s[0] \n"
"fmla v7.4s, %14.4s, v0.s[2] \n"
"fmla v8.4s, %14.4s, v1.s[0] \n"
"fmla v9.4s, %14.4s, v1.s[2] \n"
"fmla v10.4s, %23.4s, v0.s[0] \n"
"fmla v11.4s, %23.4s, v0.s[2] \n"
"fmla v12.4s, %23.4s, v1.s[0] \n"
"fmla v13.4s, %23.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%3] \n"
"fmla v6.4s, %15.4s, v0.s[1] \n"
"fmla v7.4s, %15.4s, v0.s[3] \n"
"fmla v8.4s, %15.4s, v1.s[1] \n"
"fmla v9.4s, %15.4s, v1.s[3] \n"
"fmla v10.4s, %24.4s, v0.s[1] \n"
"fmla v11.4s, %24.4s, v0.s[3] \n"
"fmla v12.4s, %24.4s, v1.s[1] \n"
"fmla v13.4s, %24.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v6.4s, %16.4s, v0.s[2] \n"
"fmla v7.4s, %16.4s, v1.s[0] \n"
"fmla v8.4s, %16.4s, v1.s[2] \n"
"fmla v9.4s, %16.4s, v4.s[0] \n"
"sub %0, %0, #64 \n"
"fmla v10.4s, %25.4s, v0.s[2] \n"
"fmla v11.4s, %25.4s, v1.s[0] \n"
"fmla v12.4s, %25.4s, v1.s[2] \n"
"fmla v13.4s, %25.4s, v4.s[0] \n"
"st1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%0], #64 \n"
"st1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00_0), // %8
"w"(_k01_0), // %9
"w"(_k02_0), // %10
"w"(_k10_0), // %11
"w"(_k11_0), // %12
"w"(_k12_0), // %13
"w"(_k20_0), // %14
"w"(_k21_0), // %15
"w"(_k22_0), // %16
"w"(_k00_1), // %17
"w"(_k01_1), // %18
"w"(_k02_1), // %19
"w"(_k10_1), // %20
"w"(_k11_1), // %21
"w"(_k12_1), // %22
"w"(_k20_1), // %23
"w"(_k21_1), // %24
"w"(_k22_1) // %25
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"
);
}
for (; j+1<outw; j+=2)
{
asm volatile(
// r0
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1], #8 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%0] \n"// sum0 sum1
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %8.4s, v0.s[0] \n"
"fmla v11.4s, %8.4s, v0.s[2] \n"
"fmla v12.4s, %17.4s, v0.s[0] \n"
"fmla v13.4s, %17.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%1] \n"
"fmla v10.4s, %9.4s, v0.s[1] \n"
"fmla v11.4s, %9.4s, v0.s[3] \n"
"fmla v12.4s, %18.4s, v0.s[1] \n"
"fmla v13.4s, %18.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
// r1
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v2.4h}, [%2], #8 \n"
"fmla v10.4s, %10.4s, v0.s[2] \n"
"fmla v11.4s, %10.4s, v1.s[0] \n"
"fmla v12.4s, %19.4s, v0.s[2] \n"
"fmla v13.4s, %19.4s, v1.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v10.4s, %11.4s, v2.s[0] \n"
"fmla v11.4s, %11.4s, v2.s[2] \n"
"fmla v12.4s, %20.4s, v2.s[0] \n"
"fmla v13.4s, %20.4s, v2.s[2] \n"
"ld1 {v3.h}[0], [%2] \n"
"fmla v10.4s, %12.4s, v2.s[1] \n"
"fmla v11.4s, %12.4s, v2.s[3] \n"
"fmla v12.4s, %21.4s, v2.s[1] \n"
"fmla v13.4s, %21.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
// r2
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"fmla v10.4s, %13.4s, v2.s[2] \n"
"fmla v11.4s, %13.4s, v3.s[0] \n"
"fmla v12.4s, %22.4s, v2.s[2] \n"
"fmla v13.4s, %22.4s, v3.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %14.4s, v0.s[0] \n"
"fmla v11.4s, %14.4s, v0.s[2] \n"
"fmla v12.4s, %23.4s, v0.s[0] \n"
"fmla v13.4s, %23.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%3] \n"
"fmla v10.4s, %15.4s, v0.s[1] \n"
"fmla v11.4s, %15.4s, v0.s[3] \n"
"fmla v12.4s, %24.4s, v0.s[1] \n"
"fmla v13.4s, %24.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v10.4s, %16.4s, v0.s[2] \n"
"fmla v11.4s, %16.4s, v1.s[0] \n"
"fmla v12.4s, %25.4s, v0.s[2] \n"
"fmla v13.4s, %25.4s, v1.s[0] \n"
"st1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00_0), // %8
"w"(_k01_0), // %9
"w"(_k02_0), // %10
"w"(_k10_0), // %11
"w"(_k11_0), // %12
"w"(_k12_0), // %13
"w"(_k20_0), // %14
"w"(_k21_0), // %15
"w"(_k22_0), // %16
"w"(_k00_1), // %17
"w"(_k01_1), // %18
"w"(_k02_1), // %19
"w"(_k10_1), // %20
"w"(_k11_1), // %21
"w"(_k12_1), // %22
"w"(_k20_1), // %23
"w"(_k21_1), // %24
"w"(_k22_1) // %25
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"
);
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _sum1 = vld1q_f32(outptr0+4);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
_sum0 = vfmaq_laneq_f32(_sum0, _k00_0, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01_0, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02_0, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10_0, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11_0, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12_0, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20_0, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21_0, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22_0, _r2, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k00_1, _r0, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k01_1, _r0, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k02_1, _r0, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k10_1, _r1, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k11_1, _r1, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k12_1, _r1, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k20_1, _r2, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k21_1, _r2, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k22_1, _r2, 2);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr0+4, _sum1);
r0 += 2;
r1 += 2;
r2 += 2;
outptr0 += 8;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
k0 += 9*4;
k1 += 9*4;
}
for (; q<inch; q++)
{
unsigned short* outptr0_bf16 = top_blob.channel(p);
unsigned short* outptr1_bf16 = top_blob.channel(p+1);
const float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22_0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
float32x4_t _k00_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1), 16));
float32x4_t _k01_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+4), 16));
float32x4_t _k02_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+8), 16));
float32x4_t _k10_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+12), 16));
float32x4_t _k11_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+16), 16));
float32x4_t _k12_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+20), 16));
float32x4_t _k20_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+24), 16));
float32x4_t _k21_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+28), 16));
float32x4_t _k22_1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k1+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
asm volatile(
// r0
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4h, v1.4h}, [%3], #16 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%2], #64 \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%2], #64 \n"// sum1
"fmla v6.4s, %12.4s, v0.s[0] \n"
"fmla v7.4s, %12.4s, v0.s[2] \n"
"fmla v8.4s, %12.4s, v1.s[0] \n"
"fmla v9.4s, %12.4s, v1.s[2] \n"
"fmla v10.4s, %21.4s, v0.s[0] \n"
"fmla v11.4s, %21.4s, v0.s[2] \n"
"fmla v12.4s, %21.4s, v1.s[0] \n"
"fmla v13.4s, %21.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%3] \n"
"fmla v6.4s, %13.4s, v0.s[1] \n"
"fmla v7.4s, %13.4s, v0.s[3] \n"
"fmla v8.4s, %13.4s, v1.s[1] \n"
"fmla v9.4s, %13.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v10.4s, %22.4s, v0.s[1] \n"
"fmla v11.4s, %22.4s, v0.s[3] \n"
"fmla v12.4s, %22.4s, v1.s[1] \n"
"fmla v13.4s, %22.4s, v1.s[3] \n"
// r1
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v2.4h, v3.4h}, [%4], #16 \n"
"fmla v6.4s, %14.4s, v0.s[2] \n"
"fmla v7.4s, %14.4s, v1.s[0] \n"
"fmla v8.4s, %14.4s, v1.s[2] \n"
"fmla v9.4s, %14.4s, v4.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v10.4s, %23.4s, v0.s[2] \n"
"fmla v11.4s, %23.4s, v1.s[0] \n"
"fmla v12.4s, %23.4s, v1.s[2] \n"
"fmla v13.4s, %23.4s, v4.s[0] \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v6.4s, %15.4s, v2.s[0] \n"
"fmla v7.4s, %15.4s, v2.s[2] \n"
"fmla v8.4s, %15.4s, v3.s[0] \n"
"fmla v9.4s, %15.4s, v3.s[2] \n"
"fmla v10.4s, %24.4s, v2.s[0] \n"
"fmla v11.4s, %24.4s, v2.s[2] \n"
"fmla v12.4s, %24.4s, v3.s[0] \n"
"fmla v13.4s, %24.4s, v3.s[2] \n"
"ld1 {v5.h}[0], [%4] \n"
"fmla v6.4s, %16.4s, v2.s[1] \n"
"fmla v7.4s, %16.4s, v2.s[3] \n"
"fmla v8.4s, %16.4s, v3.s[1] \n"
"fmla v9.4s, %16.4s, v3.s[3] \n"
"shll v5.4s, v5.4h, #16 \n"
"fmla v10.4s, %25.4s, v2.s[1] \n"
"fmla v11.4s, %25.4s, v2.s[3] \n"
"fmla v12.4s, %25.4s, v3.s[1] \n"
"fmla v13.4s, %25.4s, v3.s[3] \n"
// r2
"prfm pldl1keep, [%5, #128] \n"
"ld1 {v0.4h, v1.4h}, [%5], #16 \n"
"fmla v6.4s, %17.4s, v2.s[2] \n"
"fmla v7.4s, %17.4s, v3.s[0] \n"
"fmla v8.4s, %17.4s, v3.s[2] \n"
"fmla v9.4s, %17.4s, v5.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %26.4s, v2.s[2] \n"
"fmla v11.4s, %26.4s, v3.s[0] \n"
"fmla v12.4s, %26.4s, v3.s[2] \n"
"fmla v13.4s, %26.4s, v5.s[0] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %18.4s, v0.s[0] \n"
"fmla v7.4s, %18.4s, v0.s[2] \n"
"fmla v8.4s, %18.4s, v1.s[0] \n"
"fmla v9.4s, %18.4s, v1.s[2] \n"
"fmla v10.4s, %27.4s, v0.s[0] \n"
"fmla v11.4s, %27.4s, v0.s[2] \n"
"fmla v12.4s, %27.4s, v1.s[0] \n"
"fmla v13.4s, %27.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%5] \n"
"fmla v6.4s, %19.4s, v0.s[1] \n"
"fmla v7.4s, %19.4s, v0.s[3] \n"
"fmla v8.4s, %19.4s, v1.s[1] \n"
"fmla v9.4s, %19.4s, v1.s[3] \n"
"fmla v10.4s, %28.4s, v0.s[1] \n"
"fmla v11.4s, %28.4s, v0.s[3] \n"
"fmla v12.4s, %28.4s, v1.s[1] \n"
"fmla v13.4s, %28.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v6.4s, %20.4s, v0.s[2] \n"
"fmla v7.4s, %20.4s, v1.s[0] \n"
"fmla v8.4s, %20.4s, v1.s[2] \n"
"fmla v9.4s, %20.4s, v4.s[0] \n"
"fmla v10.4s, %29.4s, v0.s[2] \n"
"fmla v11.4s, %29.4s, v1.s[0] \n"
"fmla v12.4s, %29.4s, v1.s[2] \n"
"fmla v13.4s, %29.4s, v4.s[0] \n"
"shrn v6.4h, v6.4s, #16 \n"
"shrn v7.4h, v7.4s, #16 \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"st1 {v6.4h, v7.4h, v8.4h, v9.4h}, [%0], #32 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"st1 {v10.4h, v11.4h, v12.4h, v13.4h}, [%1], #32 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr1_bf16), // %1
"=r"(outptr0), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(outptr0_bf16),
"1"(outptr1_bf16),
"2"(outptr0),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00_0), // %12
"w"(_k01_0), // %13
"w"(_k02_0), // %14
"w"(_k10_0), // %15
"w"(_k11_0), // %16
"w"(_k12_0), // %17
"w"(_k20_0), // %18
"w"(_k21_0), // %19
"w"(_k22_0), // %20
"w"(_k00_1), // %21
"w"(_k01_1), // %22
"w"(_k02_1), // %23
"w"(_k10_1), // %24
"w"(_k11_1), // %25
"w"(_k12_1), // %26
"w"(_k20_1), // %27
"w"(_k21_1), // %28
"w"(_k22_1) // %29
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"
);
}
for (; j+1<outw; j+=2)
{
asm volatile(
// r0
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"prfm pldl1keep, [%2, #512] \n"
"ld1 {v10.4s, v11.4s, v12.4s, v13.4s}, [%2], #64 \n"// sum0 sum1
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %12.4s, v0.s[0] \n"
"fmla v11.4s, %12.4s, v0.s[2] \n"
"fmla v12.4s, %21.4s, v0.s[0] \n"
"fmla v13.4s, %21.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%3] \n"
"fmla v10.4s, %13.4s, v0.s[1] \n"
"fmla v11.4s, %13.4s, v0.s[3] \n"
"fmla v12.4s, %22.4s, v0.s[1] \n"
"fmla v13.4s, %22.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
// r1
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v2.4h}, [%4], #8 \n"
"fmla v10.4s, %14.4s, v0.s[2] \n"
"fmla v11.4s, %14.4s, v1.s[0] \n"
"fmla v12.4s, %23.4s, v0.s[2] \n"
"fmla v13.4s, %23.4s, v1.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v10.4s, %15.4s, v2.s[0] \n"
"fmla v11.4s, %15.4s, v2.s[2] \n"
"fmla v12.4s, %24.4s, v2.s[0] \n"
"fmla v13.4s, %24.4s, v2.s[2] \n"
"ld1 {v3.h}[0], [%4] \n"
"fmla v10.4s, %16.4s, v2.s[1] \n"
"fmla v11.4s, %16.4s, v2.s[3] \n"
"fmla v12.4s, %25.4s, v2.s[1] \n"
"fmla v13.4s, %25.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
// r2
"prfm pldl1keep, [%5, #64] \n"
"ld1 {v0.4h}, [%5], #8 \n"
"fmla v10.4s, %17.4s, v2.s[2] \n"
"fmla v11.4s, %17.4s, v3.s[0] \n"
"fmla v12.4s, %26.4s, v2.s[2] \n"
"fmla v13.4s, %26.4s, v3.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v10.4s, %18.4s, v0.s[0] \n"
"fmla v11.4s, %18.4s, v0.s[2] \n"
"fmla v12.4s, %27.4s, v0.s[0] \n"
"fmla v13.4s, %27.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%5] \n"
"fmla v10.4s, %19.4s, v0.s[1] \n"
"fmla v11.4s, %19.4s, v0.s[3] \n"
"fmla v12.4s, %28.4s, v0.s[1] \n"
"fmla v13.4s, %28.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v10.4s, %20.4s, v0.s[2] \n"
"fmla v11.4s, %20.4s, v1.s[0] \n"
"fmla v12.4s, %29.4s, v0.s[2] \n"
"fmla v13.4s, %29.4s, v1.s[0] \n"
"shrn v10.4h, v10.4s, #16 \n"
"shrn v11.4h, v11.4s, #16 \n"
"shrn v12.4h, v12.4s, #16 \n"
"shrn v13.4h, v13.4s, #16 \n"
"st1 {v10.4h, v11.4h}, [%0], #16 \n"
"st1 {v12.4h, v13.4h}, [%1], #16 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr1_bf16), // %1
"=r"(outptr0), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(outptr0_bf16),
"1"(outptr1_bf16),
"2"(outptr0),
"3"(r0),
"4"(r1),
"5"(r2),
"w"(_k00_0), // %12
"w"(_k01_0), // %13
"w"(_k02_0), // %14
"w"(_k10_0), // %15
"w"(_k11_0), // %16
"w"(_k12_0), // %17
"w"(_k20_0), // %18
"w"(_k21_0), // %19
"w"(_k22_0), // %20
"w"(_k00_1), // %21
"w"(_k01_1), // %22
"w"(_k02_1), // %23
"w"(_k10_1), // %24
"w"(_k11_1), // %25
"w"(_k12_1), // %26
"w"(_k20_1), // %27
"w"(_k21_1), // %28
"w"(_k22_1) // %29
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13"
);
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _sum1 = vld1q_f32(outptr0+4);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
_sum0 = vfmaq_laneq_f32(_sum0, _k00_0, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01_0, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02_0, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10_0, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11_0, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12_0, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20_0, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21_0, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22_0, _r2, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k00_1, _r0, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k01_1, _r0, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k02_1, _r0, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k10_1, _r1, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k11_1, _r1, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k12_1, _r1, 2);
_sum1 = vfmaq_laneq_f32(_sum1, _k20_1, _r2, 0);
_sum1 = vfmaq_laneq_f32(_sum1, _k21_1, _r2, 1);
_sum1 = vfmaq_laneq_f32(_sum1, _k22_1, _r2, 2);
vst1_u16(outptr0_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum0), 16));
vst1_u16(outptr1_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum1), 16));
r0 += 2;
r1 += 2;
r2 += 2;
outptr0 += 8;
outptr0_bf16 += 4;
outptr1_bf16 += 4;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
k0 += 9*4;
k1 += 9*4;
}
}
#endif // __ARM_NEON && __aarch64__
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob_fp32.channel(get_omp_thread_num());
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f);
out0.fill(_bias0);
const unsigned short* k0 = kernel.channel(p);
int q=0;
for (; q<inch-1; q++)
{
float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
#if __aarch64__
asm volatile(
// r0
"prfm pldl1keep, [%1, #128] \n"
"ld1 {v0.4h, v1.4h}, [%1], #16 \n"
"prfm pldl1keep, [%0, #512] \n"
"ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%0] \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %8.4s, v0.s[0] \n"
"fmla v7.4s, %8.4s, v0.s[2] \n"
"fmla v8.4s, %8.4s, v1.s[0] \n"
"fmla v9.4s, %8.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%1] \n"
"fmla v6.4s, %9.4s, v0.s[1] \n"
"fmla v7.4s, %9.4s, v0.s[3] \n"
"fmla v8.4s, %9.4s, v1.s[1] \n"
"fmla v9.4s, %9.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
// r1
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v2.4h, v3.4h}, [%2], #16 \n"
"fmla v6.4s, %10.4s, v0.s[2] \n"
"fmla v7.4s, %10.4s, v1.s[0] \n"
"fmla v8.4s, %10.4s, v1.s[2] \n"
"fmla v9.4s, %10.4s, v4.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v6.4s, %11.4s, v2.s[0] \n"
"fmla v7.4s, %11.4s, v2.s[2] \n"
"fmla v8.4s, %11.4s, v3.s[0] \n"
"fmla v9.4s, %11.4s, v3.s[2] \n"
"ld1 {v5.h}[0], [%2] \n"
"fmla v6.4s, %12.4s, v2.s[1] \n"
"fmla v7.4s, %12.4s, v2.s[3] \n"
"fmla v8.4s, %12.4s, v3.s[1] \n"
"fmla v9.4s, %12.4s, v3.s[3] \n"
"shll v5.4s, v5.4h, #16 \n"
// r2
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v0.4h, v1.4h}, [%3], #16 \n"
"fmla v6.4s, %13.4s, v2.s[2] \n"
"fmla v7.4s, %13.4s, v3.s[0] \n"
"fmla v8.4s, %13.4s, v3.s[2] \n"
"fmla v9.4s, %13.4s, v5.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %14.4s, v0.s[0] \n"
"fmla v7.4s, %14.4s, v0.s[2] \n"
"fmla v8.4s, %14.4s, v1.s[0] \n"
"fmla v9.4s, %14.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%3] \n"
"fmla v6.4s, %15.4s, v0.s[1] \n"
"fmla v7.4s, %15.4s, v0.s[3] \n"
"fmla v8.4s, %15.4s, v1.s[1] \n"
"fmla v9.4s, %15.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v6.4s, %16.4s, v0.s[2] \n"
"fmla v7.4s, %16.4s, v1.s[0] \n"
"fmla v8.4s, %16.4s, v1.s[2] \n"
"fmla v9.4s, %16.4s, v4.s[0] \n"
"st1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%0], #64 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else // __aarch64__
asm volatile(
// r0
"pld [%1, #128] \n"
"vld1.u16 {d12-d13}, [%1]! \n"
"pld [%0, #512] \n"
"vldm %0, {d0-d7} \n"// sum0
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%1] \n"
"vmla.f32 q0, %q8, d8[0] \n"
"vmla.f32 q1, %q8, d9[0] \n"
"vmla.f32 q2, %q8, d10[0] \n"
"vmla.f32 q3, %q8, d11[0] \n"
"vmla.f32 q0, %q9, d8[1] \n"
"vmla.f32 q1, %q9, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q9, d10[1] \n"
"vmla.f32 q3, %q9, d11[1] \n"
// r1
"pld [%2, #128] \n"
"vld1.u16 {d12-d13}, [%2]! \n"
"vmla.f32 q0, %q10, d9[0] \n"
"vmla.f32 q1, %q10, d10[0] \n"
"vmla.f32 q2, %q10, d11[0] \n"
"vmla.f32 q3, %q10, d8[0] \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%2] \n"
"vmla.f32 q0, %q11, d8[0] \n"
"vmla.f32 q1, %q11, d9[0] \n"
"vmla.f32 q2, %q11, d10[0] \n"
"vmla.f32 q3, %q11, d11[0] \n"
"vmla.f32 q0, %q12, d8[1] \n"
"vmla.f32 q1, %q12, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q12, d10[1] \n"
"vmla.f32 q3, %q12, d11[1] \n"
// r2
"pld [%3, #128] \n"
"vld1.u16 {d12-d13}, [%3]! \n"
"vmla.f32 q0, %q13, d9[0] \n"
"vmla.f32 q1, %q13, d10[0] \n"
"vmla.f32 q2, %q13, d11[0] \n"
"vmla.f32 q3, %q13, d8[0] \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%3] \n"
"vmla.f32 q0, %q14, d8[0] \n"
"vmla.f32 q1, %q14, d9[0] \n"
"vmla.f32 q2, %q14, d10[0] \n"
"vmla.f32 q3, %q14, d11[0] \n"
"vmla.f32 q0, %q15, d8[1] \n"
"vmla.f32 q1, %q15, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q15, d10[1] \n"
"vmla.f32 q3, %q15, d11[1] \n"
"vmla.f32 q0, %q16, d9[0] \n"
"vmla.f32 q1, %q16, d10[0] \n"
"vmla.f32 q2, %q16, d11[0] \n"
"vmla.f32 q3, %q16, d8[0] \n"
"vstm %0!, {d0-d7} \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j+1<outw; j+=2)
{
#if __aarch64__
asm volatile(
// r0
"prfm pldl1keep, [%1, #64] \n"
"ld1 {v0.4h}, [%1], #8 \n"
"prfm pldl1keep, [%0, #256] \n"
"ld1 {v8.4s, v9.4s}, [%0] \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
"fmul v6.4s, %8.4s, v0.s[0] \n"
"fmul v7.4s, %8.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%1] \n"
"fmla v8.4s, %9.4s, v0.s[1] \n"
"fmla v9.4s, %9.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
// r1
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v2.4h}, [%2], #8 \n"
"fmla v6.4s, %10.4s, v0.s[2] \n"
"fmla v7.4s, %10.4s, v1.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v8.4s, %11.4s, v2.s[0] \n"
"fmla v9.4s, %11.4s, v2.s[2] \n"
"ld1 {v3.h}[0], [%2] \n"
"fmla v6.4s, %12.4s, v2.s[1] \n"
"fmla v7.4s, %12.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
// r2
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v0.4h}, [%3], #8 \n"
"fmla v8.4s, %13.4s, v2.s[2] \n"
"fmla v9.4s, %13.4s, v3.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v6.4s, %14.4s, v0.s[0] \n"
"fmla v7.4s, %14.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%3] \n"
"fmla v8.4s, %15.4s, v0.s[1] \n"
"fmla v9.4s, %15.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %16.4s, v0.s[2] \n"
"fmla v7.4s, %16.4s, v1.s[0] \n"
"fadd v8.4s, v8.4s, v6.4s \n"
"fadd v9.4s, v9.4s, v7.4s \n"
"st1 {v8.4s, v9.4s}, [%0], #32 \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else // __aarch64__
asm volatile(
// r0
"pld [%1, #64] \n"
"vld1.u16 {d9}, [%1]! \n"
"pld [%0, #256] \n"
"vld1.f32 {d4-d7}, [%0] \n"// sum0
"vshll.u16 q4, d9, #16 \n"
"vmul.f32 q0, %q8, d8[0] \n"
"vmul.f32 q1, %q8, d9[0] \n"
"vld1.u16 {d11[]}, [%1] \n"
"vmla.f32 q2, %q9, d8[1] \n"
"vmla.f32 q3, %q9, d9[1] \n"
"vshll.u16 q5, d11, #16 \n"
// r1
"pld [%2, #64] \n"
"vld1.u16 {d13}, [%2]! \n"
"vmla.f32 q0, %q10, d9[0] \n"
"vmla.f32 q1, %q10, d10[0] \n"
"vshll.u16 q6, d13, #16 \n"
"vmla.f32 q2, %q11, d12[0] \n"
"vmla.f32 q3, %q11, d13[0] \n"
"vld1.u16 {d9[]}, [%2] \n"
"vmla.f32 q0, %q12, d12[1] \n"
"vmla.f32 q1, %q12, d13[1] \n"
"vshll.u16 q4, d9, #16 \n"
// r2
"pld [%3, #64] \n"
"vld1.u16 {d11}, [%3]! \n"
"vmla.f32 q2, %q13, d13[0] \n"
"vmla.f32 q3, %q13, d8[0] \n"
"vshll.u16 q5, d11, #16 \n"
"vmla.f32 q0, %q14, d10[0] \n"
"vmla.f32 q1, %q14, d11[0] \n"
"vld1.u16 {d13[]}, [%3] \n"
"vmla.f32 q2, %q15, d10[1] \n"
"vmla.f32 q3, %q15, d11[1] \n"
"vshll.u16 q6, d13, #16 \n"
"vmla.f32 q0, %q16, d11[0] \n"
"vmla.f32 q1, %q16, d12[0] \n"
"vadd.f32 q2, q2, q0 \n"
"vadd.f32 q3, q3, q1 \n"
"vst1.f32 {d4-d7}, [%0]! \n"
: "=r"(outptr0), // %0
"=r"(r0), // %1
"=r"(r1), // %2
"=r"(r2) // %3
: "0"(outptr0),
"1"(r0),
"2"(r1),
"3"(r2),
"w"(_k00), // %8
"w"(_k01), // %9
"w"(_k02), // %10
"w"(_k10), // %11
"w"(_k11), // %12
"w"(_k12), // %13
"w"(_k20), // %14
"w"(_k21), // %15
"w"(_k22) // %16
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
#if __aarch64__
_sum0 = vfmaq_laneq_f32(_sum0, _k00, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22, _r2, 2);
#else
_sum0 = vmlaq_lane_f32(_sum0, _k00, vget_low_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k01, vget_low_f32(_r0), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k02, vget_high_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k10, vget_low_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k11, vget_low_f32(_r1), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k12, vget_high_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k20, vget_low_f32(_r2), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k21, vget_low_f32(_r2), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k22, vget_high_f32(_r2), 0);
#endif
vst1q_f32(outptr0, _sum0);
r0 += 2;
r1 += 2;
r2 += 2;
outptr0 += 4;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
k0 += 9*4;
}
for (; q<inch; q++)
{
unsigned short* outptr0_bf16 = top_blob.channel(p);
const float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const unsigned short* r0 = img0.row<const unsigned short>(0);
const unsigned short* r1 = img0.row<const unsigned short>(1);
const unsigned short* r2 = img0.row<const unsigned short>(2);
float32x4_t _k00 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0), 16));
float32x4_t _k01 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+4), 16));
float32x4_t _k02 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+8), 16));
float32x4_t _k10 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+12), 16));
float32x4_t _k11 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+16), 16));
float32x4_t _k12 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+20), 16));
float32x4_t _k20 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+24), 16));
float32x4_t _k21 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+28), 16));
float32x4_t _k22 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(k0+32), 16));
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j+3<outw; j+=4)
{
#if __aarch64__
asm volatile(
// r0
"prfm pldl1keep, [%2, #128] \n"
"ld1 {v0.4h, v1.4h}, [%2], #16 \n"
"prfm pldl1keep, [%1, #512] \n"
"ld1 {v6.4s, v7.4s, v8.4s, v9.4s}, [%1], #64 \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %10.4s, v0.s[0] \n"
"fmla v7.4s, %10.4s, v0.s[2] \n"
"fmla v8.4s, %10.4s, v1.s[0] \n"
"fmla v9.4s, %10.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%2] \n"
"fmla v6.4s, %11.4s, v0.s[1] \n"
"fmla v7.4s, %11.4s, v0.s[3] \n"
"fmla v8.4s, %11.4s, v1.s[1] \n"
"fmla v9.4s, %11.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
// r1
"prfm pldl1keep, [%3, #128] \n"
"ld1 {v2.4h, v3.4h}, [%3], #16 \n"
"fmla v6.4s, %12.4s, v0.s[2] \n"
"fmla v7.4s, %12.4s, v1.s[0] \n"
"fmla v8.4s, %12.4s, v1.s[2] \n"
"fmla v9.4s, %12.4s, v4.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"shll v3.4s, v3.4h, #16 \n"
"fmla v6.4s, %13.4s, v2.s[0] \n"
"fmla v7.4s, %13.4s, v2.s[2] \n"
"fmla v8.4s, %13.4s, v3.s[0] \n"
"fmla v9.4s, %13.4s, v3.s[2] \n"
"ld1 {v5.h}[0], [%3] \n"
"fmla v6.4s, %14.4s, v2.s[1] \n"
"fmla v7.4s, %14.4s, v2.s[3] \n"
"fmla v8.4s, %14.4s, v3.s[1] \n"
"fmla v9.4s, %14.4s, v3.s[3] \n"
"shll v5.4s, v5.4h, #16 \n"
// r2
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v0.4h, v1.4h}, [%4], #16 \n"
"fmla v6.4s, %15.4s, v2.s[2] \n"
"fmla v7.4s, %15.4s, v3.s[0] \n"
"fmla v8.4s, %15.4s, v3.s[2] \n"
"fmla v9.4s, %15.4s, v5.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %16.4s, v0.s[0] \n"
"fmla v7.4s, %16.4s, v0.s[2] \n"
"fmla v8.4s, %16.4s, v1.s[0] \n"
"fmla v9.4s, %16.4s, v1.s[2] \n"
"ld1 {v4.h}[0], [%4] \n"
"fmla v6.4s, %17.4s, v0.s[1] \n"
"fmla v7.4s, %17.4s, v0.s[3] \n"
"fmla v8.4s, %17.4s, v1.s[1] \n"
"fmla v9.4s, %17.4s, v1.s[3] \n"
"shll v4.4s, v4.4h, #16 \n"
"fmla v6.4s, %18.4s, v0.s[2] \n"
"fmla v7.4s, %18.4s, v1.s[0] \n"
"fmla v8.4s, %18.4s, v1.s[2] \n"
"fmla v9.4s, %18.4s, v4.s[0] \n"
"shrn v6.4h, v6.4s, #16 \n"
"shrn v7.4h, v7.4s, #16 \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"st1 {v6.4h, v7.4h, v8.4h, v9.4h}, [%0], #32 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else // __aarch64__
asm volatile(
// r0
"pld [%2, #128] \n"
"vld1.u16 {d12-d13}, [%2]! \n"
"pld [%1, #512] \n"
"vldm %1!, {d0-d7} \n"// sum0
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%2] \n"
"vmla.f32 q0, %q10, d8[0] \n"
"vmla.f32 q1, %q10, d9[0] \n"
"vmla.f32 q2, %q10, d10[0] \n"
"vmla.f32 q3, %q10, d11[0] \n"
"vmla.f32 q0, %q11, d8[1] \n"
"vmla.f32 q1, %q11, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q11, d10[1] \n"
"vmla.f32 q3, %q11, d11[1] \n"
// r1
"pld [%3, #128] \n"
"vld1.u16 {d12-d13}, [%3]! \n"
"vmla.f32 q0, %q12, d9[0] \n"
"vmla.f32 q1, %q12, d10[0] \n"
"vmla.f32 q2, %q12, d11[0] \n"
"vmla.f32 q3, %q12, d8[0] \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%3] \n"
"vmla.f32 q0, %q13, d8[0] \n"
"vmla.f32 q1, %q13, d9[0] \n"
"vmla.f32 q2, %q13, d10[0] \n"
"vmla.f32 q3, %q13, d11[0] \n"
"vmla.f32 q0, %q14, d8[1] \n"
"vmla.f32 q1, %q14, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q14, d10[1] \n"
"vmla.f32 q3, %q14, d11[1] \n"
// r2
"pld [%4, #128] \n"
"vld1.u16 {d12-d13}, [%4]! \n"
"vmla.f32 q0, %q15, d9[0] \n"
"vmla.f32 q1, %q15, d10[0] \n"
"vmla.f32 q2, %q15, d11[0] \n"
"vmla.f32 q3, %q15, d8[0] \n"
"vshll.u16 q4, d12, #16 \n"
"vshll.u16 q5, d13, #16 \n"
"vld1.u16 {d12[0]}, [%4] \n"
"vmla.f32 q0, %q16, d8[0] \n"
"vmla.f32 q1, %q16, d9[0] \n"
"vmla.f32 q2, %q16, d10[0] \n"
"vmla.f32 q3, %q16, d11[0] \n"
"vmla.f32 q0, %q17, d8[1] \n"
"vmla.f32 q1, %q17, d9[1] \n"
"vshl.u32 d8, d12, #16 \n"
"vmla.f32 q2, %q17, d10[1] \n"
"vmla.f32 q3, %q17, d11[1] \n"
"vmla.f32 q0, %q18, d9[0] \n"
"vmla.f32 q1, %q18, d10[0] \n"
"vmla.f32 q2, %q18, d11[0] \n"
"vmla.f32 q3, %q18, d8[0] \n"
"vshrn.u32 d0, q0, #16 \n"
"vshrn.u32 d1, q1, #16 \n"
"vshrn.u32 d2, q2, #16 \n"
"vshrn.u32 d3, q3, #16 \n"
"vst1.u16 {d0-d3}, [%0 :64]! \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j+1<outw; j+=2)
{
#if __aarch64__
asm volatile(
// r0
"prfm pldl1keep, [%2, #64] \n"
"ld1 {v0.4h}, [%2], #8 \n"
"prfm pldl1keep, [%1, #256] \n"
"ld1 {v8.4s, v9.4s}, [%1], #32 \n"// sum0
"shll v0.4s, v0.4h, #16 \n"
"fmul v6.4s, %10.4s, v0.s[0] \n"
"fmul v7.4s, %10.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%2] \n"
"fmla v8.4s, %11.4s, v0.s[1] \n"
"fmla v9.4s, %11.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
// r1
"prfm pldl1keep, [%3, #64] \n"
"ld1 {v2.4h}, [%3], #8 \n"
"fmla v6.4s, %12.4s, v0.s[2] \n"
"fmla v7.4s, %12.4s, v1.s[0] \n"
"shll v2.4s, v2.4h, #16 \n"
"fmla v8.4s, %13.4s, v2.s[0] \n"
"fmla v9.4s, %13.4s, v2.s[2] \n"
"ld1 {v3.h}[0], [%3] \n"
"fmla v6.4s, %14.4s, v2.s[1] \n"
"fmla v7.4s, %14.4s, v2.s[3] \n"
"shll v3.4s, v3.4h, #16 \n"
// r2
"prfm pldl1keep, [%4, #64] \n"
"ld1 {v0.4h}, [%4], #8 \n"
"fmla v8.4s, %15.4s, v2.s[2] \n"
"fmla v9.4s, %15.4s, v3.s[0] \n"
"shll v0.4s, v0.4h, #16 \n"
"fmla v6.4s, %16.4s, v0.s[0] \n"
"fmla v7.4s, %16.4s, v0.s[2] \n"
"ld1 {v1.h}[0], [%4] \n"
"fmla v8.4s, %17.4s, v0.s[1] \n"
"fmla v9.4s, %17.4s, v0.s[3] \n"
"shll v1.4s, v1.4h, #16 \n"
"fmla v6.4s, %18.4s, v0.s[2] \n"
"fmla v7.4s, %18.4s, v1.s[0] \n"
"fadd v8.4s, v8.4s, v6.4s \n"
"fadd v9.4s, v9.4s, v7.4s \n"
"shrn v8.4h, v8.4s, #16 \n"
"shrn v9.4h, v9.4s, #16 \n"
"st1 {v8.4h, v9.4h}, [%0], #16 \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9"
);
#else // __aarch64__
asm volatile(
// r0
"pld [%2, #64] \n"
"vld1.u16 {d9}, [%2]! \n"
"pld [%1, #256] \n"
"vld1.f32 {d4-d7}, [%1]! \n"// sum0
"vshll.u16 q4, d9, #16 \n"
"vmul.f32 q0, %q10, d8[0] \n"
"vmul.f32 q1, %q10, d9[0] \n"
"vld1.u16 {d11[]}, [%2] \n"
"vmla.f32 q2, %q11, d8[1] \n"
"vmla.f32 q3, %q11, d9[1] \n"
"vshll.u16 q5, d11, #16 \n"
// r1
"pld [%3, #64] \n"
"vld1.u16 {d13}, [%3]! \n"
"vmla.f32 q0, %q12, d9[0] \n"
"vmla.f32 q1, %q12, d10[0] \n"
"vshll.u16 q6, d13, #16 \n"
"vmla.f32 q2, %q13, d12[0] \n"
"vmla.f32 q3, %q13, d13[0] \n"
"vld1.u16 {d9[]}, [%3] \n"
"vmla.f32 q0, %q14, d12[1] \n"
"vmla.f32 q1, %q14, d13[1] \n"
"vshll.u16 q4, d9, #16 \n"
// r2
"pld [%4, #64] \n"
"vld1.u16 {d11}, [%4]! \n"
"vmla.f32 q2, %q15, d13[0] \n"
"vmla.f32 q3, %q15, d8[0] \n"
"vshll.u16 q5, d11, #16 \n"
"vmla.f32 q0, %q16, d10[0] \n"
"vmla.f32 q1, %q16, d11[0] \n"
"vld1.u16 {d13[]}, [%4] \n"
"vmla.f32 q2, %q17, d10[1] \n"
"vmla.f32 q3, %q17, d11[1] \n"
"vshll.u16 q6, d13, #16 \n"
"vmla.f32 q0, %q18, d11[0] \n"
"vmla.f32 q1, %q18, d12[0] \n"
"vadd.f32 q2, q2, q0 \n"
"vadd.f32 q3, q3, q1 \n"
"vshrn.u32 d2, q2, #16 \n"
"vshrn.u32 d3, q3, #16 \n"
"vst1.u16 {d2-d3}, [%0 :64]! \n"
: "=r"(outptr0_bf16), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(outptr0_bf16),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6"
);
#endif // __aarch64__
}
for (; j<outw; j++)
{
float32x4_t _sum0 = vld1q_f32(outptr0);
float32x4_t _r0 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r0), 16));
float32x4_t _r1 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r1), 16));
float32x4_t _r2 = vreinterpretq_f32_u32(vshll_n_u16(vld1_u16(r2), 16));
#if __aarch64__
_sum0 = vfmaq_laneq_f32(_sum0, _k00, _r0, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k01, _r0, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k02, _r0, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k10, _r1, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k11, _r1, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k12, _r1, 2);
_sum0 = vfmaq_laneq_f32(_sum0, _k20, _r2, 0);
_sum0 = vfmaq_laneq_f32(_sum0, _k21, _r2, 1);
_sum0 = vfmaq_laneq_f32(_sum0, _k22, _r2, 2);
#else
_sum0 = vmlaq_lane_f32(_sum0, _k00, vget_low_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k01, vget_low_f32(_r0), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k02, vget_high_f32(_r0), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k10, vget_low_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k11, vget_low_f32(_r1), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k12, vget_high_f32(_r1), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k20, vget_low_f32(_r2), 0);
_sum0 = vmlaq_lane_f32(_sum0, _k21, vget_low_f32(_r2), 1);
_sum0 = vmlaq_lane_f32(_sum0, _k22, vget_high_f32(_r2), 0);
#endif
vst1_u16(outptr0_bf16, vshrn_n_u32(vreinterpretq_u32_f32(_sum0), 16));
r0 += 2;
r1 += 2;
r2 += 2;
outptr0 += 4;
outptr0_bf16 += 4;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
k0 += 9*4;
}
}
}
|
ch_ompss.c |
#include "ch_common.h"
#include "../timing.h"
#include "../timing_override.h"
void cholesky_mpi(const int ts, const int nt, double * SPEC_RESTRICT A[nt][nt], double * SPEC_RESTRICT B, double * SPEC_RESTRICT C[nt], int *block_rank)
{
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
#pragma omp parallel
{
chameleon_thread_init();
}
// necessary to be aware of binary base addresses to calculate offset for target entry functions
chameleon_determine_base_addresses((void *)&cholesky_mpi);
#endif
#ifdef USE_TIMING
#pragma omp parallel
#pragma omp master
INIT_TIMING(omp_get_num_threads());
#endif
int send_cnt = 0;
char recv_flag = 0, *send_flags = malloc(sizeof(char) * np);
MPI_Request recv_req, *send_reqs = malloc(sizeof(MPI_Request) * np);
#ifdef TRACE
static int event_communication = -1;
char* event_name = "communication";
if(event_communication == -1) {
int ierr;
ierr = VT_funcdef(event_name, VT_NOCLASS, &event_communication);
}
#endif
START_TIMING(TIME_TOTAL);
#pragma omp parallel
{
for (int k = 0; k < nt; k++) {
#if PRINT_DEBUG
my_print("Iteration [%03d][000]\tR#%d T#%d (OS_TID:%ld): --> 0 Starting new loop iter\n", k, mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
if (block_rank[k*nt+k] == mype) {
#pragma omp single
{
// first calculate diagonal element
omp_potrf(A[k][k], ts, ts);
}
#pragma omp master
{
START_TIMING(TIME_COMM);
send_cnt = 0;
reset_send_flags(send_flags);
send_cnt = get_send_flags(send_flags, block_rank, k, k, k+1, nt-1, nt);
if (send_cnt != 0) {
#ifdef TRACE
VT_begin(event_communication);
#endif
int exec_wait = 0;
send_cnt = 0;
for (int dst = 0; dst < np; dst++) {
if (send_flags[dst] && dst != mype) {
exec_wait = 1;
MPI_Isend(A[k][k], ts*ts, MPI_DOUBLE, dst, k*nt+k, MPI_COMM_WORLD,
&send_reqs[send_cnt++]);
}
}
if(exec_wait)
waitall(send_reqs, send_cnt);
#ifdef TRACE
VT_end(event_communication);
#endif
}
END_TIMING(TIME_COMM);
}
} else {
#pragma omp single
{
START_TIMING(TIME_COMM);
recv_flag = 0;
get_recv_flag(&recv_flag, block_rank, k, k, k+1, nt-1, nt);
if (recv_flag) {
#ifdef TRACE
VT_begin(event_communication);
#endif
MPI_Irecv(B, ts*ts, MPI_DOUBLE, block_rank[k*nt+k], k*nt+k, MPI_COMM_WORLD,
&recv_req);
wait(&recv_req);
#ifdef TRACE
VT_end(event_communication);
#endif
}
END_TIMING(TIME_COMM);
}
}
void* literal_ts = *(void**)(&ts);
#pragma omp for nowait
for (int i = k + 1; i < nt; i++) {
if (block_rank[k*nt+i] == mype) {
if (block_rank[k*nt+k] == mype) {
double * SPEC_RESTRICT tmp_a_k_k = A[k][k];
double * SPEC_RESTRICT tmp_a_k_i = A[k][i];
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: tmp_a_k_k[0:ts*ts]) map(tofrom: tmp_a_k_i[0:ts*ts]) device(1002)
{
// printf("In Task: AKK = " DPxMOD ", AKI = " DPxMOD "\n", DPxPTR(tmp_a_k_k), DPxPTR(tmp_a_k_i));
omp_trsm(tmp_a_k_k, tmp_a_k_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(4*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_a_k_k, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_k_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[2] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_trsm, 4, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
// printf("R#%d T#%d (OS_TID:%ld): --> In Task: AKK = " DPxMOD ", AKI = " DPxMOD "\n", mype, omp_get_thread_num(), syscall(SYS_gettid), DPxPTR(tmp_a_k_k), DPxPTR(tmp_a_k_i));
omp_trsm(tmp_a_k_k, tmp_a_k_i, ts, ts);
}
#endif
} else {
double * SPEC_RESTRICT tmp_a_k_i = A[k][i];
// printf("R#%d T#%d (OS_TID:%ld): --> Before Task: B = " DPxMOD ", AKI = " DPxMOD "\n", mype, omp_get_thread_num(), syscall(SYS_gettid), DPxPTR(B), DPxPTR(tmp_a_k_i));
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: B[0:ts*ts]) map(tofrom: tmp_a_k_i[0:ts*ts]) device(1002)
{
// printf("In Task: B = " DPxMOD ", AKI = " DPxMOD "\n", DPxPTR(B), DPxPTR(tmp_a_k_i));
omp_trsm(B, tmp_a_k_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(4*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(B, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_k_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[2] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_trsm, 4, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
// printf("R#%d T#%d (OS_TID:%ld): --> In Task: B = " DPxMOD ", AKI = " DPxMOD "\n", mype, omp_get_thread_num(), syscall(SYS_gettid), DPxPTR(B), DPxPTR(tmp_a_k_i));
omp_trsm(B, tmp_a_k_i, ts, ts);
}
#endif
}
}
}
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
chameleon_distributed_taskwait(0);
#else
#pragma omp barrier
#endif
#pragma omp single nowait
{
for (int i = k + 1; i < nt; i++) {
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 0 Begin\n", k, i, mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
if (block_rank[k*nt+i] != mype) {
START_TIMING(TIME_COMM);
recv_flag = 0;
get_recv_flag(&recv_flag, block_rank, k+1, i-1, i, i, nt);
get_recv_flag(&recv_flag, block_rank, i, i, i+1, nt-1, nt);
get_recv_flag(&recv_flag, block_rank, i, i, i, i, nt);
if (recv_flag) {
#ifdef TRACE
VT_begin(event_communication);
#endif
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 1 Recieving from R#%d - Start\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid), block_rank[k*nt+i]);
#endif
MPI_Irecv(C[i], ts*ts, MPI_DOUBLE, block_rank[k*nt+i], k*nt+i, MPI_COMM_WORLD, &recv_req);
wait(&recv_req);
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 2 Recieving from R#%d - zComplete\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid), block_rank[k*nt+i]);
#endif
#ifdef TRACE
VT_end(event_communication);
#endif
}
END_TIMING(TIME_COMM);
} else {
START_TIMING(TIME_COMM);
send_cnt = 0;
reset_send_flags(send_flags);
send_cnt += get_send_flags(send_flags, block_rank, k+1, i-1, i, i, nt);
send_cnt += get_send_flags(send_flags, block_rank, i, i, i+1, nt-1, nt);
send_cnt += get_send_flags(send_flags, block_rank, i, i, i, i, nt);
if (send_cnt != 0) {
#ifdef TRACE
VT_begin(event_communication);
#endif
send_cnt = 0;
int exec_wait = 0;
for (int dst = 0; dst < np; dst++) {
if (send_flags[dst] && dst != mype) {
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 1 Sending to R#%d - Start\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid), dst);
#endif
exec_wait = 1;
MPI_Isend(A[k][i], ts*ts, MPI_DOUBLE, dst, k*nt+i,
MPI_COMM_WORLD, &send_reqs[send_cnt++]);
}
}
if(exec_wait) {
waitall(send_reqs, send_cnt);
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 2 Sending zComplete\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
}
#ifdef TRACE
VT_end(event_communication);
#endif
}
END_TIMING(TIME_COMM);
}
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 3 Comm finished\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
// temporary pointers to be able to define slices for offloading
double * SPEC_RESTRICT tmp_a_k_i = A[k][i];
double * SPEC_RESTRICT tmp_a_i_i = A[i][i];
double * SPEC_RESTRICT tmp_c_i = C[i];
{
START_TIMING(TIME_CREATE);
for (int j = k + 1; j < i; j++) {
// temporary pointers to be able to define slices for offloading
double * SPEC_RESTRICT tmp_a_k_j = A[k][j];
double * SPEC_RESTRICT tmp_a_j_i = A[j][i];
double * SPEC_RESTRICT tmp_c_j = C[j];
if (block_rank[j*nt+i] == mype) {
if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] == mype) {
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: tmp_a_k_i[0:ts*ts], tmp_a_k_j[0:ts*ts]) map(tofrom: tmp_a_j_i[0:ts*ts]) device(1002)
{
omp_gemm(tmp_a_k_i, tmp_a_k_j, tmp_a_j_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(5*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_a_k_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_k_j, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[2] = chameleon_map_data_entry_create(tmp_a_j_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[4] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_gemm, 5, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_gemm(tmp_a_k_i, tmp_a_k_j, tmp_a_j_i, ts, ts);
}
#endif
} else if (block_rank[k*nt+i] != mype && block_rank[k*nt+j] == mype) {
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: tmp_c_i[0:ts*ts], tmp_a_k_j[0:ts*ts]) map(tofrom: tmp_a_j_i[0:ts*ts]) device(1002)
{
omp_gemm(tmp_c_i, tmp_a_k_j, tmp_a_j_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(5*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_c_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_k_j, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[2] = chameleon_map_data_entry_create(tmp_a_j_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[4] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_gemm, 5, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_gemm(tmp_c_i, tmp_a_k_j, tmp_a_j_i, ts, ts);
}
#endif
} else if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] != mype) {
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: tmp_a_k_i[0:ts*ts], tmp_c_j[0:ts*ts]) map(tofrom: tmp_a_j_i[0:ts*ts]) device(1002)
{
omp_gemm(tmp_a_k_i, tmp_c_j, tmp_a_j_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(5*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_a_k_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_c_j, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[2] = chameleon_map_data_entry_create(tmp_a_j_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[4] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_gemm, 5, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_gemm(tmp_a_k_i, tmp_c_j, tmp_a_j_i, ts, ts);
}
#endif
} else {
#ifdef CHAMELEON_TARGET
#pragma omp target map(to: tmp_c_i[0:ts*ts], tmp_c_j[0:ts*ts]) map(tofrom: tmp_a_j_i[0:ts*ts]) device(1002)
{
omp_gemm(tmp_c_i, tmp_c_j, tmp_a_j_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(5*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_c_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_c_j, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[2] = chameleon_map_data_entry_create(tmp_a_j_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[4] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_gemm, 5, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_gemm(tmp_c_i, tmp_c_j, tmp_a_j_i, ts, ts);
}
#endif
}
}
}
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 4 Gemm Tasks created\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
if (block_rank[i*nt+i] == mype) {
if (block_rank[k*nt+i] == mype) {
#ifdef CHAMELEON_TARGET
#pragma omp target map(tofrom: tmp_a_k_i[0:ts*ts]) map(to: tmp_a_i_i[0:ts*ts]) device(1002)
{
omp_syrk(tmp_a_k_i, tmp_a_i_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(4*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_a_k_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_i_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[2] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_syrk, 4, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_syrk(tmp_a_k_i, tmp_a_i_i, ts, ts);
}
#endif
} else {
#ifdef CHAMELEON_TARGET
#pragma omp target map(tofrom: tmp_c_i[0:ts*ts]) map(to: tmp_a_i_i[0:ts*ts]) device(1002)
{
omp_syrk(tmp_c_i, tmp_a_i_i, ts, ts);
}
#elif CHAMELEON
chameleon_map_data_entry_t* args = (chameleon_map_data_entry_t*) malloc(4*sizeof(chameleon_map_data_entry_t));
args[0] = chameleon_map_data_entry_create(tmp_c_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO);
args[1] = chameleon_map_data_entry_create(tmp_a_i_i, ts*ts*sizeof(double), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_FROM);
args[2] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
args[3] = chameleon_map_data_entry_create(literal_ts, sizeof(void*), CHAM_OMP_TGT_MAPTYPE_TO | CHAM_OMP_TGT_MAPTYPE_LITERAL);
cham_migratable_task_t *cur_task = chameleon_create_task((void *)&omp_syrk, 4, args);
int32_t res = chameleon_add_task(cur_task);
free(args);
#else
#pragma omp task
{
omp_syrk(tmp_c_i, tmp_a_i_i, ts, ts);
}
#endif
}
}
#if PRINT_DEBUG
my_print("Iteration [%03d][%03d]\tR#%d T#%d (OS_TID:%ld): --> 5 Syrk Tasks created\n", k, i,mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
END_TIMING(TIME_CREATE);
}
}
}
#if PRINT_DEBUG
my_print("Iteration [%03d][998]\tR#%d T#%d (OS_TID:%ld): --> 6 Proceeding to chameleon_distributed_taskwait(...)/barrier\n", k, mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
chameleon_distributed_taskwait(0);
#else
#pragma omp barrier
#endif
#if PRINT_DEBUG
my_print("Iteration [%03d][999]\tR#%d T#%d (OS_TID:%ld): --> 7 Finished chameleon_distributed_taskwait(...)/barrier\n", k, mype, omp_get_thread_num(), syscall(SYS_gettid));
#endif
// #if !defined(CHAMELEON) && !defined(CHAMELEON_TARGET)
// #pragma omp single
// {
// PRINT_INTERMEDIATE_TIMINGS(omp_get_num_threads());
// }
// #endif
}
} /* end omp parallel */
END_TIMING(TIME_TOTAL);
MPI_Barrier(MPI_COMM_WORLD);
#pragma omp parallel
#pragma omp master
PRINT_TIMINGS(omp_get_num_threads());
FREE_TIMING();
#if defined(CHAMELEON) || defined(CHAMELEON_TARGET)
chameleon_finalize();
#endif
free(send_flags);
}
|
kmeans_impl.h | /*!
* Modifications Copyright 2017 H2O.ai, Inc.
*/
// original code from https://github.com/NVIDIA/kmeans (Apache V2.0 License)
#pragma once
#include <atomic>
#include <signal.h>
#include <string>
#include <sstream>
#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <thrust/inner_product.h>
#include "kmeans_centroids.h"
#include "kmeans_labels.h"
#include "kmeans_general.h"
namespace kmeans {
//! kmeans clusters data into k groups
/*!
\param n Number of data points
\param d Number of dimensions
\param k Number of clusters
\param data Data points, in row-major order. This vector must have
size n * d, and since it's in row-major order, data point x occupies
positions [x * d, (x + 1) * d) in the vector. The vector is passed
by reference since it is shared with the caller and not copied.
\param labels Cluster labels. This vector has size n.
The vector is passed by reference since it is shared with the caller
and not copied.
\param centroids Centroid locations, in row-major order. This
vector must have size k * d, and since it's in row-major order,
centroid x occupies positions [x * d, (x + 1) * d) in the
vector. The vector is passed by reference since it is shared
with the caller and not copied.
\param threshold This controls early termination of the kmeans
iterations. If the ratio of points being reassigned to a different
centroid is less than the threshold, than the iterations are
terminated. Defaults to 1e-3.
\param max_iterations Maximum number of iterations to run
\return The number of iterations actually performed.
*/
template<typename T>
int kmeans(
int verbose,
volatile std::atomic_int *flag,
int n, int d, int k,
thrust::device_vector<T> **data,
thrust::device_vector<int> **labels,
thrust::device_vector<T> **centroids,
thrust::device_vector<T> **data_dots,
std::vector<int> dList,
int n_gpu,
int max_iterations,
double threshold = 1e-3,
bool do_per_iter_check = true) {
thrust::device_vector<T> *centroid_dots[n_gpu];
thrust::device_vector<int> *labels_copy[n_gpu];
thrust::device_vector<int> *range[n_gpu];
thrust::device_vector<int> *indices[n_gpu];
thrust::device_vector<int> *counts[n_gpu];
thrust::device_vector<T> d_old_centroids;
thrust::host_vector<int> h_counts(k);
thrust::host_vector<int> h_counts_tmp(k);
thrust::host_vector<T> h_centroids(k * d);
h_centroids = *centroids[0]; // all should be equal
thrust::host_vector<T> h_centroids_tmp(k * d);
T *d_distance_sum[n_gpu];
bool unable_alloc = false;
#pragma omp parallel for
for (int q = 0; q < n_gpu; q++) {
log_debug(verbose, "Before kmeans() Allocation: gpu: %d", q);
safe_cuda(cudaSetDevice(dList[q]));
safe_cuda(cudaMalloc(&d_distance_sum[q], sizeof(T)));
try {
centroid_dots[q] = new thrust::device_vector<T>(k);
labels_copy[q] = new thrust::device_vector<int>(n / n_gpu);
range[q] = new thrust::device_vector<int>(n / n_gpu);
counts[q] = new thrust::device_vector<int>(k);
indices[q] = new thrust::device_vector<int>(n / n_gpu);
} catch (thrust::system_error &e) {
log_error(verbose, "Unable to allocate memory for gpu: %d | n/n_gpu: %d | k: %d | d: %d | error: %s",
q, n / n_gpu, k, d, e.what());
unable_alloc = true;
// throw std::runtime_error(ss.str());
} catch (std::bad_alloc &e) {
log_error(verbose, "Unable to allocate memory for gpu: %d | n/n_gpu: %d | k: %d | d: %d | error: %s",
q, n / n_gpu, k, d, e.what());
unable_alloc = true;
//throw std::runtime_error(ss.str());
}
if (!unable_alloc){
//Create and save "range" for initializing labels
thrust::copy(thrust::counting_iterator<int>(0),
thrust::counting_iterator<int>(n / n_gpu),
(*range[q]).begin());
}
}
if (unable_alloc) return(-1);
log_debug(verbose, "Before kmeans() Iterations");
int i = 0;
bool done = false;
for (; i < max_iterations; i++) {
log_verbose(verbose, "KMeans - Iteration %d/%d", i, max_iterations);
if (*flag) continue;
safe_cuda(cudaSetDevice(dList[0]));
d_old_centroids = *centroids[dList[0]];
#pragma omp parallel for
for (int q = 0; q < n_gpu; q++) {
safe_cuda(cudaSetDevice(dList[q]));
detail::batch_calculate_distances(verbose, q, n / n_gpu, d, k,
*data[q], *centroids[q], *data_dots[q], *centroid_dots[q],
[&](int n, size_t offset, thrust::device_vector<T> &pairwise_distances) {
detail::relabel(n, k, pairwise_distances, *labels[q], offset);
});
log_verbose(verbose, "KMeans - Relabeled.");
detail::memcpy(*labels_copy[q], *labels[q]);
detail::find_centroids(q,
n / n_gpu,
d,
k,
*data[q],
*labels_copy[q],
*centroids[q],
*range[q],
*indices[q],
*counts[q],
n_gpu <= 1
);
}
// Scale the centroids on host
if (n_gpu > 1) {
//Average the centroids from each device
for (int p = 0; p < k; p++) h_counts[p] = 0.0;
for (int q = 0; q < n_gpu; q++) {
safe_cuda(cudaSetDevice(dList[q]));
detail::memcpy(h_counts_tmp, *counts[q]);
detail::streamsync(dList[q]);
for (int p = 0; p < k; p++) h_counts[p] += h_counts_tmp[p];
}
// Zero the centroids only if any of the GPUs actually updated them
for (int p = 0; p < k; p++) {
for (int r = 0; r < d; r++) {
if (h_counts[p] != 0) {
h_centroids[p * d + r] = 0.0;
}
}
}
for (int q = 0; q < n_gpu; q++) {
safe_cuda(cudaSetDevice(dList[q]));
detail::memcpy(h_centroids_tmp, *centroids[q]);
detail::streamsync(dList[q]);
for (int p = 0; p < k; p++) {
for (int r = 0; r < d; r++) {
if (h_counts[p] != 0) {
h_centroids[p * d + r] += h_centroids_tmp[p * d + r];
}
}
}
}
for (int p = 0; p < k; p++) {
for (int r = 0; r < d; r++) {
// If 0 counts that means we leave the original centroids
if (h_counts[p] == 0) {
h_counts[p] = 1;
}
h_centroids[p * d + r] /= h_counts[p];
}
}
//Copy the averaged centroids to each device
#pragma omp parallel for
for (int q = 0; q < n_gpu; q++) {
safe_cuda(cudaSetDevice(dList[q]));
detail::memcpy(*centroids[q], h_centroids);
}
}
// whether to perform per iteration check
if (do_per_iter_check) {
safe_cuda(cudaSetDevice(dList[0]));
T squared_norm = thrust::inner_product(
d_old_centroids.begin(), d_old_centroids.end(),
(*centroids[0]).begin(),
(T) 0.0,
thrust::plus<T>(),
[=]__device__(T left, T right){
T diff = left - right;
return diff * diff;
}
);
if (squared_norm < threshold) {
if (verbose) { std::cout << "Threshold triggered. Terminating early." << std::endl; }
done = true;
}
}
if (*flag) {
fprintf(stderr, "Signal caught. Terminated early.\n");
fflush(stderr);
*flag = 0; // set flag
done = true;
}
if (done || i == max_iterations - 1){
// Final relabeling - uses final centroids
#pragma omp parallel for
for (int q = 0; q < n_gpu; q++){
safe_cuda(cudaSetDevice(dList[q]));
detail::batch_calculate_distances(verbose, q, n / n_gpu, d, k,
*data[q], *centroids[q], *data_dots[q], *centroid_dots[q],
[&](int n, size_t offset, thrust::device_vector<T> &pairwise_distances) {
detail::relabel(n, k, pairwise_distances, *labels[q], offset);
});
}
break;
}
}
//#pragma omp parallel for
for (int q = 0; q < n_gpu; q++){
safe_cuda(cudaSetDevice(dList[q]));
delete (centroid_dots[q]);
delete (labels_copy[q]);
delete (range[q]);
delete (counts[q]);
delete (indices[q]);
}
log_debug(verbose, "Iterations: %d", i);
return i;
}
}
|
main-single-mailbox-wavefront.c | #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <shmem.h>
#include <shmemx.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
#include <omp.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <limits.h>
#include <pthread.h>
#define VERBOSE
// #ifdef USE_CRC
// #include "crc.h"
// typedef int32_t size_type;
// #elif USE_MURMUR
// #include "MurmurHash3.h"
// typedef uint32_t crc;
// typedef int32_t size_type;
// #elif USE_CITY32
// #include "city.h"
// typedef uint32_t crc;
// typedef int32_t size_type;
// #elif USE_CITY64
// #include "city.h"
// typedef uint64_t crc;
// typedef int64_t size_type;
// #else
// #error No hashing algorithm specific
// #endif
#include "mrg.h"
#include "packed_edge.h"
#include "utilities.h"
#include "generator.h"
// #define QUEUE_SIZE 1572864
#define QUEUE_SIZE 1048576
// #define INCOMING_MAILBOX_SIZE_IN_BYTES 100663296
#define INCOMING_MAILBOX_SIZE_IN_BYTES (200 * 1024 * 1024)
/*
* Header format:
*
* sizeof(crc) bytes : header checksum
* sizeof(size_type) bytes : Length of whole packet in bytes (N)
* sizeof(crc) bytes : CRC32 body checksum
* N - sizeof(crc) - sizeof(size_type) - sizeof(crc) bytes : Body
*/
#define COALESCING 512
#define SEND_HEADER_SIZE (sizeof(crc) + sizeof(size_type) + sizeof(crc))
#define SEND_BUFFER_SIZE (SEND_HEADER_SIZE + COALESCING * sizeof(packed_edge))
#define BITS_PER_BYTE 8
#define BITS_PER_INT (sizeof(unsigned) * BITS_PER_BYTE)
#define CONTEXTS_PER_THREAD 2
typedef struct {
short steady_state;
short bufs[2];
} vert_info;
typedef struct _send_buf {
unsigned char *buf;
struct _send_buf *next;
} send_buf;
#define SEND_BUF_SIZE_TO_NEDGES(my_send_buf_size) (((my_send_buf_size) - SEND_HEADER_SIZE) / sizeof(packed_edge))
#define GET_SEND_BUF(my_target_pe) { \
assert(send_bufs[my_target_pe] == NULL); \
send_buf *gotten = pre_allocated_send_bufs; \
assert(gotten); \
pre_allocated_send_bufs = gotten->next; \
send_bufs[my_target_pe] = gotten; \
send_bufs_size[my_target_pe] = SEND_HEADER_SIZE; \
}
#define PREPARE_PACKET(my_target_pe) { \
assert(send_bufs[my_target_pe]); \
const unsigned send_buf_size = send_bufs_size[my_target_pe]; \
assert((send_buf_size - SEND_HEADER_SIZE) % sizeof(packed_edge) == 0); \
assert(send_buf_size <= SEND_BUFFER_SIZE); \
const unsigned nedges = SEND_BUF_SIZE_TO_NEDGES(send_buf_size); \
unsigned char *send_buf = send_bufs[my_target_pe]->buf; \
/* Save the total size of this packet */ \
*((size_type *)(send_buf + sizeof(crc))) = send_buf_size; \
/* Save the CRC of the body of this packet */ \
*((crc *)(send_buf + sizeof(crc) + sizeof(size_type))) = hash( \
(const unsigned char *)(send_buf + SEND_HEADER_SIZE), \
send_buf_size - SEND_HEADER_SIZE); \
/* Save the CRC of the header of this packet */ \
*((crc *)send_buf) = hash( \
(const unsigned char *)(send_buf + sizeof(crc)), \
SEND_HEADER_SIZE - sizeof(crc)); \
}
#define SEND_PACKET(my_target_pe) { \
PREPARE_PACKET(my_target_pe) \
\
const int remote_offset = shmem_int_fadd( \
recv_buf_index, send_bufs_size[my_target_pe], \
my_target_pe); \
assert(remote_offset + send_bufs_size[my_target_pe] < INCOMING_MAILBOX_SIZE_IN_BYTES); \
shmem_char_put_nbi((char *)(recv_buf + remote_offset), \
(const char *)send_bufs[my_target_pe]->buf, \
send_bufs_size[my_target_pe], my_target_pe); \
\
send_bufs[my_target_pe] = NULL; \
send_bufs_size[my_target_pe] = 0; \
}
// #define VERBOSE
// #define PROFILE
static int pe = -1;
static int npes = -1;
void sig_handler(int signo) {
fprintf(stderr, "%d: received signal %d %d\n", pe, signo, SIGUSR1);
raise(SIGABRT);
assert(0); // should never reach here
}
void *kill_func(void *data) {
int kill_seconds = *((int *)data);
int err = sleep(kill_seconds);
assert(err == 0);
fprintf(stderr, "hitting pe %d with SUGUSR1\n", pe);
raise(SIGUSR1);
return NULL;
}
#ifdef PROFILE
unsigned long long hash_time = 0;
unsigned long long hash_calls = 0;
unsigned long long wasted_hashes = 0;
unsigned long long total_packets_received = 0;
unsigned long long n_packets_wasted = 0;
unsigned long long total_elements_received = 0;
unsigned long long n_elements_wasted = 0;
#ifdef DETAILED_PROFILE
unsigned *wavefront_visited = NULL;
unsigned long long duplicates_in_same_wavefront = 0;
unsigned long long duplicates_in_same_wavefront_total = 0;
#endif
#endif
// static inline crc hash(const unsigned char * const data, const size_t len) {
// #ifdef PROFILE
// const unsigned long long start_time = current_time_ns();
// #endif
//
// crc result;
// #ifdef USE_CRC
// result = crcFast(data, len);
// #elif USE_MURMUR
// MurmurHash3_x86_32(data, len, 12345, &result);
// #elif USE_CITY32
// result = CityHash32((const char *)data, len);
// #elif USE_CITY64
// result = CityHash64((const char *)data, len);
// #else
// #error No hashing algorithm specified
// #endif
//
// #ifdef PROFILE
// hash_time += (current_time_ns() - start_time);
// hash_calls++;
// #endif
//
// return result;
// }
uint64_t bfs_roots[] = {240425174, 115565041, 66063943, 180487911, 11178951,
123935973, 231036167, 373595937, 363787030, 85801485, 108275987, 69071368,
514373733, 251500048, 140103887, 506907254, 39995468, 195903646, 21863341,
390997409, 470978452, 372755572, 449581394, 461086083, 357027875, 355651295,
18628407, 427844427, 273604491, 372475785, 427329960, 465597328, 78313325,
90706091, 457847627, 430362844, 178489195, 374418701, 7644678, 154891942,
353689376, 56388509, 191747720, 264370699, 20638787, 421731131, 14127289,
411537113, 397525451, 189929616, 140277533, 221845716, 135921328, 141538717,
264336150, 267866811, 413698500, 263044574, 490922152, 81101617, 415841963,
132009584, 67293842, 148419562};
volatile long long n_local_edges = 0;
volatile long long max_n_local_edges;
static uint64_t get_vertices_per_pe(uint64_t nvertices) {
return (nvertices + npes - 1) / npes;
}
static uint64_t get_starting_vertex_for_pe(int pe, uint64_t nvertices) {
uint64_t vertices_per_pe = get_vertices_per_pe(nvertices);
return pe * vertices_per_pe;
}
static uint64_t get_ending_vertex_for_pe(int pe, uint64_t nvertices) {
uint64_t vertices_per_pe = get_vertices_per_pe(nvertices);
uint64_t limit = (pe + 1) * vertices_per_pe;
if (limit > nvertices) limit = nvertices;
return limit;
}
static inline int get_owner_pe(uint64_t vertex, uint64_t nvertices) {
uint64_t vertices_per_pe = get_vertices_per_pe(nvertices);
return vertex / vertices_per_pe;
}
static inline void set_visited(const uint64_t global_vertex_id,
unsigned *visited, const unsigned visited_length,
const uint64_t local_min_vertex) {
const int word_index = global_vertex_id / BITS_PER_INT;
assert(word_index < visited_length);
const int bit_index = global_vertex_id % BITS_PER_INT;
const int mask = (1 << bit_index);
// __sync_fetch_and_or(visited + word_index, mask);
visited[word_index] |= mask;
}
static inline int is_visited(const uint64_t global_vertex_id,
const unsigned *visited, const size_t visited_length,
const uint64_t local_min_vertex) {
const unsigned word_index = global_vertex_id / BITS_PER_INT;
assert(word_index < visited_length);
const int bit_index = global_vertex_id % BITS_PER_INT;
const int mask = (1 << bit_index);
return (((visited[word_index] & mask) > 0) ? 1 : 0);
}
/* Spread the two 64-bit numbers into five nonzero values in the correct
* range. */
static void make_mrg_seed(uint64_t userseed1, uint64_t userseed2,
uint_fast32_t* seed) {
seed[0] = (userseed1 & 0x3FFFFFFF) + 1;
seed[1] = ((userseed1 >> 30) & 0x3FFFFFFF) + 1;
seed[2] = (userseed2 & 0x3FFFFFFF) + 1;
seed[3] = ((userseed2 >> 30) & 0x3FFFFFFF) + 1;
seed[4] = ((userseed2 >> 60) << 4) + (userseed1 >> 60) + 1;
}
static int compare_uint64_t(const void *a, const void *b) {
const uint64_t *aa = (const uint64_t *)a;
const uint64_t *bb = (const uint64_t *)b;
if (*aa < *bb) {
return -1;
} else if (*aa == *bb) {
return 0;
} else {
return 1;
}
}
static inline void loop_body(vert_info *verts, const uint64_t local_vertex_id,
const int last_put_index, const unsigned *local_vertex_offsets,
const uint64_t *neighbors, const uint64_t nglobalverts,
unsigned *shared_visited, const size_t visited_ints,
const uint64_t local_min_vertex, unsigned *local_visited,
const int updating_index, const short *pe_plus_one_ptr,
int *thread_natomics,
unsigned long long *time_blocked_on_quiet, shmemx_ctx_t *thread_ctxs,
int *natomics_issued, int *curr_ctx_index) {
const short curr = verts[local_vertex_id].bufs[last_put_index];
// const short curr = last_put[local_vertex_id];
if (curr > 0 && verts[local_vertex_id].steady_state == 0) {
const int neighbor_start = local_vertex_offsets[local_vertex_id];
const int neighbor_end = local_vertex_offsets[local_vertex_id + 1];
int j;
for (j = neighbor_start; j < neighbor_end; j++) {
const uint64_t to_explore_global_id = neighbors[j];
const int target_pe = get_owner_pe(to_explore_global_id, nglobalverts);
const uint64_t to_explore_local_id = to_explore_global_id -
get_starting_vertex_for_pe(target_pe, nglobalverts);
assert(to_explore_local_id < get_vertices_per_pe(nglobalverts));
const int already_visited = is_visited(
to_explore_global_id, shared_visited,
visited_ints, local_min_vertex) ||
is_visited(to_explore_global_id, local_visited,
visited_ints, local_min_vertex);
if (!already_visited) {
const int ctx_index = *curr_ctx_index;
const shmemx_ctx_t curr_ctx = thread_ctxs[ctx_index];
shmemx_ctx_putmem(
&(verts[to_explore_local_id].bufs[updating_index]),
pe_plus_one_ptr, sizeof(*pe_plus_one_ptr), target_pe,
curr_ctx);
const int curr_n_atomics = *thread_natomics + 1;
*thread_natomics = curr_n_atomics;
natomics_issued[ctx_index]++;
if (natomics_issued[ctx_index] > 512) {
// Want to start quieting this one and move to the next one
const int next_index = (ctx_index + 1) % CONTEXTS_PER_THREAD;
shmemx_ctx_t next_ctx = thread_ctxs[next_index];
const unsigned long long start_quiet = current_time_ns();
shmemx_ctx_quiet(next_ctx);
// if (shmemx_ctx_try_quiet(next_ctx) == 0) {
natomics_issued[next_index] = 0;
*curr_ctx_index = next_index;
// }
const unsigned long long elapsed_quiet = current_time_ns() - start_quiet;
*time_blocked_on_quiet += elapsed_quiet;
}
set_visited(to_explore_global_id, local_visited,
visited_ints, local_min_vertex);
if (target_pe == pe) {
set_visited(to_explore_global_id, shared_visited,
visited_ints, local_min_vertex);
}
}
}
verts[local_vertex_id].steady_state = curr;
verts[local_vertex_id].bufs[last_put_index] = 0;
set_visited(local_min_vertex + local_vertex_id,
shared_visited,visited_ints, local_min_vertex);
}
}
int main(int argc, char **argv) {
#ifdef USE_CRC
crcInit();
#endif
if (argc < 4) {
fprintf(stderr, "usage: %s scale edgefactor num-bfs-roots\n",
argv[0]);
fprintf(stderr, " scale = log_2(# vertices)\n");
fprintf(stderr, " edgefactor = .5 * (average vertex degree)\n");
fprintf(stderr, " num-bfs-roots = # of roots to build a tree from "
"[optional]\n");
fprintf(stderr, "\n");
fprintf(stderr, " For scale, the Graph500 benchmark defines the "
"following presets:\n");
fprintf(stderr, " toy = 26\n");
fprintf(stderr, " mini = 29\n");
fprintf(stderr, " small = 32\n");
fprintf(stderr, " medium = 36\n");
fprintf(stderr, " large = 39\n");
fprintf(stderr, " huge = 42\n");
fprintf(stderr, " The standard choice for edgefactor is 16\n");
return 1;
}
const uint64_t scale = atoi(argv[1]);
const uint64_t edgefactor = atoi(argv[2]);
const uint64_t nglobaledges = (uint64_t)(edgefactor << scale);
const uint64_t nglobalverts = (uint64_t)(((uint64_t)1) << scale);
const int num_bfs_roots = atoi(argv[3]);
// __sighandler_t serr = signal(SIGUSR1, sig_handler);
// assert(serr != SIG_ERR);
// int kill_seconds = 120;
// pthread_t thread;
// const int perr = pthread_create(&thread, NULL, kill_func,
// (void *)&kill_seconds);
// assert(perr == 0);
int provided;
shmemx_init_thread(SHMEMX_THREAD_MULTIPLE, &provided);
assert(provided == SHMEMX_THREAD_MULTIPLE);
int nthreads;
#pragma omp parallel
#pragma omp master
{
nthreads = omp_get_num_threads();
}
uint64_t i;
shmemx_domain_t *domains = (shmemx_domain_t *)malloc(nthreads * sizeof(*domains));
shmemx_ctx_t *contexts = (shmemx_ctx_t *)malloc(CONTEXTS_PER_THREAD * nthreads * sizeof(*contexts));
assert(domains && contexts);
int err = shmemx_domain_create(SHMEMX_THREAD_SINGLE,
nthreads, domains);
assert(err == 0);
for (i = 0; i < nthreads; i++) {
int j;
for (j = 0; j < CONTEXTS_PER_THREAD; j++) {
err = shmemx_ctx_create(domains[i],
contexts + (CONTEXTS_PER_THREAD * i + j));
assert(err == 0);
}
}
pe = shmem_my_pe();
npes = shmem_n_pes();
uint_fast32_t seed[5];
uint64_t seed1 = 2, seed2 = 3;
make_mrg_seed(seed1, seed2, seed);
const uint64_t edges_per_pe = (nglobaledges + npes - 1) / npes;
const uint64_t start_edge_index = pe * edges_per_pe;
int64_t nedges_this_pe = edges_per_pe;
if (start_edge_index + nedges_this_pe > nglobaledges) {
nedges_this_pe = nglobaledges - start_edge_index;
if (nedges_this_pe < 0) nedges_this_pe = 0;
}
if (pe == 0) {
fprintf(stderr, "%llu: %lu total vertices, %lu total edges, %d PEs, "
"~%lu edges per PE, ~%lu vertices per PE, %d threads per PE\n",
current_time_ns(), nglobalverts, nglobaledges, npes,
edges_per_pe, get_vertices_per_pe(nglobalverts), nthreads);
}
/*
* Use the Graph500 utilities to generate a set of edges distributed across
* PEs.
*/
#ifdef VERBOSE
fprintf(stderr, "A> PE %d malloc-ing %llu bytes\n", shmem_my_pe(),
nedges_this_pe * sizeof(packed_edge));
#endif
packed_edge *actual_buf = (packed_edge *)malloc(
nedges_this_pe * sizeof(packed_edge));
assert(actual_buf || nedges_this_pe == 0);
generate_kronecker_range(seed, scale, start_edge_index,
start_edge_index + nedges_this_pe, actual_buf);
/*
* Count the number of edge endpoints in actual_buf that are resident on
* each PE.
*/
#ifdef VERBOSE
fprintf(stderr, "B> PE %d calloc-ing %llu bytes\n", shmem_my_pe(),
npes * sizeof(long long));
const unsigned long long start_counting_edges = current_time_ns();
#endif
long long *count_edges_shared_with_pe = (long long *)calloc(npes,
sizeof(long long));
assert(count_edges_shared_with_pe);
for (i = 0; i < nedges_this_pe; i++) {
int64_t v0 = get_v0_from_edge(actual_buf + i);
int64_t v1 = get_v1_from_edge(actual_buf + i);
int v0_pe = get_owner_pe(v0, nglobalverts);
int v1_pe = get_owner_pe(v1, nglobalverts);
count_edges_shared_with_pe[v0_pe] += 1;
count_edges_shared_with_pe[v1_pe] += 1;
}
/*
* Tell each PE how many edges you have to send it based on vertex
* ownership.
*/
#ifdef VERBOSE
fprintf(stderr, "C> PE %d malloc-ing %llu bytes\n", shmem_my_pe(),
npes * sizeof(long long));
const unsigned long long start_getting_offsets = current_time_ns();
fprintf(stderr, "PE %d time to count edges = %f ms\n", shmem_my_pe(),
(double)(start_getting_offsets - start_counting_edges) / 1000000.0);
#endif
long long *remote_offsets = (long long *)malloc(npes * sizeof(long long));
assert(remote_offsets);
for (i = 0; i < npes; i++) {
remote_offsets[i] = shmem_longlong_fadd((long long int *)&n_local_edges,
count_edges_shared_with_pe[i], i);
}
free(count_edges_shared_with_pe);
shmem_barrier_all();
#ifdef VERBOSE
fprintf(stderr, "D> PE %d shmem_malloc-ing %llu bytes\n", shmem_my_pe(),
SHMEM_REDUCE_SYNC_SIZE * sizeof(long));
#endif
int *pWrkInt = (int *)shmem_malloc(SHMEM_REDUCE_MIN_WRKDATA_SIZE * sizeof(*pWrkInt));
long long *pWrkLongLong = (long long *)shmem_malloc(
SHMEM_REDUCE_MIN_WRKDATA_SIZE * sizeof(*pWrkLongLong));
assert(pWrkInt && pWrkLongLong);
long *pSync = (long *)shmem_malloc(SHMEM_REDUCE_SYNC_SIZE * sizeof(long));
#ifdef VERBOSE
fprintf(stderr, "E> PE %d shmem_malloc-ing %llu bytes\n", shmem_my_pe(),
SHMEM_REDUCE_SYNC_SIZE * sizeof(long));
#endif
long *pSync2 = (long *)shmem_malloc(SHMEM_REDUCE_SYNC_SIZE * sizeof(long));
assert(pSync && pSync2);
for (i = 0; i < SHMEM_REDUCE_SYNC_SIZE; i++) {
pSync[i] = SHMEM_SYNC_VALUE;
pSync2[i] = SHMEM_SYNC_VALUE;
}
shmem_longlong_max_to_all((long long int *)&max_n_local_edges,
(long long int *)&n_local_edges, 1, 0, 0, npes, pWrkLongLong, pSync);
if (pe == 0) {
fprintf(stderr, "%llu: Max. # local edges = %lld\n", current_time_ns(),
max_n_local_edges);
}
uint64_t local_min_vertex = get_starting_vertex_for_pe(pe, nglobalverts);
uint64_t local_max_vertex = get_ending_vertex_for_pe(pe, nglobalverts);
uint64_t n_local_vertices;
if (local_min_vertex >= local_max_vertex) {
n_local_vertices = 0;
} else {
n_local_vertices = local_max_vertex - local_min_vertex;
}
/*
* Allocate buffers on each PE for storing all edges for which at least one
* of the vertices of the edge is handled by this PE. This information will
* be provided by other PEs.
*/
#ifdef VERBOSE
fprintf(stderr, "F> PE %d shmem_malloc-ing %llu bytes\n", shmem_my_pe(),
max_n_local_edges * sizeof(packed_edge));
const unsigned long long start_sending_edges = current_time_ns();
fprintf(stderr, "PE %d time to get offsets = %f ms\n", shmem_my_pe(),
(double)(start_sending_edges - start_getting_offsets) / 1000000.0);
#endif
packed_edge *local_edges = (packed_edge *)shmem_malloc(
max_n_local_edges * sizeof(packed_edge));
assert(local_edges);
/*
* Send out to each PE based on the vertices each owns, all edges that have
* a vertix on that node. This means that vertices which have one vertix on
* one node and one vertix on another will be sent to two different nodes.
*/
// for (i = 0; i < nedges_this_pe; i++) {
// int64_t v0 = get_v0_from_edge(actual_buf + i);
// int64_t v1 = get_v1_from_edge(actual_buf + i);
// int v0_pe = get_owner_pe(v0, nglobalverts);
// int v1_pe = get_owner_pe(v1, nglobalverts);
// shmem_putmem(local_edges + remote_offsets[v0_pe], actual_buf + i,
// sizeof(packed_edge), v0_pe);
// remote_offsets[v0_pe]++;
// shmem_putmem(local_edges + remote_offsets[v1_pe], actual_buf + i,
// sizeof(packed_edge), v1_pe);
// remote_offsets[v1_pe]++;
// shmem_quiet();
// }
//
// free(remote_offsets);
//
// shmem_barrier_all();
//
// free(actual_buf);
unsigned max_count = 0;
#pragma omp parallel default(none) reduction(max:max_count) \
firstprivate(actual_buf, npes, nedges_this_pe)
{
unsigned local_max_count = 0;
#pragma omp for
for (int p = 0; p < npes; p++) {
unsigned count = 0;
for (int i = 0; i < nedges_this_pe; i++) {
int64_t v0 = get_v0_from_edge(actual_buf + i);
int64_t v1 = get_v1_from_edge(actual_buf + i);
int v0_pe = get_owner_pe(v0, nglobalverts);
int v1_pe = get_owner_pe(v1, nglobalverts);
if (v0_pe == p) {
count++;
}
if (v1_pe == p) {
count++;
}
}
if (count > local_max_count) {
local_max_count = count;
}
}
max_count = local_max_count;
}
packed_edge *tmp_buf = (packed_edge *)malloc(
nthreads * max_count * sizeof(packed_edge));
assert(tmp_buf);
#pragma omp parallel for default(none) firstprivate(npes, remote_offsets, \
contexts, nedges_this_pe, actual_buf, local_edges, tmp_buf, max_count)
for (int p = 0; p < npes; p++) {
packed_edge *my_tmp_buf = tmp_buf + (omp_get_thread_num() * max_count);
#ifndef RUNTIME_SAFETY
const shmemx_ctx_t ctx = contexts[omp_get_thread_num() *
CONTEXTS_PER_THREAD];
#endif
int count = 0;
for (unsigned i = 0; i < nedges_this_pe; i++) {
int64_t v0 = get_v0_from_edge(actual_buf + i);
int64_t v1 = get_v1_from_edge(actual_buf + i);
int v0_pe = get_owner_pe(v0, nglobalverts);
int v1_pe = get_owner_pe(v1, nglobalverts);
if (v0_pe == p) {
memcpy(my_tmp_buf + count, actual_buf + i, sizeof(packed_edge));
count++;
}
if (v1_pe == p) {
memcpy(my_tmp_buf + count, actual_buf + i, sizeof(packed_edge));
count++;
}
}
#ifndef RUNTIME_SAFETY
shmemx_ctx_putmem(local_edges + remote_offsets[p], my_tmp_buf,
count * sizeof(packed_edge), p, ctx);
shmemx_ctx_quiet(ctx);
#else
shmem_putmem(local_edges + remote_offsets[p], my_tmp_buf,
count * sizeof(packed_edge), p);
shmem_quiet();
#endif
}
free(tmp_buf);
free(remote_offsets);
#ifdef VERBOSE
fprintf(stderr, "PE %d done sending edges\n", shmem_my_pe());
#endif
shmem_barrier_all();
free(actual_buf);
// End paste
#ifdef VERBOSE
fprintf(stderr, "G> PE %d calloc-ing %llu bytes\n", shmem_my_pe(),
(n_local_vertices + 1) * sizeof(unsigned));
#endif
unsigned *local_vertex_offsets = (unsigned *)calloc(
(n_local_vertices + 1), sizeof(unsigned));
assert(local_vertex_offsets);
/*
* Location i in local_vertex_offsets stores the number of endpoints in
* local_edges that have locale vertix i as one of the endpoints. Hence, it
* is the total number of edge endpoints that are vertix i.
*/
for (i = 0; i < n_local_edges; i++) {
packed_edge *edge = local_edges + i;
int64_t v0 = get_v0_from_edge(edge);
int64_t v1 = get_v1_from_edge(edge);
assert(get_owner_pe(v0, nglobalverts) == pe ||
get_owner_pe(v1, nglobalverts) == pe);
if (get_owner_pe(v0, nglobalverts) == pe) {
local_vertex_offsets[v0 - local_min_vertex]++;
}
if (get_owner_pe(v1, nglobalverts) == pe) {
local_vertex_offsets[v1 - local_min_vertex]++;
}
}
#ifdef VERBOSE
fprintf(stderr, "GG> PE %d done getting offsets\n", shmem_my_pe());
#endif
/*
* After this loop, location i in local_vertex_offsets stores a global
* offset for vertix i in a local list of all endpoints stored on this PE.
* The total number of local endpoints is the number of endpoints on the
* locally stored edges that are for a vertix assigned to this PE (where the
* locally stored edges are defined to be all edges that have at least one
* vertix on this node). The sum of all local endpoints (the value in acc
* after this loop) must be >= n_local_edges because each local edge must
* have at least one endpoint that is a vertix on this node, but
* <= n_local_edges * 2 because each edge can have at most 2 endpoints that
* are vertices on this node.
*/
uint64_t acc = 0;
for (i = 0; i < n_local_vertices; i++) {
uint64_t new_acc = acc + local_vertex_offsets[i];
local_vertex_offsets[i] = new_acc; // point to the last element
acc = new_acc;
}
local_vertex_offsets[n_local_vertices] = acc;
assert(acc >= n_local_edges && acc <= n_local_edges * 2);
/*
* In neighbors, for each local endpoint discovered above we store the
* destination vertex for that endpoint. So, after this loop, given local
* vertex i:
*
* - its global vertex ID would be local_min_vertex + i
* - the list of global vertix IDs it is attached to by edges starts at
* local_vertex_offsets[i] and ends at local_vertex_offsets[i + 1]
*/
#ifdef VERBOSE
fprintf(stderr, "H> PE %d malloc-ing %llu bytes\n", shmem_my_pe(),
acc * 2 * sizeof(uint64_t));
#endif
uint64_t *neighbors = (uint64_t *)malloc(acc * 2 * sizeof(uint64_t));
assert(neighbors);
for (i = 0; i < n_local_edges; i++) {
packed_edge *edge = local_edges + i;
int64_t v0 = get_v0_from_edge(edge);
int64_t v1 = get_v1_from_edge(edge);
if (get_owner_pe(v0, nglobalverts) == pe) {
neighbors[local_vertex_offsets[v0 - local_min_vertex] - 1] = v1;
local_vertex_offsets[v0 - local_min_vertex]--;
}
if (get_owner_pe(v1, nglobalverts) == pe) {
neighbors[local_vertex_offsets[v1 - local_min_vertex] - 1] = v0;
local_vertex_offsets[v1 - local_min_vertex]--;
}
}
fprintf(stderr, "I> PE %d done computing local vertex offsets\n");
// Remove duplicate edges in neighbors
uint64_t writing_index = 0;
for (i = 0; i < n_local_vertices; i++) {
const unsigned start = local_vertex_offsets[i];
const unsigned end = local_vertex_offsets[i + 1];
assert(start <= end);
local_vertex_offsets[i] = writing_index;
qsort(neighbors + start, end - start, sizeof(*neighbors),
compare_uint64_t);
uint64_t reading_index = start;
while (reading_index < end) {
unsigned j = reading_index + 1;
while (j < end && neighbors[j] == neighbors[reading_index]) {
j++;
}
neighbors[writing_index++] = neighbors[reading_index];
reading_index = j;
}
}
local_vertex_offsets[n_local_vertices] = writing_index;
#ifdef VERBOSE
fprintf(stderr, "J> PE %d realloc-ing from %llu bytes to %llu bytes\n", shmem_my_pe(),
acc * 2 * sizeof(uint64_t), writing_index * sizeof(uint64_t));
#endif
neighbors = (uint64_t *)realloc(neighbors, writing_index *
sizeof(uint64_t));
assert(writing_index == 0 || neighbors);
// Just some double checking
for (i = 0; i < n_local_vertices; i++) {
const unsigned neighbors_start = local_vertex_offsets[i];
const unsigned neighbors_end = local_vertex_offsets[i + 1];
int j;
for (j = neighbors_start; j < neighbors_end; j++) {
if (neighbors[j] >= nglobalverts) {
fprintf(stderr, "Invalid neighbor at i = %llu / %llu, j = %u "
"(%u -> %u)\n", i,
n_local_vertices, j, neighbors_start, neighbors_end);
assert(0);
}
}
}
// For debugging, print all vertices
// {
// int k;
// for (k = 0; k < npes; k++) {
// if (k == shmem_my_pe()) {
// for (i = 0; i < n_local_vertices; i++) {
// const unsigned neighbors_start = local_vertex_offsets[i];
// const unsigned neighbors_end = local_vertex_offsets[i + 1];
// fprintf(stderr, "HOWDY %d :", local_min_vertex + i);
// int j;
// for (j = neighbors_start; j < neighbors_end; j++) {
// fprintf(stderr, " %d", neighbors[j]);
// }
// fprintf(stderr, "\n");
// }
// }
// shmem_barrier_all();
// }
// }
shmem_free(local_edges);
int *first_traversed_by = (int *)shmem_malloc(
get_vertices_per_pe(nglobalverts) * sizeof(*first_traversed_by));
assert(first_traversed_by);
int *my_n_signalled = (int *)shmem_malloc(sizeof(*my_n_signalled));
assert(my_n_signalled);
int *total_n_signalled = (int *)shmem_malloc(sizeof(*total_n_signalled));
assert(total_n_signalled);
int *my_natomics = (int *)shmem_malloc(sizeof(*my_natomics));
assert(my_natomics);
int *total_natomics = (int *)shmem_malloc(sizeof(*total_natomics));
assert(total_natomics);
const size_t visited_ints = ((nglobalverts + BITS_PER_INT - 1) /
BITS_PER_INT);
const size_t visited_bytes = visited_ints * sizeof(unsigned);
unsigned *shared_visited = (unsigned *)shmem_malloc(visited_bytes);
assert(shared_visited);
unsigned *local_visited = (unsigned *)malloc(visited_bytes);
assert(local_visited);
vert_info *verts = (vert_info *)shmem_malloc(get_vertices_per_pe(nglobalverts) *
sizeof(*verts));
assert(verts);
// short *steady_state = (short *)shmem_malloc(get_vertices_per_pe(nglobalverts) * sizeof(*steady_state));
// assert(steady_state);
// short *last_put = (short *)shmem_malloc(get_vertices_per_pe(nglobalverts) * sizeof(*last_put));
// assert(last_put);
// short *updating = (short *)shmem_malloc(get_vertices_per_pe(nglobalverts) * sizeof(*updating));
// assert(updating);
int old;
unsigned run;
for (run = 0; run < num_bfs_roots; run++) {
memset(first_traversed_by, 0x00,
get_vertices_per_pe(nglobalverts) * sizeof(*first_traversed_by));
memset(shared_visited, 0x00, visited_bytes);
memset(local_visited, 0x00, visited_bytes);
memset(verts, 0x00, get_vertices_per_pe(nglobalverts) * sizeof(*verts));
// memset(steady_state, 0x00, get_vertices_per_pe(nglobalverts) * sizeof(*steady_state));
// memset(last_put, 0x00, get_vertices_per_pe(nglobalverts) * sizeof(*last_put));
// memset(updating, 0x00, get_vertices_per_pe(nglobalverts) * sizeof(*updating));
int last_put_index = 0;
uint64_t root = 0;
set_visited(root, shared_visited, visited_ints, local_min_vertex);
set_visited(root, local_visited, visited_ints, local_min_vertex);
if (get_owner_pe(root, nglobalverts) == pe) {
// last_put[root - local_min_vertex] = pe + 1;
verts[root - local_min_vertex].bufs[last_put_index] = pe + 1;
}
shmem_barrier_all();
const unsigned long long start_bfs = current_time_ns();
int iter = 0;
*my_natomics = 0;
int prev_prev_put = 0;
int prev_put = 0;
do {
*my_n_signalled = 0;
// memset(my_n_signalled, 0x00, (npes + 1) * sizeof(*my_n_signalled));
int old; // unused
short pe_plus_one = pe + 1;
const int updating_index = (last_put_index + 1) % 2;
int reduced_natomics = 0;
unsigned long long reduced_quiet_time = 0;
const int put_delta = prev_put - prev_prev_put;
const unsigned long long start_iter = current_time_ns();
#pragma omp parallel reduction(+:reduced_natomics) reduction(+:reduced_quiet_time) default(none) \
firstprivate(pe_plus_one, my_n_signalled, pe, \
npes, local_min_vertex, local_max_vertex, verts, \
local_visited, neighbors, \
shared_visited, local_vertex_offsets, n_local_vertices, contexts, last_put_index, put_delta)
{
shmemx_ctx_t *thread_ctxs = contexts +
(omp_get_thread_num() * CONTEXTS_PER_THREAD);
int natomics_issued[CONTEXTS_PER_THREAD] = {0};
int curr_ctx_index = 0;
int thread_natomics = 0;
unsigned long long thread_quiet_time = 0;
uint64_t local_vertex_id;
const int nchunks = 4 * omp_get_num_threads();
const int chunk_size = (n_local_vertices + nchunks - 1) /
nchunks;
if (put_delta > 100000) {
#pragma omp for schedule(dynamic,chunk_size)
for (local_vertex_id = 0;
local_vertex_id < n_local_vertices; local_vertex_id++) {
loop_body(verts, local_vertex_id, last_put_index,
local_vertex_offsets, neighbors, nglobalverts,
shared_visited, visited_ints, local_min_vertex,
local_visited, updating_index, &pe_plus_one,
&thread_natomics,
&thread_quiet_time, thread_ctxs,
natomics_issued, &curr_ctx_index);
}
} else {
#pragma omp for schedule(static)
for (local_vertex_id = 0;
local_vertex_id < n_local_vertices; local_vertex_id++) {
loop_body(verts, local_vertex_id, last_put_index,
local_vertex_offsets, neighbors, nglobalverts,
shared_visited, visited_ints, local_min_vertex,
local_visited, updating_index, &pe_plus_one,
&thread_natomics,
&thread_quiet_time, thread_ctxs,
natomics_issued, &curr_ctx_index);
}
}
const size_t min_byte_to_send = local_min_vertex / BITS_PER_BYTE;
const size_t max_byte_to_send = local_max_vertex / BITS_PER_BYTE;
const size_t bytes_to_send = max_byte_to_send - min_byte_to_send + 1;
char *my_visited = ((char *)shared_visited) + min_byte_to_send;
#pragma omp for schedule(static)
for (i = 0; i < npes - 1; i++) {
if (i >= pe) {
i = i + 1;
}
shmemx_ctx_putmem_nbi(my_visited, my_visited, bytes_to_send,
i, thread_ctxs[0]);
}
reduced_natomics += thread_natomics;
reduced_quiet_time += thread_quiet_time;
}
const unsigned long long end_kernel = current_time_ns();
*my_natomics += reduced_natomics;
*my_n_signalled = reduced_natomics;
shmem_int_sum_to_all(total_n_signalled, my_n_signalled, 1, 0, 0,
npes, pWrkInt, pSync);
const unsigned long long end_reduction = current_time_ns();
for (i = 0; i < CONTEXTS_PER_THREAD * nthreads; i++) {
shmemx_ctx_quiet(contexts[i]);
}
shmem_barrier_all();
const unsigned long long end_iter = current_time_ns();
printf("PE %d iter %d kernel = %f ms, reduce = %f ms, barrier = %f "
"ms, %d sends / %llu vertices, signalled = %d, %s, "
"quiet time = %f ms\n", pe, iter,
(double)(end_kernel - start_iter) / 1000000.0,
(double)(end_reduction - end_kernel) / 1000000.0,
(double)(end_iter - end_reduction) / 1000000.0,
reduced_natomics, nglobalverts, *total_n_signalled,
(put_delta > 100000 ? "dynamic" : "static"),
(double)reduced_quiet_time / 1000000.0);
// short *tmp = last_put;
// last_put = updating;
// updating = tmp;
iter++;
last_put_index = (last_put_index + 1) % 2;
prev_prev_put = prev_put;
prev_put = *total_n_signalled;
} while (*total_n_signalled > 0);
const unsigned long long end_bfs = current_time_ns();
// For debugging on small datasets, print results
// for (i = 0; i < nglobalverts; i++) {
// if (get_owner_pe(i, nglobalverts) == pe) {
// printf("Vertex %d : traversed by %d\n", i,
// first_traversed_by[i - local_min_vertex]);
// }
// shmem_barrier_all();
// }
// Lightweight validation
// int count_not_set = 0;
// int count_not_handled = 0;
// int count_set = 0;
// for (i = 0; i < n_local_vertices; i++) {
// const int curr = first_traversed_by[i];
// if (curr == 0) {
// count_not_set++;
// } else if (curr > 0) {
// count_not_handled++;
// } else {
// count_set++;
// }
// }
// fprintf(stderr, "PE %d, run %d : set %d , not set %d , unhandled %d\n",
// shmem_my_pe(), run, count_set, count_not_set, count_not_handled);
shmem_int_sum_to_all(total_natomics, my_natomics, 1, 0, 0,
npes, pWrkInt, pSync);
shmem_barrier_all();
if (pe == 0) {
fprintf(stderr, "BFS %d with root=%llu took %f ms, %d iters, %d atomics\n",
run, root, (double)(end_bfs - start_bfs) / 1000000.0,
iter, *total_natomics);
}
}
for (i = 0; i < nthreads; i++) {
shmemx_ctx_destroy(contexts[i]);
}
shmemx_domain_destroy(nthreads, domains);
shmem_finalize();
return 0;
}
|
p_kernel.c |
#include <petscmat.h>
#include <petscsnes.h>
#include <petscvec.h>
#include <omp.h>
#include <geometry.h>
#include <ktime.h>
#ifdef __USE_HW_COUNTER
#include <perf.h>
#include <kperf.h>
#endif
#include <kernel.h>
#include <phy.h>
/*
Evaluate Function F(x): Functional form used to convey the
nonlinear function to be solved by PETSc SNES
*/
int
ffunc(SNES snes, Vec x, Vec f, void *restrict ctx)
{
struct ctx *restrict c = (struct ctx *) ctx;
const size_t nnodes = c->g->n->sz;
const size_t bsz = c->g->c->bsz;
int ierr;
const double *restrict q;
ierr = VecGetArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
struct grad grad;
{
grad.bsz = c->g->c->bsz;
grad.dofs = c->g->c->sz;
grad.ie = c->g->s->ie;
grad.part = c->g->s->part;
grad.n0 = c->g->e->eptr->n0;
grad.n1 = c->g->e->eptr->n1;
grad.w0termsx = c->g->e->w->w0->x0;
grad.w0termsy = c->g->e->w->w0->x1;
grad.w0termsz = c->g->e->w->w0->x2;
grad.w1termsx = c->g->e->w->w1->x0;
grad.w1termsy = c->g->e->w->w1->x1;
grad.w1termsz = c->g->e->w->w1->x2;
grad.q = q;
grad.gradx0 = c->grad->x0;
grad.gradx1 = c->grad->x1;
grad.gradx2 = c->grad->x2;
grad.t = &c->t->grad;
#ifdef __USE_HW_COUNTER
grad.perf_counters = c->perf_counters;
#endif
}
compute_grad(&grad);
double *restrict r;
ierr = VecGetArray(f, (PetscScalar **) &r);
CHKERRQ(ierr);
struct flux flux;
{
flux.bsz = c->g->c->bsz;
flux.nfnodes = c->g->b->f->n->sz;
flux.dofs = c->g->c->sz;
flux.snfc = c->g->s->snfc;
flux.pressure = c->iv->p;
flux.velocity_u = c->iv->u;
flux.velocity_v = c->iv->v;
flux.velocity_w = c->iv->w;
flux.f_xyz0 = c->g->b->f->n->xyz->x0;
flux.f_xyz1 = c->g->b->f->n->xyz->x1;
flux.f_xyz2 = c->g->b->f->n->xyz->x2;
flux.xyz0 = c->g->n->xyz->x0;
flux.xyz1 = c->g->n->xyz->x1;
flux.xyz2 = c->g->n->xyz->x2;
flux.ie = c->g->s->ie;
flux.part = c->g->s->part;
flux.snfic = c->g->s->snfic;
flux.n0 = c->g->e->eptr->n0;
flux.n1 = c->g->e->eptr->n1;
flux.nfptr = c->g->b->f->n->nptr;
flux.sn0 = c->g->b->snfptr->n0;
flux.sn1 = c->g->b->snfptr->n1;
flux.sn2 = c->g->b->snfptr->n2;
flux.x0 = c->g->e->xyzn->x0;
flux.x1 = c->g->e->xyzn->x1;
flux.x2 = c->g->e->xyzn->x2;
flux.x3 = c->g->e->xyzn->x3;
flux.q = q;
flux.gradx0 = c->grad->x0;
flux.gradx1 = c->grad->x1;
flux.gradx2 = c->grad->x2;
flux.r = r;
flux.t = &c->t->flux;
#ifdef __USE_HW_COUNTER
flux.perf_counters = c->perf_counters;
#endif
}
compute_flux(&flux);
#ifdef __USE_MAN_FLOPS_COUNTER
uint64_t grad_flops = 56 * c->g->e->sz;
uint64_t flux_flops = 0;
flux_flops += 335 * c->g->e->sz;
flux_flops += 53 * c->g->b->s->f->sz;
flux_flops += 210 * c->g->b->f->n->sz;
c->t->flux.flops += flux_flops;
c->t->grad.flops += grad_flops;
#endif
#ifdef __USE_HW_COUNTER
const struct fd fd = c->perf_counters->fd;
struct counters start;
perf_read(fd, &start);
const uint64_t icycle = __rdtsc();
#endif
struct ktime ktime;
setktime(&ktime);
const double *restrict q_;
ierr = VecGetArrayRead(c->ts->q, (const PetscScalar **) &q_);
CHKERRQ(ierr);
const double *restrict area = c->g->n->area;
double *restrict cdt = c->ts->cdt;
const double cfl = c->ts->cfl;
uint32_t i;
#pragma omp parallel for
for(i = 0; i < nnodes; i++)
{
const double t = area[i] / (cfl * cdt[i]);
const uint32_t idx = bsz * i;
r[idx + 0] += t * (q[idx + 0] - q_[idx + 0]);
r[idx + 1] += t * (q[idx + 1] - q_[idx + 1]);
r[idx + 2] += t * (q[idx + 2] - q_[idx + 2]);
r[idx + 3] += t * (q[idx + 3] - q_[idx + 3]);
}
ierr = VecRestoreArrayRead(c->ts->q, (const PetscScalar **) &q_);
CHKERRQ(ierr);
compute_time(&ktime, &c->t->tstep_contr);
ierr = VecRestoreArray(f, (PetscScalar **) &r);
CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
#ifdef __USE_HW_COUNTER
const uint64_t cycle = __rdtsc() - icycle;
struct counters end;
perf_read(fd, &end);
struct tot tot;
perf_calc(start, end, &tot);
c->perf_counters->ctrs->timestep.cycles += cycle;
c->perf_counters->ctrs->timestep.tot.imcR += tot.imcR;
c->perf_counters->ctrs->timestep.tot.imcW += tot.imcW;
c->perf_counters->ctrs->timestep.tot.edcR += tot.edcR;
c->perf_counters->ctrs->timestep.tot.edcW += tot.edcW;
#endif
return 0;
}
/*
Function used to convey the nonlinear Jacobian of the
function to be solved by SNES
Evaluate Jacobian F'(x)
Input vector; matrix that defines the approximate Jacobian;
matrix to be used to construct the preconditioner;
flag indicating information about the preconditioner matrix structure
user-defined context
*/
int
jfunc(SNES snes, Vec x, Mat Amat, Mat Pmat, void *restrict ctx)
{
struct ctx *restrict c = (struct ctx *) ctx;
/*
Resets a factored matrix to be treated as unfactored
*/
int ierr;
ierr = MatSetUnfactored(Pmat);
CHKERRQ(ierr);
const double *restrict q;
ierr = VecGetArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
/*
Fill the nonzero term of the A matrix
*/
struct fill fill;
{
fill.q = q;
fill.g = c->g;
fill.ts = c->ts;
fill.iv = c->iv;
fill.A = Pmat;
fill.t = c->t;
#ifdef __USE_HW_COUNTER
fill.perf_counters = c->perf_counters;
#endif
}
ierr = fill_mat(&fill);
CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, (const PetscScalar **) &q);
CHKERRQ(ierr);
ierr = MatAssemblyBegin(Amat, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
ierr = MatAssemblyEnd(Amat, MAT_FINAL_ASSEMBLY);
CHKERRQ(ierr);
return 0;
}
|
geckoDataTypeGenerator.h | //
// Created by millad on 7/23/18.
//
#ifndef GECKO_GECKODATATYPEGENERATOR_H
#define GECKO_GECKODATATYPEGENERATOR_H
#include <vector>
#include <stdlib.h>
//#define CUDA_ENABLED
#ifdef CUDA_ENABLED
#include <cuda_runtime.h>
#endif
#include <openacc.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include "geckoUtils.h"
using namespace std;
typedef enum {
GECKO_GENERATOR_HOST = 0,
GECKO_GENERATOR_GPU,
GECKO_GENERATOR_UNIFIED,
GECKO_GENERATOR_UNKNOWN,
GECKO_GENERATOR_LEN
}GeckoGeneratorMemoryType;
class gecko_type_base {
protected:
size_t *total_count;
size_t *count_per_dev;
int *dev_count;
GeckoGeneratorMemoryType mem_type;
int sizes_in_byte[2];
int *dev_list;
void *alloc(GeckoGeneratorMemoryType mem_type, int datasize, int count);
void freeMemBase(void **arr);
public:
void setDevList(vector<int> dl);
virtual void allocateMemOnlyHost(size_t count) = 0;
virtual void allocateMemOnlyGPU(size_t count) = 0;
virtual void allocateMemUnifiedMem(size_t count) = 0;
virtual void allocateMem(size_t count, vector<int> &dl) = 0;
virtual void freeMem() = 0;
};
template<class Type>
class gecko_generator : public gecko_type_base {
public:
Type **arr;
gecko_generator<Type>() : arr(NULL) {
mem_type = GECKO_GENERATOR_UNKNOWN;
sizes_in_byte[0] = sizeof(Type);
sizes_in_byte[1] = sizeof(Type*);
GECKO_CUDA_CHECK(cudaMallocManaged((void**) &total_count, sizeof(size_t)));
cudaMallocManaged((void**) &count_per_dev, sizeof(size_t));
cudaMallocManaged((void**) &dev_count, sizeof(int));
}
~gecko_generator<Type>() {
}
//#pragma acc routine seq
Type &operator[] (size_t index) {
int new_index = index % (*count_per_dev);
int dev_id = index / (*count_per_dev);
if(dev_id>=*dev_count) {
dev_id = *dev_count - 1;
//i new_index += *count_per_dev;
new_index = index - dev_id*(*count_per_dev);
}
Type *d = arr[dev_id];
return d[new_index];
//#endif
}
Type *operator+ (int index) {
return &operator[](index);
}
void allocateMemOnlyHost(size_t count) {
mem_type = GECKO_GENERATOR_HOST;
*count_per_dev = count;
*total_count = count;
*dev_count = 1;
arr = (Type**) malloc(sizeof(Type*) * *dev_count);
arr[0] = (Type*) malloc(sizeof(Type) * *count_per_dev);
}
void allocateMemOnlyGPU(size_t count) {
if(true) {
allocateMemUnifiedMem(count);
return;
}
// mem_type = GECKO_GENERATOR_GPU;
// count_per_dev = count;
// dev_count = 1;
// arr = (Type**) malloc(sizeof(Type*) * dev_count);
// cudaMalloc((void**) &arr[0], sizeof(Type) * count_per_dev);
}
void allocateMemUnifiedMem(size_t count) {
mem_type = GECKO_GENERATOR_UNIFIED;
*count_per_dev = count / *dev_count;
*total_count = count;
int curr_dev = acc_get_device_num(acc_device_nvidia);
acc_set_device_num(0, acc_device_nvidia);
GECKO_CUDA_CHECK(cudaMallocManaged((void***) &arr, sizeof(Type*) * *dev_count));
//for(int i=0;i<*dev_count;i++) {
#pragma omp parallel num_threads(*dev_count)
{
int i = omp_get_thread_num();
int dev_id = dev_list[i];
size_t count_per_dev_refined = *count_per_dev;
if(i == *dev_count-1)
count_per_dev_refined = *total_count - i*(*count_per_dev);
if(dev_id != cudaCpuDeviceId)
acc_set_device_num(dev_id, acc_device_nvidia);
else
acc_set_device_num(0, acc_device_host);
void *a = NULL;
#ifdef CUDA_ENABLED
// printf("==============================FROM HELL\n");
GECKO_CUDA_CHECK(cudaMallocManaged((void**) &a, sizeof(Type) * count_per_dev_refined));
// printf("==============================FROM HELL 2 - array_count: %d - DEV_COUNT: %d\n", count_per_dev_refined, *dev_count);
#endif
#pragma acc wait
arr[i] = (Type*) a;
// printf("==============================FROM HELL 2 - A\n");
#ifdef INFO
fprintf(stderr, "===GECKO: COUNT_PER_DEV - %s: %d\n", (dev_id == -1 ? "CPU" : "GPU"), count_per_dev_refined);
#endif
}
// printf("==============================FROM HELL 3\n");
/*
for(int i=0;i<*dev_count;i++) {
int dev_id = dev_list[i];
GECKO_CUDA_CHECK(cudaMemAdvise(&arr[dev_id], sizeof(Type **) * *dev_count, cudaMemAdviseSetReadMostly, dev_id));
}
*/
// printf("==============================FROM HELL 4\n");
acc_set_device_num(curr_dev, acc_device_nvidia);
// printf("==============================FROM HELL 5\n");
}
void allocateMem(size_t count, vector<int> &dl) {
setDevList(dl);
allocateMemUnifiedMem(count);
}
void freeMem() {
cudaFree(total_count);
cudaFree(count_per_dev);
cudaFree(dev_count);
freeMemBase((void**)arr);
}
};
#define G_GENERATOR(TYPE) typedef gecko_generator<TYPE> gecko_##TYPE
G_GENERATOR(char);
G_GENERATOR(int);
G_GENERATOR(long);
G_GENERATOR(float);
G_GENERATOR(double);
G_GENERATOR(bool);
typedef gecko_generator<unsigned int> gecko_unsigned_int;
#endif //GECKO_GECKODATATYPEGENERATOR_H
|
master-worker-omp.c | # include <stdio.h>
# include <stdlib.h>
# include <omp.h>
struct {
int maxtask;
int task;
} taskinfo = { 0, 0 };
void work(void);
void get_task(int *nexttask);
int main(int argc, char *argv[])
{
taskinfo.maxtask = 40;
#pragma omp parallel
work();
return 0;
}
void get_task(int *nexttask)
{
#pragma omp critical
{
if (taskinfo.task < taskinfo.maxtask) {
++taskinfo.task;
*nexttask = taskinfo.task;
} else {
*nexttask = -1;
}
}
}
void work(void)
{
int task;
do
{
get_task(&task);
if (task >= 0)
{
printf("thread %d: working on task %d\n",
(int) omp_get_thread_num(), task);
system("sleep 1");
}
}
while (task >= 0);
}
|
TailLenSoftMax.c | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/TailLenSoftMax.c"
#else
void THLENN_(TailLenSoftMax_updateOutput)(
THLENNState *state,
THTensor *input,
THTensor *output,
THIndexTensor *len)
{
if ((input->nDimension != 2) && (len->nDimension != 1))
{
THArgCheck(0, 2, "2D tensor expected for input, 1D tensor expected for len");
}
real *input_data, *output_data;
THIndex_t *len_data;
ptrdiff_t nframe = input->size[0], dim = input->size[1];
ptrdiff_t t;
input = THTensor_(newContiguous)(input);
THTensor_(resizeAs)(output, input);
input_data = THTensor_(data)(input);
output_data = THTensor_(data)(output);
len_data = THIndexTensor_(data)(len);
#pragma omp parallel for private(t)
for (t = 0; t < nframe; t++)
{
real *input_ptr = input_data + t*dim;
real *output_ptr = output_data + t*dim;
real inputMax = -THInf;
accreal sum;
ptrdiff_t d, ld = dim - (ptrdiff_t)len_data[t];
for (d = ld; d < dim; d++)
{
if (input_ptr[d] >= inputMax) inputMax = input_ptr[d];
}
sum = 0;
for (d = ld; d < dim; d++)
{
real z = exp(input_ptr[d] - inputMax);
output_ptr[d] = z;
sum += z;
}
for (d = 0; d < ld; d++)
{
output_ptr[d] = 0;
}
for (d = ld; d < dim; d++)
{
output_ptr[d] *= 1/sum;
}
}
THTensor_(free)(input);
}
void THLENN_(TailLenSoftMax_updateGradInput)(
THLENNState *state,
THTensor *input,
THTensor *gradOutput,
THTensor *gradInput,
THTensor *output,
THIndexTensor *len)
{
THNN_CHECK_SHAPE(input, gradOutput);
if ((output->nDimension != 2) && (len->nDimension != 1))
{
THError("2D tensor expected for input, 1D tensor expected for len");
}
real *gradInput_data, *gradOutput_data, *output_data;
THIndex_t *len_data;
ptrdiff_t nframe = output->size[0], dim = output->size[1];
ptrdiff_t t;
gradOutput = THTensor_(newContiguous)(gradOutput);
output = THTensor_(newContiguous)(output);
THTensor_(resizeAs)(gradInput, output);
gradInput_data = THTensor_(data)(gradInput);
output_data = THTensor_(data)(output);
gradOutput_data = THTensor_(data)(gradOutput);
len_data = THIndexTensor_(data)(len);
#pragma omp parallel for private(t)
for (t = 0; t < nframe; t++)
{
real *gradInput_ptr = gradInput_data + t*dim;
real *output_ptr = output_data + t*dim;
real *gradOutput_ptr = gradOutput_data + t*dim;
ptrdiff_t d, ld = dim - (ptrdiff_t)len_data[t];
accreal sum = 0;
for (d = ld; d < dim; d++)
sum += (accreal)gradOutput_ptr[d] * output_ptr[d];
for (d = ld; d < dim; d++)
gradInput_ptr[d] = output_ptr[d] * (gradOutput_ptr[d] - sum);
for (d = 0; d < ld; d++)
gradInput_ptr[d] = 0;
}
THTensor_(free)(gradOutput);
THTensor_(free)(output);
}
#endif
|
base_ptr_ref_count.c | // RUN: %libomptarget-compile-aarch64-unknown-linux-gnu && env LIBOMPTARGET_DEBUG=1 %libomptarget-run-aarch64-unknown-linux-gnu 2>&1 | %fcheck-aarch64-unknown-linux-gnu
// RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu && env LIBOMPTARGET_DEBUG=1 %libomptarget-run-powerpc64-ibm-linux-gnu 2>&1 | %fcheck-powerpc64-ibm-linux-gnu
// RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu && env LIBOMPTARGET_DEBUG=1 %libomptarget-run-powerpc64le-ibm-linux-gnu 2>&1 | %fcheck-powerpc64le-ibm-linux-gnu
// RUN: %libomptarget-compile-x86_64-pc-linux-gnu && env LIBOMPTARGET_DEBUG=1 %libomptarget-run-x86_64-pc-linux-gnu 2>&1 | %fcheck-x86_64-pc-linux-gnu
// RUN: %libomptarget-compile-nvptx64-nvidia-cuda && env LIBOMPTARGET_DEBUG=1 %libomptarget-run-nvptx64-nvidia-cuda 2>&1 | %fcheck-nvptx64-nvidia-cuda
// REQUIRES: libomptarget-debug
#include <stdlib.h>
int *allocate(size_t n) {
int *ptr = malloc(sizeof(int) * n);
#pragma omp target enter data map(to : ptr[:n])
return ptr;
}
void deallocate(int *ptr, size_t n) {
#pragma omp target exit data map(delete : ptr[:n])
free(ptr);
}
#pragma omp declare target
int *cnt;
void foo() {
++(*cnt);
}
#pragma omp end declare target
int main(void) {
int *A = allocate(10);
int *V = allocate(10);
deallocate(A, 10);
deallocate(V, 10);
// CHECK-NOT: RefCount=2
cnt = malloc(sizeof(int));
*cnt = 0;
#pragma omp target map(cnt[:1])
foo();
printf("Cnt = %d.\n", *cnt);
// CHECK: Cnt = 1.
*cnt = 0;
#pragma omp target data map(cnt[:1])
#pragma omp target
foo();
printf("Cnt = %d.\n", *cnt);
// CHECK: Cnt = 1.
free(cnt);
return 0;
}
|
pdplgsy.c | /**
*
* @file pdplgsy.c
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:45:12 2014
*
**/
#include "common.h"
#if defined(USE_OMPEXT)
#include <omp_ext.h>
#endif
#define A(m,n) BLKADDR(A, double, m, n)
/***************************************************************************//**
* Parallel tile Cholesky factorization - dynamic scheduling
**/
void plasma_pdplgsy_quark( double bump, PLASMA_desc A, unsigned long long int seed)
{
int m, n;
int ldam;
int tempmm, tempnn;
for (m = 0; m < A.mt; m++) {
tempmm = m == A.mt-1 ? A.m-m*A.mb : A.mb;
ldam = BLKLDD(A, m);
for (n = 0; n < A.nt; n++) {
tempnn = n == A.nt-1 ? A.n-n*A.nb : A.nb;
double *dA = A(m, n);
#if defined(USE_OMPEXT)
omp_set_task_affinity( (n%4)*6+(m%6) );
#endif
#pragma omp task depend(out:dA[0:ldam*tempnn])
CORE_dplgsy( bump, tempmm, tempnn, dA, ldam, A.m, m*A.mb, n*A.nb, seed );
}
}
}
|
_kdtree_core.c | /*
pykdtree, Fast kd-tree implementation with OpenMP-enabled queries
Copyright (C) 2013 - present Esben S. Nielsen
This program 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.
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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
This kd-tree implementation is based on the scipy.spatial.cKDTree by
Anne M. Archibald and libANN by David M. Mount and Sunil Arya.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <float.h>
#define PA(i,d) (pa[no_dims * pidx[i] + d])
#define PASWAP(a,b) { uint32_t tmp = pidx[a]; pidx[a] = pidx[b]; pidx[b] = tmp; }
#ifdef _MSC_VER
#define restrict __restrict
#endif
typedef struct
{
float cut_val;
int8_t cut_dim;
uint32_t start_idx;
uint32_t n;
float cut_bounds_lv;
float cut_bounds_hv;
struct Node_float *left_child;
struct Node_float *right_child;
} Node_float;
typedef struct
{
float *bbox;
int8_t no_dims;
uint32_t *pidx;
struct Node_float *root;
} Tree_float;
typedef struct
{
double cut_val;
int8_t cut_dim;
uint32_t start_idx;
uint32_t n;
double cut_bounds_lv;
double cut_bounds_hv;
struct Node_double *left_child;
struct Node_double *right_child;
} Node_double;
typedef struct
{
double *bbox;
int8_t no_dims;
uint32_t *pidx;
struct Node_double *root;
} Tree_double;
void insert_point_float(uint32_t *closest_idx, float *closest_dist, uint32_t pidx, float cur_dist, uint32_t k);
void get_bounding_box_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t n, float *bbox);
int partition_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *bbox, int8_t *cut_dim,
float *cut_val, uint32_t *n_lo);
Tree_float* construct_tree_float(float *pa, int8_t no_dims, uint32_t n, uint32_t bsp);
Node_float* construct_subtree_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, uint32_t bsp, float *bbox);
Node_float * create_node_float(uint32_t start_idx, uint32_t n, int is_leaf);
void delete_subtree_float(Node_float *root);
void delete_tree_float(Tree_float *tree);
void print_tree_float(Node_float *root, int level);
float calc_dist_float(float *point1_coord, float *point2_coord, int8_t no_dims);
float get_cube_offset_float(int8_t dim, float *point_coord, float *bbox);
float get_min_dist_float(float *point_coord, int8_t no_dims, float *bbox);
void search_leaf_float(float *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *restrict point_coord,
uint32_t k, uint32_t *restrict closest_idx, float *restrict closest_dist);
void search_leaf_float_mask(float *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *restrict point_coord,
uint32_t k, uint8_t *restrict mask, uint32_t *restrict closest_idx, float *restrict closest_dist);
void search_splitnode_float(Node_float *root, float *pa, uint32_t *pidx, int8_t no_dims, float *point_coord,
float min_dist, uint32_t k, float distance_upper_bound, float eps_fac, uint8_t *mask, uint32_t * closest_idx, float *closest_dist);
void search_tree_float(Tree_float *tree, float *pa, float *point_coords,
uint32_t num_points, uint32_t k, float distance_upper_bound,
float eps, uint8_t *mask, uint32_t *closest_idxs, float *closest_dists);
void insert_point_double(uint32_t *closest_idx, double *closest_dist, uint32_t pidx, double cur_dist, uint32_t k);
void get_bounding_box_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t n, double *bbox);
int partition_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *bbox, int8_t *cut_dim,
double *cut_val, uint32_t *n_lo);
Tree_double* construct_tree_double(double *pa, int8_t no_dims, uint32_t n, uint32_t bsp);
Node_double* construct_subtree_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, uint32_t bsp, double *bbox);
Node_double * create_node_double(uint32_t start_idx, uint32_t n, int is_leaf);
void delete_subtree_double(Node_double *root);
void delete_tree_double(Tree_double *tree);
void print_tree_double(Node_double *root, int level);
double calc_dist_double(double *point1_coord, double *point2_coord, int8_t no_dims);
double get_cube_offset_double(int8_t dim, double *point_coord, double *bbox);
double get_min_dist_double(double *point_coord, int8_t no_dims, double *bbox);
void search_leaf_double(double *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *restrict point_coord,
uint32_t k, uint32_t *restrict closest_idx, double *restrict closest_dist);
void search_leaf_double_mask(double *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *restrict point_coord,
uint32_t k, uint8_t *restrict mask, uint32_t *restrict closest_idx, double *restrict closest_dist);
void search_splitnode_double(Node_double *root, double *pa, uint32_t *pidx, int8_t no_dims, double *point_coord,
double min_dist, uint32_t k, double distance_upper_bound, double eps_fac, uint8_t *mask, uint32_t * closest_idx, double *closest_dist);
void search_tree_double(Tree_double *tree, double *pa, double *point_coords,
uint32_t num_points, uint32_t k, double distance_upper_bound,
double eps, uint8_t *mask, uint32_t *closest_idxs, double *closest_dists);
/************************************************
Insert point into priority queue
Params:
closest_idx : index queue
closest_dist : distance queue
pidx : permutation index of data points
cur_dist : distance to point inserted
k : number of neighbours
************************************************/
void insert_point_float(uint32_t *closest_idx, float *closest_dist, uint32_t pidx, float cur_dist, uint32_t k)
{
int i;
for (i = k - 1; i > 0; i--)
{
if (closest_dist[i - 1] > cur_dist)
{
closest_dist[i] = closest_dist[i - 1];
closest_idx[i] = closest_idx[i - 1];
}
else
{
break;
}
}
closest_idx[i] = pidx;
closest_dist[i] = cur_dist;
}
/************************************************
Get the bounding box of a set of points
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
n : number of points
bbox : bounding box (return)
************************************************/
void get_bounding_box_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t n, float *bbox)
{
float cur;
int8_t i, j;
uint32_t bbox_idx, i2;
/* Use first data point to initialize */
for (i = 0; i < no_dims; i++)
{
bbox[2 * i] = bbox[2 * i + 1] = PA(0, i);
}
/* Update using rest of data points */
for (i2 = 1; i2 < n; i2++)
{
for (j = 0; j < no_dims; j++)
{
bbox_idx = 2 * j;
cur = PA(i2, j);
if (cur < bbox[bbox_idx])
{
bbox[bbox_idx] = cur;
}
else if (cur > bbox[bbox_idx + 1])
{
bbox[bbox_idx + 1] = cur;
}
}
}
}
/************************************************
Partition a range of data points by manipulation the permutation index.
The sliding midpoint rule is used for the partitioning.
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
start_idx : index of first data point to use
n : number of data points
bbox : bounding box of data points
cut_dim : dimension used for partition (return)
cut_val : value of cutting point (return)
n_lo : number of point below cutting plane (return)
************************************************/
int partition_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *bbox, int8_t *cut_dim, float *cut_val, uint32_t *n_lo)
{
int8_t dim = 0, i;
uint32_t p, q, i2;
float size = 0, min_val, max_val, split, side_len, cur_val;
uint32_t end_idx = start_idx + n - 1;
/* Find largest bounding box side */
for (i = 0; i < no_dims; i++)
{
side_len = bbox[2 * i + 1] - bbox[2 * i];
if (side_len > size)
{
dim = i;
size = side_len;
}
}
min_val = bbox[2 * dim];
max_val = bbox[2 * dim + 1];
/* Check for zero length or inconsistent */
if (min_val >= max_val)
return 1;
/* Use middle for splitting */
split = (min_val + max_val) / 2;
/* Partition all data points around middle */
p = start_idx;
q = end_idx;
while (p <= q)
{
if (PA(p, dim) < split)
{
p++;
}
else if (PA(q, dim) >= split)
{
/* Guard for underflow */
if (q > 0)
{
q--;
}
else
{
break;
}
}
else
{
PASWAP(p, q);
p++;
q--;
}
}
/* Check for empty splits */
if (p == start_idx)
{
/* No points less than split.
Split at lowest point instead.
Minimum 1 point will be in lower box.
*/
uint32_t j = start_idx;
split = PA(j, dim);
for (i2 = start_idx + 1; i2 <= end_idx; i2++)
{
/* Find lowest point */
cur_val = PA(i2, dim);
if (cur_val < split)
{
j = i2;
split = cur_val;
}
}
PASWAP(j, start_idx);
p = start_idx + 1;
}
else if (p == end_idx + 1)
{
/* No points greater than split.
Split at highest point instead.
Minimum 1 point will be in higher box.
*/
uint32_t j = end_idx;
split = PA(j, dim);
for (i2 = start_idx; i2 < end_idx; i2++)
{
/* Find highest point */
cur_val = PA(i2, dim);
if (cur_val > split)
{
j = i2;
split = cur_val;
}
}
PASWAP(j, end_idx);
p = end_idx;
}
/* Set return values */
*cut_dim = dim;
*cut_val = split;
*n_lo = p - start_idx;
return 0;
}
/************************************************
Construct a sub tree over a range of data points.
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
start_idx : index of first data point to use
n : number of data points
bsp : number of points per leaf
bbox : bounding box of set of data points
************************************************/
Node_float* construct_subtree_float(float *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, uint32_t bsp, float *bbox)
{
/* Create new node */
int is_leaf = (n <= bsp);
Node_float *root = create_node_float(start_idx, n, is_leaf);
int rval;
int8_t cut_dim;
uint32_t n_lo;
float cut_val, lv, hv;
if (is_leaf)
{
/* Make leaf node */
root->cut_dim = -1;
}
else
{
/* Make split node */
/* Partition data set and set node info */
rval = partition_float(pa, pidx, no_dims, start_idx, n, bbox, &cut_dim, &cut_val, &n_lo);
if (rval == 1)
{
root->cut_dim = -1;
return root;
}
root->cut_val = cut_val;
root->cut_dim = cut_dim;
/* Recurse on both subsets */
lv = bbox[2 * cut_dim];
hv = bbox[2 * cut_dim + 1];
/* Set bounds for cut dimension */
root->cut_bounds_lv = lv;
root->cut_bounds_hv = hv;
/* Update bounding box before call to lower subset and restore after */
bbox[2 * cut_dim + 1] = cut_val;
root->left_child = (struct Node_float *)construct_subtree_float(pa, pidx, no_dims, start_idx, n_lo, bsp, bbox);
bbox[2 * cut_dim + 1] = hv;
/* Update bounding box before call to higher subset and restore after */
bbox[2 * cut_dim] = cut_val;
root->right_child = (struct Node_float *)construct_subtree_float(pa, pidx, no_dims, start_idx + n_lo, n - n_lo, bsp, bbox);
bbox[2 * cut_dim] = lv;
}
return root;
}
/************************************************
Construct a tree over data points.
Params:
pa : data points
no_dims: number of dimensions
n : number of data points
bsp : number of points per leaf
************************************************/
Tree_float* construct_tree_float(float *pa, int8_t no_dims, uint32_t n, uint32_t bsp)
{
Tree_float *tree = (Tree_float *)malloc(sizeof(Tree_float));
uint32_t i;
uint32_t *pidx;
float *bbox;
tree->no_dims = no_dims;
/* Initialize permutation array */
pidx = (uint32_t *)malloc(sizeof(uint32_t) * n);
for (i = 0; i < n; i++)
{
pidx[i] = i;
}
bbox = (float *)malloc(2 * sizeof(float) * no_dims);
get_bounding_box_float(pa, pidx, no_dims, n, bbox);
tree->bbox = bbox;
/* Construct subtree on full dataset */
tree->root = (struct Node_float *)construct_subtree_float(pa, pidx, no_dims, 0, n, bsp, bbox);
tree->pidx = pidx;
return tree;
}
/************************************************
Create a tree node.
Params:
start_idx : index of first data point to use
n : number of data points
************************************************/
Node_float* create_node_float(uint32_t start_idx, uint32_t n, int is_leaf)
{
Node_float *new_node;
if (is_leaf)
{
/*
Allocate only the part of the struct that will be used in a leaf node.
This relies on the C99 specification of struct layout conservation and padding and
that dereferencing is never attempted for the node pointers in a leaf.
*/
new_node = (Node_float *)malloc(sizeof(Node_float) - 2 * sizeof(Node_float *));
}
else
{
new_node = (Node_float *)malloc(sizeof(Node_float));
}
new_node->n = n;
new_node->start_idx = start_idx;
return new_node;
}
/************************************************
Delete subtree
Params:
root : root node of subtree to delete
************************************************/
void delete_subtree_float(Node_float *root)
{
if (root->cut_dim != -1)
{
delete_subtree_float((Node_float *)root->left_child);
delete_subtree_float((Node_float *)root->right_child);
}
free(root);
}
/************************************************
Delete tree
Params:
tree : Tree struct of kd tree
************************************************/
void delete_tree_float(Tree_float *tree)
{
delete_subtree_float((Node_float *)tree->root);
free(tree->bbox);
free(tree->pidx);
free(tree);
}
/************************************************
Print
************************************************/
void print_tree_float(Node_float *root, int level)
{
int i;
for (i = 0; i < level; i++)
{
printf(" ");
}
printf("(cut_val: %f, cut_dim: %i)\n", root->cut_val, root->cut_dim);
if (root->cut_dim != -1)
print_tree_float((Node_float *)root->left_child, level + 1);
if (root->cut_dim != -1)
print_tree_float((Node_float *)root->right_child, level + 1);
}
/************************************************
Calculate squared cartesian distance between points
Params:
point1_coord : point 1
point2_coord : point 2
************************************************/
float calc_dist_float(float *point1_coord, float *point2_coord, int8_t no_dims)
{
/* Calculate squared distance */
float dist = 0, dim_dist;
int8_t i;
for (i = 0; i < no_dims; i++)
{
dim_dist = point2_coord[i] - point1_coord[i];
dist += dim_dist * dim_dist;
}
return dist;
}
/************************************************
Get squared distance from point to cube in specified dimension
Params:
dim : dimension
point_coord : cartesian coordinates of point
bbox : cube
************************************************/
float get_cube_offset_float(int8_t dim, float *point_coord, float *bbox)
{
float dim_coord = point_coord[dim];
if (dim_coord < bbox[2 * dim])
{
/* Left of cube in dimension */
return dim_coord - bbox[2 * dim];
}
else if (dim_coord > bbox[2 * dim + 1])
{
/* Right of cube in dimension */
return dim_coord - bbox[2 * dim + 1];
}
else
{
/* Inside cube in dimension */
return 0.;
}
}
/************************************************
Get minimum squared distance between point and cube.
Params:
point_coord : cartesian coordinates of point
no_dims : number of dimensions
bbox : cube
************************************************/
float get_min_dist_float(float *point_coord, int8_t no_dims, float *bbox)
{
float cube_offset = 0, cube_offset_dim;
int8_t i;
for (i = 0; i < no_dims; i++)
{
cube_offset_dim = get_cube_offset_float(i, point_coord, bbox);
cube_offset += cube_offset_dim * cube_offset_dim;
}
return cube_offset;
}
/************************************************
Search a leaf node for closest point
Params:
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
start_idx : index of first data point to use
size : number of data points
point_coord : query point
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_leaf_float(float *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *restrict point_coord,
uint32_t k, uint32_t *restrict closest_idx, float *restrict closest_dist)
{
float cur_dist;
uint32_t i;
/* Loop through all points in leaf */
for (i = 0; i < n; i++)
{
/* Get distance to query point */
cur_dist = calc_dist_float(&PA(start_idx + i, 0), point_coord, no_dims);
/* Update closest info if new point is closest so far*/
if (cur_dist < closest_dist[k - 1])
{
insert_point_float(closest_idx, closest_dist, pidx[start_idx + i], cur_dist, k);
}
}
}
/************************************************
Search a leaf node for closest point with data point mask
Params:
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
start_idx : index of first data point to use
size : number of data points
point_coord : query point
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_leaf_float_mask(float *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, float *restrict point_coord,
uint32_t k, uint8_t *mask, uint32_t *restrict closest_idx, float *restrict closest_dist)
{
float cur_dist;
uint32_t i;
/* Loop through all points in leaf */
for (i = 0; i < n; i++)
{
/* Is this point masked out? */
if (mask[pidx[start_idx + i]])
{
continue;
}
/* Get distance to query point */
cur_dist = calc_dist_float(&PA(start_idx + i, 0), point_coord, no_dims);
/* Update closest info if new point is closest so far*/
if (cur_dist < closest_dist[k - 1])
{
insert_point_float(closest_idx, closest_dist, pidx[start_idx + i], cur_dist, k);
}
}
}
/************************************************
Search subtree for nearest to query point
Params:
root : root node of subtree
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
point_coord : query point
min_dist : minumum distance to nearest neighbour
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_splitnode_float(Node_float *root, float *pa, uint32_t *pidx, int8_t no_dims, float *point_coord,
float min_dist, uint32_t k, float distance_upper_bound, float eps_fac, uint8_t *mask,
uint32_t *closest_idx, float *closest_dist)
{
int8_t dim;
float dist_left, dist_right;
float new_offset;
float box_diff;
/* Skip if distance bound exeeded */
if (min_dist > distance_upper_bound)
{
return;
}
dim = root->cut_dim;
/* Handle leaf node */
if (dim == -1)
{
if (mask)
{
search_leaf_float_mask(pa, pidx, no_dims, root->start_idx, root->n, point_coord, k, mask, closest_idx, closest_dist);
}
else
{
search_leaf_float(pa, pidx, no_dims, root->start_idx, root->n, point_coord, k, closest_idx, closest_dist);
}
return;
}
/* Get distance to cutting plane */
new_offset = point_coord[dim] - root->cut_val;
if (new_offset < 0)
{
/* Left of cutting plane */
dist_left = min_dist;
if (dist_left < closest_dist[k - 1] * eps_fac)
{
/* Search left subtree if minimum distance is below limit */
search_splitnode_float((Node_float *)root->left_child, pa, pidx, no_dims, point_coord, dist_left, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
/* Right of cutting plane. Update minimum distance.
See Algorithms for Fast Vector Quantization
Sunil Arya and David M. Mount. */
box_diff = root->cut_bounds_lv - point_coord[dim];
if (box_diff < 0)
{
box_diff = 0;
}
dist_right = min_dist - box_diff * box_diff + new_offset * new_offset;
if (dist_right < closest_dist[k - 1] * eps_fac)
{
/* Search right subtree if minimum distance is below limit*/
search_splitnode_float((Node_float *)root->right_child, pa, pidx, no_dims, point_coord, dist_right, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
}
else
{
/* Right of cutting plane */
dist_right = min_dist;
if (dist_right < closest_dist[k - 1] * eps_fac)
{
/* Search right subtree if minimum distance is below limit*/
search_splitnode_float((Node_float *)root->right_child, pa, pidx, no_dims, point_coord, dist_right, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
/* Left of cutting plane. Update minimum distance.
See Algorithms for Fast Vector Quantization
Sunil Arya and David M. Mount. */
box_diff = point_coord[dim] - root->cut_bounds_hv;
if (box_diff < 0)
{
box_diff = 0;
}
dist_left = min_dist - box_diff * box_diff + new_offset * new_offset;
if (dist_left < closest_dist[k - 1] * eps_fac)
{
/* Search left subtree if minimum distance is below limit*/
search_splitnode_float((Node_float *)root->left_child, pa, pidx, no_dims, point_coord, dist_left, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
}
}
/************************************************
Search for nearest neighbour for a set of query points
Params:
tree : Tree struct of kd tree
pa : data points
pidx : permutation index of data points
point_coords : query points
num_points : number of query points
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_tree_float(Tree_float *tree, float *pa, float *point_coords,
uint32_t num_points, uint32_t k, float distance_upper_bound,
float eps, uint8_t *mask, uint32_t *closest_idxs, float *closest_dists)
{
float min_dist;
float eps_fac = 1 / ((1 + eps) * (1 + eps));
int8_t no_dims = tree->no_dims;
float *bbox = tree->bbox;
uint32_t *pidx = tree->pidx;
uint32_t j = 0;
#if defined(_MSC_VER) && defined(_OPENMP)
int32_t i = 0;
int32_t local_num_points = (int32_t) num_points;
#else
uint32_t i;
uint32_t local_num_points = num_points;
#endif
Node_float *root = (Node_float *)tree->root;
/* Queries are OpenMP enabled */
#pragma omp parallel
{
/* The low chunk size is important to avoid L2 cache trashing
for spatial coherent query datasets
*/
#pragma omp for private(i, j) schedule(static, 100) nowait
for (i = 0; i < local_num_points; i++)
{
for (j = 0; j < k; j++)
{
closest_idxs[i * k + j] = UINT32_MAX;
closest_dists[i * k + j] = DBL_MAX;
}
min_dist = get_min_dist_float(point_coords + no_dims * i, no_dims, bbox);
search_splitnode_float(root, pa, pidx, no_dims, point_coords + no_dims * i, min_dist,
k, distance_upper_bound, eps_fac, mask, &closest_idxs[i * k], &closest_dists[i * k]);
}
}
}
/************************************************
Insert point into priority queue
Params:
closest_idx : index queue
closest_dist : distance queue
pidx : permutation index of data points
cur_dist : distance to point inserted
k : number of neighbours
************************************************/
void insert_point_double(uint32_t *closest_idx, double *closest_dist, uint32_t pidx, double cur_dist, uint32_t k)
{
int i;
for (i = k - 1; i > 0; i--)
{
if (closest_dist[i - 1] > cur_dist)
{
closest_dist[i] = closest_dist[i - 1];
closest_idx[i] = closest_idx[i - 1];
}
else
{
break;
}
}
closest_idx[i] = pidx;
closest_dist[i] = cur_dist;
}
/************************************************
Get the bounding box of a set of points
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
n : number of points
bbox : bounding box (return)
************************************************/
void get_bounding_box_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t n, double *bbox)
{
double cur;
int8_t i, j;
uint32_t bbox_idx, i2;
/* Use first data point to initialize */
for (i = 0; i < no_dims; i++)
{
bbox[2 * i] = bbox[2 * i + 1] = PA(0, i);
}
/* Update using rest of data points */
for (i2 = 1; i2 < n; i2++)
{
for (j = 0; j < no_dims; j++)
{
bbox_idx = 2 * j;
cur = PA(i2, j);
if (cur < bbox[bbox_idx])
{
bbox[bbox_idx] = cur;
}
else if (cur > bbox[bbox_idx + 1])
{
bbox[bbox_idx + 1] = cur;
}
}
}
}
/************************************************
Partition a range of data points by manipulation the permutation index.
The sliding midpoint rule is used for the partitioning.
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
start_idx : index of first data point to use
n : number of data points
bbox : bounding box of data points
cut_dim : dimension used for partition (return)
cut_val : value of cutting point (return)
n_lo : number of point below cutting plane (return)
************************************************/
int partition_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *bbox, int8_t *cut_dim, double *cut_val, uint32_t *n_lo)
{
int8_t dim = 0, i;
uint32_t p, q, i2;
double size = 0, min_val, max_val, split, side_len, cur_val;
uint32_t end_idx = start_idx + n - 1;
/* Find largest bounding box side */
for (i = 0; i < no_dims; i++)
{
side_len = bbox[2 * i + 1] - bbox[2 * i];
if (side_len > size)
{
dim = i;
size = side_len;
}
}
min_val = bbox[2 * dim];
max_val = bbox[2 * dim + 1];
/* Check for zero length or inconsistent */
if (min_val >= max_val)
return 1;
/* Use middle for splitting */
split = (min_val + max_val) / 2;
/* Partition all data points around middle */
p = start_idx;
q = end_idx;
while (p <= q)
{
if (PA(p, dim) < split)
{
p++;
}
else if (PA(q, dim) >= split)
{
/* Guard for underflow */
if (q > 0)
{
q--;
}
else
{
break;
}
}
else
{
PASWAP(p, q);
p++;
q--;
}
}
/* Check for empty splits */
if (p == start_idx)
{
/* No points less than split.
Split at lowest point instead.
Minimum 1 point will be in lower box.
*/
uint32_t j = start_idx;
split = PA(j, dim);
for (i2 = start_idx + 1; i2 <= end_idx; i2++)
{
/* Find lowest point */
cur_val = PA(i2, dim);
if (cur_val < split)
{
j = i2;
split = cur_val;
}
}
PASWAP(j, start_idx);
p = start_idx + 1;
}
else if (p == end_idx + 1)
{
/* No points greater than split.
Split at highest point instead.
Minimum 1 point will be in higher box.
*/
uint32_t j = end_idx;
split = PA(j, dim);
for (i2 = start_idx; i2 < end_idx; i2++)
{
/* Find highest point */
cur_val = PA(i2, dim);
if (cur_val > split)
{
j = i2;
split = cur_val;
}
}
PASWAP(j, end_idx);
p = end_idx;
}
/* Set return values */
*cut_dim = dim;
*cut_val = split;
*n_lo = p - start_idx;
return 0;
}
/************************************************
Construct a sub tree over a range of data points.
Params:
pa : data points
pidx : permutation index of data points
no_dims: number of dimensions
start_idx : index of first data point to use
n : number of data points
bsp : number of points per leaf
bbox : bounding box of set of data points
************************************************/
Node_double* construct_subtree_double(double *pa, uint32_t *pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, uint32_t bsp, double *bbox)
{
/* Create new node */
int is_leaf = (n <= bsp);
Node_double *root = create_node_double(start_idx, n, is_leaf);
int rval;
int8_t cut_dim;
uint32_t n_lo;
double cut_val, lv, hv;
if (is_leaf)
{
/* Make leaf node */
root->cut_dim = -1;
}
else
{
/* Make split node */
/* Partition data set and set node info */
rval = partition_double(pa, pidx, no_dims, start_idx, n, bbox, &cut_dim, &cut_val, &n_lo);
if (rval == 1)
{
root->cut_dim = -1;
return root;
}
root->cut_val = cut_val;
root->cut_dim = cut_dim;
/* Recurse on both subsets */
lv = bbox[2 * cut_dim];
hv = bbox[2 * cut_dim + 1];
/* Set bounds for cut dimension */
root->cut_bounds_lv = lv;
root->cut_bounds_hv = hv;
/* Update bounding box before call to lower subset and restore after */
bbox[2 * cut_dim + 1] = cut_val;
root->left_child = (struct Node_double *)construct_subtree_double(pa, pidx, no_dims, start_idx, n_lo, bsp, bbox);
bbox[2 * cut_dim + 1] = hv;
/* Update bounding box before call to higher subset and restore after */
bbox[2 * cut_dim] = cut_val;
root->right_child = (struct Node_double *)construct_subtree_double(pa, pidx, no_dims, start_idx + n_lo, n - n_lo, bsp, bbox);
bbox[2 * cut_dim] = lv;
}
return root;
}
/************************************************
Construct a tree over data points.
Params:
pa : data points
no_dims: number of dimensions
n : number of data points
bsp : number of points per leaf
************************************************/
Tree_double* construct_tree_double(double *pa, int8_t no_dims, uint32_t n, uint32_t bsp)
{
Tree_double *tree = (Tree_double *)malloc(sizeof(Tree_double));
uint32_t i;
uint32_t *pidx;
double *bbox;
tree->no_dims = no_dims;
/* Initialize permutation array */
pidx = (uint32_t *)malloc(sizeof(uint32_t) * n);
for (i = 0; i < n; i++)
{
pidx[i] = i;
}
bbox = (double *)malloc(2 * sizeof(double) * no_dims);
get_bounding_box_double(pa, pidx, no_dims, n, bbox);
tree->bbox = bbox;
/* Construct subtree on full dataset */
tree->root = (struct Node_double *)construct_subtree_double(pa, pidx, no_dims, 0, n, bsp, bbox);
tree->pidx = pidx;
return tree;
}
/************************************************
Create a tree node.
Params:
start_idx : index of first data point to use
n : number of data points
************************************************/
Node_double* create_node_double(uint32_t start_idx, uint32_t n, int is_leaf)
{
Node_double *new_node;
if (is_leaf)
{
/*
Allocate only the part of the struct that will be used in a leaf node.
This relies on the C99 specification of struct layout conservation and padding and
that dereferencing is never attempted for the node pointers in a leaf.
*/
new_node = (Node_double *)malloc(sizeof(Node_double) - 2 * sizeof(Node_double *));
}
else
{
new_node = (Node_double *)malloc(sizeof(Node_double));
}
new_node->n = n;
new_node->start_idx = start_idx;
return new_node;
}
/************************************************
Delete subtree
Params:
root : root node of subtree to delete
************************************************/
void delete_subtree_double(Node_double *root)
{
if (root->cut_dim != -1)
{
delete_subtree_double((Node_double *)root->left_child);
delete_subtree_double((Node_double *)root->right_child);
}
free(root);
}
/************************************************
Delete tree
Params:
tree : Tree struct of kd tree
************************************************/
void delete_tree_double(Tree_double *tree)
{
delete_subtree_double((Node_double *)tree->root);
free(tree->bbox);
free(tree->pidx);
free(tree);
}
/************************************************
Print
************************************************/
void print_tree_double(Node_double *root, int level)
{
int i;
for (i = 0; i < level; i++)
{
printf(" ");
}
printf("(cut_val: %f, cut_dim: %i)\n", root->cut_val, root->cut_dim);
if (root->cut_dim != -1)
print_tree_double((Node_double *)root->left_child, level + 1);
if (root->cut_dim != -1)
print_tree_double((Node_double *)root->right_child, level + 1);
}
/************************************************
Calculate squared cartesian distance between points
Params:
point1_coord : point 1
point2_coord : point 2
************************************************/
double calc_dist_double(double *point1_coord, double *point2_coord, int8_t no_dims)
{
/* Calculate squared distance */
double dist = 0, dim_dist;
int8_t i;
for (i = 0; i < no_dims; i++)
{
dim_dist = point2_coord[i] - point1_coord[i];
dist += dim_dist * dim_dist;
}
return dist;
}
/************************************************
Get squared distance from point to cube in specified dimension
Params:
dim : dimension
point_coord : cartesian coordinates of point
bbox : cube
************************************************/
double get_cube_offset_double(int8_t dim, double *point_coord, double *bbox)
{
double dim_coord = point_coord[dim];
if (dim_coord < bbox[2 * dim])
{
/* Left of cube in dimension */
return dim_coord - bbox[2 * dim];
}
else if (dim_coord > bbox[2 * dim + 1])
{
/* Right of cube in dimension */
return dim_coord - bbox[2 * dim + 1];
}
else
{
/* Inside cube in dimension */
return 0.;
}
}
/************************************************
Get minimum squared distance between point and cube.
Params:
point_coord : cartesian coordinates of point
no_dims : number of dimensions
bbox : cube
************************************************/
double get_min_dist_double(double *point_coord, int8_t no_dims, double *bbox)
{
double cube_offset = 0, cube_offset_dim;
int8_t i;
for (i = 0; i < no_dims; i++)
{
cube_offset_dim = get_cube_offset_double(i, point_coord, bbox);
cube_offset += cube_offset_dim * cube_offset_dim;
}
return cube_offset;
}
/************************************************
Search a leaf node for closest point
Params:
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
start_idx : index of first data point to use
size : number of data points
point_coord : query point
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_leaf_double(double *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *restrict point_coord,
uint32_t k, uint32_t *restrict closest_idx, double *restrict closest_dist)
{
double cur_dist;
uint32_t i;
/* Loop through all points in leaf */
for (i = 0; i < n; i++)
{
/* Get distance to query point */
cur_dist = calc_dist_double(&PA(start_idx + i, 0), point_coord, no_dims);
/* Update closest info if new point is closest so far*/
if (cur_dist < closest_dist[k - 1])
{
insert_point_double(closest_idx, closest_dist, pidx[start_idx + i], cur_dist, k);
}
}
}
/************************************************
Search a leaf node for closest point with data point mask
Params:
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
start_idx : index of first data point to use
size : number of data points
point_coord : query point
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_leaf_double_mask(double *restrict pa, uint32_t *restrict pidx, int8_t no_dims, uint32_t start_idx, uint32_t n, double *restrict point_coord,
uint32_t k, uint8_t *mask, uint32_t *restrict closest_idx, double *restrict closest_dist)
{
double cur_dist;
uint32_t i;
/* Loop through all points in leaf */
for (i = 0; i < n; i++)
{
/* Is this point masked out? */
if (mask[pidx[start_idx + i]])
{
continue;
}
/* Get distance to query point */
cur_dist = calc_dist_double(&PA(start_idx + i, 0), point_coord, no_dims);
/* Update closest info if new point is closest so far*/
if (cur_dist < closest_dist[k - 1])
{
insert_point_double(closest_idx, closest_dist, pidx[start_idx + i], cur_dist, k);
}
}
}
/************************************************
Search subtree for nearest to query point
Params:
root : root node of subtree
pa : data points
pidx : permutation index of data points
no_dims : number of dimensions
point_coord : query point
min_dist : minumum distance to nearest neighbour
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_splitnode_double(Node_double *root, double *pa, uint32_t *pidx, int8_t no_dims, double *point_coord,
double min_dist, uint32_t k, double distance_upper_bound, double eps_fac, uint8_t *mask,
uint32_t *closest_idx, double *closest_dist)
{
int8_t dim;
double dist_left, dist_right;
double new_offset;
double box_diff;
/* Skip if distance bound exeeded */
if (min_dist > distance_upper_bound)
{
return;
}
dim = root->cut_dim;
/* Handle leaf node */
if (dim == -1)
{
if (mask)
{
search_leaf_double_mask(pa, pidx, no_dims, root->start_idx, root->n, point_coord, k, mask, closest_idx, closest_dist);
}
else
{
search_leaf_double(pa, pidx, no_dims, root->start_idx, root->n, point_coord, k, closest_idx, closest_dist);
}
return;
}
/* Get distance to cutting plane */
new_offset = point_coord[dim] - root->cut_val;
if (new_offset < 0)
{
/* Left of cutting plane */
dist_left = min_dist;
if (dist_left < closest_dist[k - 1] * eps_fac)
{
/* Search left subtree if minimum distance is below limit */
search_splitnode_double((Node_double *)root->left_child, pa, pidx, no_dims, point_coord, dist_left, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
/* Right of cutting plane. Update minimum distance.
See Algorithms for Fast Vector Quantization
Sunil Arya and David M. Mount. */
box_diff = root->cut_bounds_lv - point_coord[dim];
if (box_diff < 0)
{
box_diff = 0;
}
dist_right = min_dist - box_diff * box_diff + new_offset * new_offset;
if (dist_right < closest_dist[k - 1] * eps_fac)
{
/* Search right subtree if minimum distance is below limit*/
search_splitnode_double((Node_double *)root->right_child, pa, pidx, no_dims, point_coord, dist_right, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
}
else
{
/* Right of cutting plane */
dist_right = min_dist;
if (dist_right < closest_dist[k - 1] * eps_fac)
{
/* Search right subtree if minimum distance is below limit*/
search_splitnode_double((Node_double *)root->right_child, pa, pidx, no_dims, point_coord, dist_right, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
/* Left of cutting plane. Update minimum distance.
See Algorithms for Fast Vector Quantization
Sunil Arya and David M. Mount. */
box_diff = point_coord[dim] - root->cut_bounds_hv;
if (box_diff < 0)
{
box_diff = 0;
}
dist_left = min_dist - box_diff * box_diff + new_offset * new_offset;
if (dist_left < closest_dist[k - 1] * eps_fac)
{
/* Search left subtree if minimum distance is below limit*/
search_splitnode_double((Node_double *)root->left_child, pa, pidx, no_dims, point_coord, dist_left, k, distance_upper_bound, eps_fac, mask, closest_idx, closest_dist);
}
}
}
/************************************************
Search for nearest neighbour for a set of query points
Params:
tree : Tree struct of kd tree
pa : data points
pidx : permutation index of data points
point_coords : query points
num_points : number of query points
mask : boolean array of invalid (True) and valid (False) data points
closest_idx : index of closest data point found (return)
closest_dist : distance to closest point (return)
************************************************/
void search_tree_double(Tree_double *tree, double *pa, double *point_coords,
uint32_t num_points, uint32_t k, double distance_upper_bound,
double eps, uint8_t *mask, uint32_t *closest_idxs, double *closest_dists)
{
double min_dist;
double eps_fac = 1 / ((1 + eps) * (1 + eps));
int8_t no_dims = tree->no_dims;
double *bbox = tree->bbox;
uint32_t *pidx = tree->pidx;
uint32_t j = 0;
#if defined(_MSC_VER) && defined(_OPENMP)
int32_t i = 0;
int32_t local_num_points = (int32_t) num_points;
#else
uint32_t i;
uint32_t local_num_points = num_points;
#endif
Node_double *root = (Node_double *)tree->root;
/* Queries are OpenMP enabled */
#pragma omp parallel
{
/* The low chunk size is important to avoid L2 cache trashing
for spatial coherent query datasets
*/
#pragma omp for private(i, j) schedule(static, 100) nowait
for (i = 0; i < local_num_points; i++)
{
for (j = 0; j < k; j++)
{
closest_idxs[i * k + j] = UINT32_MAX;
closest_dists[i * k + j] = DBL_MAX;
}
min_dist = get_min_dist_double(point_coords + no_dims * i, no_dims, bbox);
search_splitnode_double(root, pa, pidx, no_dims, point_coords + no_dims * i, min_dist,
k, distance_upper_bound, eps_fac, mask, &closest_idxs[i * k], &closest_dists[i * k]);
}
}
}
|
GB_binop__islt_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 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__islt_uint32
// A.*B function (eWiseMult): GB_AemultB__islt_uint32
// A*D function (colscale): GB_AxD__islt_uint32
// D*A function (rowscale): GB_DxB__islt_uint32
// C+=B function (dense accum): GB_Cdense_accumB__islt_uint32
// C+=b function (dense accum): GB_Cdense_accumb__islt_uint32
// C+=A+B function (dense ewise3): (none)
// C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__islt_uint32
// C=scalar+B GB_bind1st__islt_uint32
// C=scalar+B' GB_bind1st_tran__islt_uint32
// C=A+scalar GB_bind2nd__islt_uint32
// C=A'+scalar GB_bind2nd_tran__islt_uint32
// C type: uint32_t
// A type: uint32_t
// B,b type: uint32_t
// 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) \
uint32_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint32_t bij = Bx [pB]
// 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) \
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) ;
// 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_ISLT || GxB_NO_UINT32 || GxB_NO_ISLT_UINT32)
//------------------------------------------------------------------------------
// 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__islt_uint32
(
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__islt_uint32
(
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__islt_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__islt_uint32
(
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
uint32_t *GB_RESTRICT Cx = (uint32_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__islt_uint32
(
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
uint32_t *GB_RESTRICT Cx = (uint32_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#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__islt_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 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__islt_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 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__islt_uint32
(
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
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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_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__islt_uint32
(
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 ;
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 = 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) \
{ \
uint32_t aij = Ax [pA] ; \
Cx [pC] = (x < aij) ; \
}
GrB_Info GB_bind1st_tran__islt_uint32
(
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 \
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 = Ax [pA] ; \
Cx [pC] = (aij < y) ; \
}
GrB_Info GB_bind2nd_tran__islt_uint32
(
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
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
multi_matrices.c | #include<stdio.h>
#include<omp.h>
#define RA 4
#define CA 2
#define RB 2
#define CB 3
void init_matrix(int *M, int init, int reng, int col){
int i;
#pragma omp parallel for
for (i=0; i<reng*col; i++){
if (init == 0){
*(M+i) = 0;
} else {
*(M+i) = i+1;
}
}
}
void print_matrix(int *M, int reng, int col){
int i;
for (i=0; i<reng*col; i++){
if (i%col == 0)
printf("\n");
printf("%d\t", *(M+i));
}
printf("\n");
}
void multiply(int a[RA][CA], int b[RB][CB], int c[RA][CB]) {
int i, j, k, suma;
#pragma omp parallel for private(i, j, k) collapse(3)
for (i=0; i<CB; i++){
for (j=0; j<RA; j++){
suma = 0;
for (k=0; k<CA; k++){
suma += A[j][k] * B[k][i];
}
C[j][i] = suma;
}
}
int main(){
int A[RA][CA], B[RB][CB], C[RA][CB], *a, *b, *c, i;
double start = omp_get_wtime();
init_matrix(A, 1, RA, CA);
init_matrix(B, 1, RB, CB);
init_matrix(C, 0, RA, CB);
a = &A;
b = &B;
c = &C;
if (CA==RB)
multiply(A, B, C);
printf("Execution time: %f\n", omp_get_wtime()-start);
printf("MATRIX A\n");
print_matrix(A, RA, CA);
printf("MATRIX B\n");
print_matrix(B, RB, CB);
printf("MATRIX C = A*B\n");
print_matrix(C, RA, CB);
return 0;
}
|
effect.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% EEEEE FFFFF FFFFF EEEEE CCCC TTTTT %
% E F F E C T %
% EEE FFF FFF EEE C T %
% E F F E C T %
% EEEEE F F EEEEE CCCC T %
% %
% %
% MagickCore Image Effects Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% 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/accelerate-private.h"
#include "magick/blob.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/effect.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/matrix.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/montage.h"
#include "magick/morphology.h"
#include "magick/morphology-private.h"
#include "magick/opencl-private.h"
#include "magick/paint.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resample.h"
#include "magick/resample-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature-private.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/transform.h"
#include "magick/threshold.h"
#ifdef MAGICKCORE_CLPERFMARKER
#include "CLPerfMarker.h"
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveBlurImage() adaptively blurs the image by blurring less
% intensely near image edges and more intensely far from edges. We blur the
% image with a Gaussian operator of the given radius and standard deviation
% (sigma). For reasonable results, radius should be larger than sigma. Use a
% radius of 0 and AdaptiveBlurImage() selects a suitable radius for you.
%
% The format of the AdaptiveBlurImage method is:
%
% Image *AdaptiveBlurImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
% Image *AdaptiveBlurImageChannel(const Image *image,
% const ChannelType channel,double radius,const double sigma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Laplacian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveBlurImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*blur_image;
blur_image=AdaptiveBlurImageChannel(image,DefaultChannels,radius,sigma,
exception);
return(blur_image);
}
MagickExport Image *AdaptiveBlurImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
#define AdaptiveBlurImageTag "Convolve/Image"
#define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma)
CacheView
*blur_view,
*edge_view,
*image_view;
double
**kernel,
normalize;
Image
*blur_image,
*edge_image,
*gaussian_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
register ssize_t
i;
size_t
width;
ssize_t
j,
k,
u,
v,
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);
blur_image=CloneImage(image,0,0,MagickTrue,exception);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
if (fabs(sigma) <= MagickEpsilon)
return(blur_image);
if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse)
{
InheritException(exception,&blur_image->exception);
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
/*
Edge detect the image brighness channel, level, blur, and level again.
*/
edge_image=EdgeImage(image,radius,exception);
if (edge_image == (Image *) NULL)
{
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
(void) AutoLevelImage(edge_image);
gaussian_image=BlurImage(edge_image,radius,sigma,exception);
if (gaussian_image != (Image *) NULL)
{
edge_image=DestroyImage(edge_image);
edge_image=gaussian_image;
}
(void) AutoLevelImage(edge_image);
/*
Create a set of kernels from maximum (radius,sigma) to minimum.
*/
width=GetOptimalKernelWidth2D(radius,sigma);
kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,
sizeof(*kernel)));
if (kernel == (double **) NULL)
{
edge_image=DestroyImage(edge_image);
blur_image=DestroyImage(blur_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(kernel,0,(size_t) width*sizeof(*kernel));
for (i=0; i < (ssize_t) width; i+=2)
{
kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t)
(width-i),(width-i)*sizeof(**kernel)));
if (kernel[i] == (double *) NULL)
break;
normalize=0.0;
j=(ssize_t) (width-i-1)/2;
k=0;
for (v=(-j); v <= j; v++)
{
for (u=(-j); u <= j; u++)
{
kernel[i][k]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma*
MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma));
normalize+=kernel[i][k];
k++;
}
}
kernel[i][(k-1)/2]+=(1.0-normalize);
if (sigma < MagickEpsilon)
kernel[i][(k-1)/2]=1.0;
}
if (i < (ssize_t) width)
{
for (i-=2; i >= 0; i-=2)
kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]);
kernel=(double **) RelinquishAlignedMemory(kernel);
edge_image=DestroyImage(edge_image);
blur_image=DestroyImage(blur_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Adaptively blur image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
SetMagickPixelPacketBias(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
edge_view=AcquireVirtualCacheView(edge_image,exception);
blur_view=AcquireAuthenticCacheView(blur_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,blur_image,blur_image->rows,1)
#endif
for (y=0; y < (ssize_t) blur_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict blur_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1,
exception);
if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view);
for (x=0; x < (ssize_t) blur_image->columns; x++)
{
double
alpha,
gamma;
DoublePixelPacket
pixel;
register const double
*magick_restrict k;
register ssize_t
i,
u,
v;
gamma=0.0;
i=CastDoubleToLong(ceil((double) width*QuantumScale*
GetPixelIntensity(edge_image,r)-0.5));
if (i < 0)
i=0;
else
if (i > (ssize_t) width)
i=(ssize_t) width;
if ((i & 0x01) != 0)
i--;
p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y-
(ssize_t) ((width-i)/2L),width-i,width-i,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetCacheViewVirtualIndexQueue(image_view);
pixel.red=bias.red;
pixel.green=bias.green;
pixel.blue=bias.blue;
pixel.opacity=bias.opacity;
pixel.index=bias.index;
k=kernel[i];
for (v=0; v < (ssize_t) (width-i); v++)
{
for (u=0; u < (ssize_t) (width-i); u++)
{
alpha=1.0;
if (((channel & OpacityChannel) != 0) &&
(image->matte != MagickFalse))
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p));
if ((channel & RedChannel) != 0)
pixel.red+=(*k)*alpha*GetPixelRed(p);
if ((channel & GreenChannel) != 0)
pixel.green+=(*k)*alpha*GetPixelGreen(p);
if ((channel & BlueChannel) != 0)
pixel.blue+=(*k)*alpha*GetPixelBlue(p);
if ((channel & OpacityChannel) != 0)
pixel.opacity+=(*k)*GetPixelOpacity(p);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u);
gamma+=(*k)*alpha;
k++;
p++;
}
}
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index));
q++;
r++;
}
if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveBlurImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
blur_image->type=image->type;
blur_view=DestroyCacheView(blur_view);
edge_view=DestroyCacheView(edge_view);
image_view=DestroyCacheView(image_view);
edge_image=DestroyImage(edge_image);
for (i=0; i < (ssize_t) width; i+=2)
kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]);
kernel=(double **) RelinquishAlignedMemory(kernel);
if (status == MagickFalse)
blur_image=DestroyImage(blur_image);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e S h a r p e n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveSharpenImage() adaptively sharpens the image by sharpening more
% intensely near image edges and less intensely far from edges. We sharpen the
% image with a Gaussian operator of the given radius and standard deviation
% (sigma). For reasonable results, radius should be larger than sigma. Use a
% radius of 0 and AdaptiveSharpenImage() selects a suitable radius for you.
%
% The format of the AdaptiveSharpenImage method is:
%
% Image *AdaptiveSharpenImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
% Image *AdaptiveSharpenImageChannel(const Image *image,
% const ChannelType channel,double radius,const double sigma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Laplacian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveSharpenImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*sharp_image;
sharp_image=AdaptiveSharpenImageChannel(image,DefaultChannels,radius,sigma,
exception);
return(sharp_image);
}
MagickExport Image *AdaptiveSharpenImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
#define AdaptiveSharpenImageTag "Convolve/Image"
#define MagickSigma (fabs(sigma) < MagickEpsilon ? MagickEpsilon : sigma)
CacheView
*sharp_view,
*edge_view,
*image_view;
double
**kernel,
normalize;
Image
*sharp_image,
*edge_image,
*gaussian_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
register ssize_t
i;
size_t
width;
ssize_t
j,
k,
u,
v,
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);
sharp_image=CloneImage(image,0,0,MagickTrue,exception);
if (sharp_image == (Image *) NULL)
return((Image *) NULL);
if (fabs(sigma) <= MagickEpsilon)
return(sharp_image);
if (SetImageStorageClass(sharp_image,DirectClass) == MagickFalse)
{
InheritException(exception,&sharp_image->exception);
sharp_image=DestroyImage(sharp_image);
return((Image *) NULL);
}
/*
Edge detect the image brighness channel, level, sharp, and level again.
*/
edge_image=EdgeImage(image,radius,exception);
if (edge_image == (Image *) NULL)
{
sharp_image=DestroyImage(sharp_image);
return((Image *) NULL);
}
(void) AutoLevelImage(edge_image);
gaussian_image=BlurImage(edge_image,radius,sigma,exception);
if (gaussian_image != (Image *) NULL)
{
edge_image=DestroyImage(edge_image);
edge_image=gaussian_image;
}
(void) AutoLevelImage(edge_image);
/*
Create a set of kernels from maximum (radius,sigma) to minimum.
*/
width=GetOptimalKernelWidth2D(radius,sigma);
kernel=(double **) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,
sizeof(*kernel)));
if (kernel == (double **) NULL)
{
edge_image=DestroyImage(edge_image);
sharp_image=DestroyImage(sharp_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(kernel,0,(size_t) width*sizeof(*kernel));
for (i=0; i < (ssize_t) width; i+=2)
{
kernel[i]=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t)
(width-i),(width-i)*sizeof(**kernel)));
if (kernel[i] == (double *) NULL)
break;
normalize=0.0;
j=(ssize_t) (width-i-1)/2;
k=0;
for (v=(-j); v <= j; v++)
{
for (u=(-j); u <= j; u++)
{
kernel[i][k]=(double) (-exp(-((double) u*u+v*v)/(2.0*MagickSigma*
MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma));
normalize+=kernel[i][k];
k++;
}
}
kernel[i][(k-1)/2]=(double) ((-2.0)*normalize);
if (sigma < MagickEpsilon)
kernel[i][(k-1)/2]=1.0;
}
if (i < (ssize_t) width)
{
for (i-=2; i >= 0; i-=2)
kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]);
kernel=(double **) RelinquishAlignedMemory(kernel);
edge_image=DestroyImage(edge_image);
sharp_image=DestroyImage(sharp_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Adaptively sharpen image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
SetMagickPixelPacketBias(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
edge_view=AcquireVirtualCacheView(edge_image,exception);
sharp_view=AcquireAuthenticCacheView(sharp_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,sharp_image,sharp_image->rows,1)
#endif
for (y=0; y < (ssize_t) sharp_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict sharp_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
r=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(sharp_view,0,y,sharp_image->columns,1,
exception);
if ((r == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
sharp_indexes=GetCacheViewAuthenticIndexQueue(sharp_view);
for (x=0; x < (ssize_t) sharp_image->columns; x++)
{
double
alpha,
gamma;
DoublePixelPacket
pixel;
register const double
*magick_restrict k;
register ssize_t
i,
u,
v;
gamma=0.0;
i=CastDoubleToLong(ceil((double) width*(1.0-QuantumScale*
GetPixelIntensity(edge_image,r))-0.5));
if (i < 0)
i=0;
else
if (i > (ssize_t) width)
i=(ssize_t) width;
if ((i & 0x01) != 0)
i--;
p=GetCacheViewVirtualPixels(image_view,x-((ssize_t) (width-i)/2L),y-
(ssize_t) ((width-i)/2L),width-i,width-i,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetCacheViewVirtualIndexQueue(image_view);
k=kernel[i];
pixel.red=bias.red;
pixel.green=bias.green;
pixel.blue=bias.blue;
pixel.opacity=bias.opacity;
pixel.index=bias.index;
for (v=0; v < (ssize_t) (width-i); v++)
{
for (u=0; u < (ssize_t) (width-i); u++)
{
alpha=1.0;
if (((channel & OpacityChannel) != 0) &&
(image->matte != MagickFalse))
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p));
if ((channel & RedChannel) != 0)
pixel.red+=(*k)*alpha*GetPixelRed(p);
if ((channel & GreenChannel) != 0)
pixel.green+=(*k)*alpha*GetPixelGreen(p);
if ((channel & BlueChannel) != 0)
pixel.blue+=(*k)*alpha*GetPixelBlue(p);
if ((channel & OpacityChannel) != 0)
pixel.opacity+=(*k)*GetPixelOpacity(p);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+(width-i)*v+u);
gamma+=(*k)*alpha;
k++;
p++;
}
}
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(sharp_indexes+x,ClampToQuantum(gamma*pixel.index));
q++;
r++;
}
if (SyncCacheViewAuthenticPixels(sharp_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveSharpenImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
sharp_image->type=image->type;
sharp_view=DestroyCacheView(sharp_view);
edge_view=DestroyCacheView(edge_view);
image_view=DestroyCacheView(image_view);
edge_image=DestroyImage(edge_image);
for (i=0; i < (ssize_t) width; i+=2)
kernel[i]=(double *) RelinquishAlignedMemory(kernel[i]);
kernel=(double **) RelinquishAlignedMemory(kernel);
if (status == MagickFalse)
sharp_image=DestroyImage(sharp_image);
return(sharp_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlurImage() blurs an image. We convolve the image with a Gaussian operator
% of the given radius and standard deviation (sigma). For reasonable results,
% the radius should be larger than sigma. Use a radius of 0 and BlurImage()
% selects a suitable radius for you.
%
% The format of the BlurImage method is:
%
% Image *BlurImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
% Image *BlurImageChannel(const Image *image,const ChannelType channel,
% const double radius,const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BlurImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*blur_image;
blur_image=BlurImageChannel(image,DefaultChannels,radius,sigma,exception);
return(blur_image);
}
MagickExport Image *BlurImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent];
KernelInfo
*kernel_info;
Image
*blur_image = NULL;
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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
blur_image=AccelerateBlurImage(image,channel,radius,sigma,exception);
if (blur_image != (Image *) NULL)
return(blur_image);
#endif
(void) FormatLocaleString(geometry,MaxTextExtent,
"blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma);
kernel_info=AcquireKernelInfo(geometry);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
blur_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1,
kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o n v o l v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvolveImage() applies a custom convolution kernel to the image.
%
% The format of the ConvolveImage method is:
%
% Image *ConvolveImage(const Image *image,const size_t order,
% const double *kernel,ExceptionInfo *exception)
% Image *ConvolveImageChannel(const Image *image,const ChannelType channel,
% const size_t order,const double *kernel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o order: the number of columns and rows in the filter kernel.
%
% o kernel: An array of double representing the convolution kernel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ConvolveImage(const Image *image,const size_t order,
const double *kernel,ExceptionInfo *exception)
{
Image
*convolve_image;
#ifdef MAGICKCORE_CLPERFMARKER
clBeginPerfMarkerAMD(__FUNCTION__,"");
#endif
convolve_image=ConvolveImageChannel(image,DefaultChannels,order,kernel,
exception);
#ifdef MAGICKCORE_CLPERFMARKER
clEndPerfMarkerAMD();
#endif
return(convolve_image);
}
MagickExport Image *ConvolveImageChannel(const Image *image,
const ChannelType channel,const size_t order,const double *kernel,
ExceptionInfo *exception)
{
Image
*convolve_image;
KernelInfo
*kernel_info;
register ssize_t
i;
kernel_info=AcquireKernelInfo((const char *) NULL);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
kernel_info->width=order;
kernel_info->height=order;
kernel_info->x=(ssize_t) (order-1)/2;
kernel_info->y=(ssize_t) (order-1)/2;
kernel_info->signature=MagickCoreSignature;
kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory(
kernel_info->width,kernel_info->width*sizeof(*kernel_info->values)));
if (kernel_info->values == (double *) NULL)
{
kernel_info=DestroyKernelInfo(kernel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) (order*order); i++)
kernel_info->values[i]=kernel[i];
convolve_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
convolve_image=AccelerateConvolveImageChannel(image,channel,kernel_info,
exception);
#endif
if (convolve_image == (Image *) NULL)
convolve_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1,
kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
return(convolve_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s p e c k l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DespeckleImage() reduces the speckle noise in an image while perserving the
% edges of the original image. A speckle removing filter uses a complementary
% hulling technique (raising pixels that are darker than their surrounding
% neighbors, then complementarily lowering pixels that are brighter than their
% surrounding neighbors) to reduce the speckle index of that image (reference
% Crimmins speckle removal).
%
% The format of the DespeckleImage method is:
%
% Image *DespeckleImage(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.
%
*/
static void Hull(const Image *image,const ssize_t x_offset,
const ssize_t y_offset,const size_t columns,const size_t rows,
const int polarity,Quantum *magick_restrict f,Quantum *magick_restrict g)
{
register Quantum
*p,
*q,
*r,
*s;
ssize_t
y;
assert(f != (Quantum *) NULL);
assert(g != (Quantum *) NULL);
p=f+(columns+2);
q=g+(columns+2);
r=p+(y_offset*((ssize_t) columns+2)+x_offset);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
register ssize_t
i,
x;
SignedQuantum
v;
i=(2*y+1)+y*columns;
if (polarity > 0)
for (x=0; x < (ssize_t) columns; x++)
{
v=(SignedQuantum) p[i];
if ((SignedQuantum) r[i] >= (v+ScaleCharToQuantum(2)))
v+=ScaleCharToQuantum(1);
q[i]=(Quantum) v;
i++;
}
else
for (x=0; x < (ssize_t) columns; x++)
{
v=(SignedQuantum) p[i];
if ((SignedQuantum) r[i] <= (v-ScaleCharToQuantum(2)))
v-=ScaleCharToQuantum(1);
q[i]=(Quantum) v;
i++;
}
}
p=f+(columns+2);
q=g+(columns+2);
r=q+(y_offset*((ssize_t) columns+2)+x_offset);
s=q-(y_offset*((ssize_t) columns+2)+x_offset);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
magick_number_threads(image,image,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
register ssize_t
i,
x;
SignedQuantum
v;
i=(2*y+1)+y*columns;
if (polarity > 0)
for (x=0; x < (ssize_t) columns; x++)
{
v=(SignedQuantum) q[i];
if (((SignedQuantum) s[i] >= (v+ScaleCharToQuantum(2))) &&
((SignedQuantum) r[i] > v))
v+=ScaleCharToQuantum(1);
p[i]=(Quantum) v;
i++;
}
else
for (x=0; x < (ssize_t) columns; x++)
{
v=(SignedQuantum) q[i];
if (((SignedQuantum) s[i] <= (v-ScaleCharToQuantum(2))) &&
((SignedQuantum) r[i] < v))
v-=ScaleCharToQuantum(1);
p[i]=(Quantum) v;
i++;
}
}
}
MagickExport Image *DespeckleImage(const Image *image,ExceptionInfo *exception)
{
#define DespeckleImageTag "Despeckle/Image"
CacheView
*despeckle_view,
*image_view;
Image
*despeckle_image;
MagickBooleanType
status;
MemoryInfo
*buffer_info,
*pixel_info;
register ssize_t
i;
Quantum
*magick_restrict buffer,
*magick_restrict pixels;
size_t
length,
number_channels;
static const ssize_t
X[4] = {0, 1, 1,-1},
Y[4] = {1, 0, 1, 1};
/*
Allocate despeckled image.
*/
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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
despeckle_image=AccelerateDespeckleImage(image, exception);
if (despeckle_image != (Image *) NULL)
return(despeckle_image);
#endif
despeckle_image=CloneImage(image,0,0,MagickTrue,exception);
if (despeckle_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(despeckle_image,DirectClass) == MagickFalse)
{
InheritException(exception,&despeckle_image->exception);
despeckle_image=DestroyImage(despeckle_image);
return((Image *) NULL);
}
/*
Allocate image buffer.
*/
length=(size_t) ((image->columns+2)*(image->rows+2));
pixel_info=AcquireVirtualMemory(length,sizeof(*pixels));
buffer_info=AcquireVirtualMemory(length,sizeof(*buffer));
if ((pixel_info == (MemoryInfo *) NULL) ||
(buffer_info == (MemoryInfo *) NULL))
{
if (buffer_info != (MemoryInfo *) NULL)
buffer_info=RelinquishVirtualMemory(buffer_info);
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
despeckle_image=DestroyImage(despeckle_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
pixels=(Quantum *) GetVirtualMemoryBlob(pixel_info);
buffer=(Quantum *) GetVirtualMemoryBlob(buffer_info);
/*
Reduce speckle in the image.
*/
status=MagickTrue;
number_channels=(size_t) (image->colorspace == CMYKColorspace ? 5 : 4);
image_view=AcquireVirtualCacheView(image,exception);
despeckle_view=AcquireAuthenticCacheView(despeckle_image,exception);
for (i=0; i < (ssize_t) number_channels; i++)
{
register ssize_t
k,
x;
ssize_t
j,
y;
if (status == MagickFalse)
continue;
if ((image->matte == MagickFalse) && (i == 3))
continue;
(void) memset(pixels,0,length*sizeof(*pixels));
j=(ssize_t) image->columns+2;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetCacheViewVirtualIndexQueue(image_view);
j++;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (i)
{
case 0: pixels[j]=GetPixelRed(p); break;
case 1: pixels[j]=GetPixelGreen(p); break;
case 2: pixels[j]=GetPixelBlue(p); break;
case 3: pixels[j]=GetPixelOpacity(p); break;
case 4: pixels[j]=GetPixelBlack(indexes+x); break;
default: break;
}
p++;
j++;
}
j++;
}
(void) memset(buffer,0,length*sizeof(*buffer));
for (k=0; k < 4; k++)
{
Hull(image,X[k],Y[k],image->columns,image->rows,1,pixels,buffer);
Hull(image,-X[k],-Y[k],image->columns,image->rows,1,pixels,buffer);
Hull(image,-X[k],-Y[k],image->columns,image->rows,-1,pixels,buffer);
Hull(image,X[k],Y[k],image->columns,image->rows,-1,pixels,buffer);
}
j=(ssize_t) image->columns+2;
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
q=GetCacheViewAuthenticPixels(despeckle_view,0,y,despeckle_image->columns,
1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetCacheViewAuthenticIndexQueue(despeckle_view);
j++;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (i)
{
case 0: SetPixelRed(q,pixels[j]); break;
case 1: SetPixelGreen(q,pixels[j]); break;
case 2: SetPixelBlue(q,pixels[j]); break;
case 3: SetPixelOpacity(q,pixels[j]); break;
case 4: SetPixelIndex(indexes+x,pixels[j]); break;
default: break;
}
q++;
j++;
}
sync=SyncCacheViewAuthenticPixels(despeckle_view,exception);
if (sync == MagickFalse)
{
status=MagickFalse;
break;
}
j++;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,DespeckleImageTag,(MagickOffsetType) i,
number_channels);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
despeckle_view=DestroyCacheView(despeckle_view);
image_view=DestroyCacheView(image_view);
buffer_info=RelinquishVirtualMemory(buffer_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
despeckle_image->type=image->type;
if (status == MagickFalse)
despeckle_image=DestroyImage(despeckle_image);
return(despeckle_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E d g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EdgeImage() finds edges in an image. Radius defines the radius of the
% convolution filter. Use a radius of 0 and EdgeImage() selects a suitable
% radius for you.
%
% The format of the EdgeImage method is:
%
% Image *EdgeImage(const Image *image,const double radius,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *EdgeImage(const Image *image,const double radius,
ExceptionInfo *exception)
{
Image
*edge_image;
KernelInfo
*kernel_info;
register ssize_t
i;
size_t
width;
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);
width=GetOptimalKernelWidth1D(radius,0.5);
kernel_info=AcquireKernelInfo((const char *) NULL);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(kernel_info,0,sizeof(*kernel_info));
kernel_info->width=width;
kernel_info->height=width;
kernel_info->x=(ssize_t) (kernel_info->width-1)/2;
kernel_info->y=(ssize_t) (kernel_info->height-1)/2;
kernel_info->signature=MagickCoreSignature;
kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory(
kernel_info->width,kernel_info->height*sizeof(*kernel_info->values)));
if (kernel_info->values == (double *) NULL)
{
kernel_info=DestroyKernelInfo(kernel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++)
kernel_info->values[i]=(-1.0);
kernel_info->values[i/2]=(double) kernel_info->width*kernel_info->height-1.0;
edge_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
edge_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info,
exception);
#endif
if (edge_image == (Image *) NULL)
edge_image=MorphologyImageChannel(image,DefaultChannels,ConvolveMorphology,
1,kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
return(edge_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E m b o s s I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EmbossImage() returns a grayscale image with a three-dimensional effect.
% We convolve the image with a Gaussian operator of the given radius and
% standard deviation (sigma). For reasonable results, radius should be
% larger than sigma. Use a radius of 0 and Emboss() selects a suitable
% radius for you.
%
% The format of the EmbossImage method is:
%
% Image *EmbossImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the pixel neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *EmbossImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
double
gamma,
normalize;
Image
*emboss_image;
KernelInfo
*kernel_info;
register ssize_t
i;
size_t
width;
ssize_t
j,
k,
u,
v;
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);
width=GetOptimalKernelWidth1D(radius,sigma);
kernel_info=AcquireKernelInfo((const char *) NULL);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
kernel_info->width=width;
kernel_info->height=width;
kernel_info->x=(ssize_t) (width-1)/2;
kernel_info->y=(ssize_t) (width-1)/2;
kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory(
kernel_info->width,kernel_info->width*sizeof(*kernel_info->values)));
if (kernel_info->values == (double *) NULL)
{
kernel_info=DestroyKernelInfo(kernel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
j=(ssize_t) (kernel_info->width-1)/2;
k=j;
i=0;
for (v=(-j); v <= j; v++)
{
for (u=(-j); u <= j; u++)
{
kernel_info->values[i]=(double) (((u < 0) || (v < 0) ? -8.0 :
8.0)*exp(-((double) u*u+v*v)/(2.0*MagickSigma*MagickSigma))/
(2.0*MagickPI*MagickSigma*MagickSigma));
if (u != k)
kernel_info->values[i]=0.0;
i++;
}
k--;
}
normalize=0.0;
for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++)
normalize+=kernel_info->values[i];
gamma=PerceptibleReciprocal(normalize);
for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++)
kernel_info->values[i]*=gamma;
emboss_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
emboss_image=AccelerateConvolveImageChannel(image,DefaultChannels,kernel_info,
exception);
#endif
if (emboss_image == (Image *) NULL)
emboss_image=MorphologyImageChannel(image,DefaultChannels,
ConvolveMorphology,1,kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
if (emboss_image != (Image *) NULL)
(void) EqualizeImageChannel(emboss_image,(ChannelType)
(AllChannels &~ SyncChannels));
return(emboss_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F i l t e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FilterImage() applies a custom convolution kernel to the image.
%
% The format of the FilterImage method is:
%
% Image *FilterImage(const Image *image,const KernelInfo *kernel,
% ExceptionInfo *exception)
% Image *FilterImageChannel(const Image *image,const ChannelType channel,
% const KernelInfo *kernel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o kernel: the filtering kernel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FilterImage(const Image *image,const KernelInfo *kernel,
ExceptionInfo *exception)
{
Image
*filter_image;
filter_image=FilterImageChannel(image,DefaultChannels,kernel,exception);
return(filter_image);
}
MagickExport Image *FilterImageChannel(const Image *image,
const ChannelType channel,const KernelInfo *kernel,ExceptionInfo *exception)
{
#define FilterImageTag "Filter/Image"
CacheView
*filter_view,
*image_view;
Image
*filter_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
MagickRealType
*filter_kernel;
register ssize_t
i;
ssize_t
y;
#ifdef MAGICKCORE_CLPERFMARKER
clBeginPerfMarkerAMD(__FUNCTION__,"");
#endif
/*
Initialize filter image attributes.
*/
assert(image != (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);
if ((kernel->width % 2) == 0)
ThrowImageException(OptionError,"KernelWidthMustBeAnOddNumber");
if (image->debug != MagickFalse)
{
char
format[MaxTextExtent],
*message;
register const double
*k;
ssize_t
u,
v;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" FilterImage with %.20gx%.20g kernel:",(double) kernel->width,(double)
kernel->height);
message=AcquireString("");
k=kernel->values;
for (v=0; v < (ssize_t) kernel->height; v++)
{
*message='\0';
(void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < (ssize_t) kernel->width; u++)
{
(void) FormatLocaleString(format,MaxTextExtent,"%g ",*k++);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
filter_image=AccelerateConvolveImageChannel(image,channel,kernel,exception);
if (filter_image != (Image *) NULL)
{
#ifdef MAGICKCORE_CLPERFMARKER
clEndPerfMarkerAMD();
#endif
return(filter_image);
}
#endif
filter_image=CloneImage(image,0,0,MagickTrue,exception);
if (filter_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(filter_image,DirectClass) == MagickFalse)
{
InheritException(exception,&filter_image->exception);
filter_image=DestroyImage(filter_image);
return((Image *) NULL);
}
/*
Normalize kernel.
*/
filter_kernel=(MagickRealType *) MagickAssumeAligned(AcquireAlignedMemory(
kernel->width,kernel->height*sizeof(*filter_kernel)));
if (filter_kernel == (MagickRealType *) NULL)
{
filter_image=DestroyImage(filter_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
filter_kernel[i]=(MagickRealType) kernel->values[i];
/*
Filter image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
SetMagickPixelPacketBias(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
filter_view=AcquireAuthenticCacheView(filter_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,filter_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict filter_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (kernel->width-1)/2L),y-
(ssize_t) ((kernel->height-1)/2L),image->columns+kernel->width,
kernel->height,exception);
q=GetCacheViewAuthenticPixels(filter_view,0,y,filter_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
filter_indexes=GetCacheViewAuthenticIndexQueue(filter_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
DoublePixelPacket
pixel;
register const MagickRealType
*magick_restrict k;
register const PixelPacket
*magick_restrict kernel_pixels;
register ssize_t
u;
ssize_t
v;
pixel.red=bias.red;
pixel.green=bias.green;
pixel.blue=bias.blue;
pixel.opacity=bias.opacity;
pixel.index=bias.index;
k=filter_kernel;
kernel_pixels=p;
if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse))
{
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
pixel.red+=(*k)*kernel_pixels[u].red;
pixel.green+=(*k)*kernel_pixels[u].green;
pixel.blue+=(*k)*kernel_pixels[u].blue;
k++;
}
kernel_pixels+=image->columns+kernel->width;
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(pixel.blue));
if ((channel & OpacityChannel) != 0)
{
k=filter_kernel;
kernel_pixels=p;
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
pixel.opacity+=(*k)*kernel_pixels[u].opacity;
k++;
}
kernel_pixels+=image->columns+kernel->width;
}
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
register const IndexPacket
*magick_restrict kernel_indexes;
k=filter_kernel;
kernel_indexes=indexes;
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
pixel.index+=(*k)*GetPixelIndex(kernel_indexes+u);
k++;
}
kernel_indexes+=image->columns+kernel->width;
}
SetPixelIndex(filter_indexes+x,ClampToQuantum(pixel.index));
}
}
else
{
double
alpha,
gamma;
gamma=0.0;
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
alpha=(MagickRealType) (QuantumScale*(QuantumRange-
GetPixelOpacity(kernel_pixels+u)));
pixel.red+=(*k)*alpha*GetPixelRed(kernel_pixels+u);
pixel.green+=(*k)*alpha*GetPixelGreen(kernel_pixels+u);
pixel.blue+=(*k)*alpha*GetPixelBlue(kernel_pixels+u);
gamma+=(*k)*alpha;
k++;
}
kernel_pixels+=image->columns+kernel->width;
}
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
if ((channel & OpacityChannel) != 0)
{
k=filter_kernel;
kernel_pixels=p;
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
pixel.opacity+=(*k)*GetPixelOpacity(kernel_pixels+u);
k++;
}
kernel_pixels+=image->columns+kernel->width;
}
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
register const IndexPacket
*magick_restrict kernel_indexes;
k=filter_kernel;
kernel_pixels=p;
kernel_indexes=indexes;
for (v=0; v < (ssize_t) kernel->width; v++)
{
for (u=0; u < (ssize_t) kernel->height; u++)
{
alpha=(MagickRealType) (QuantumScale*(QuantumRange-
kernel_pixels[u].opacity));
pixel.index+=(*k)*alpha*GetPixelIndex(kernel_indexes+u);
k++;
}
kernel_pixels+=image->columns+kernel->width;
kernel_indexes+=image->columns+kernel->width;
}
SetPixelIndex(filter_indexes+x,ClampToQuantum(gamma*pixel.index));
}
}
indexes++;
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(filter_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,FilterImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
filter_image->type=image->type;
filter_view=DestroyCacheView(filter_view);
image_view=DestroyCacheView(image_view);
filter_kernel=(MagickRealType *) RelinquishAlignedMemory(filter_kernel);
if (status == MagickFalse)
filter_image=DestroyImage(filter_image);
#ifdef MAGICKCORE_CLPERFMARKER
clEndPerfMarkerAMD();
#endif
return(filter_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G a u s s i a n B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GaussianBlurImage() blurs an image. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma).
% For reasonable results, the radius should be larger than sigma. Use a
% radius of 0 and GaussianBlurImage() selects a suitable radius for you.
%
% The format of the GaussianBlurImage method is:
%
% Image *GaussianBlurImage(const Image *image,onst double radius,
% const double sigma,ExceptionInfo *exception)
% Image *GaussianBlurImageChannel(const Image *image,
% const ChannelType channel,const double radius,const double sigma,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *GaussianBlurImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*blur_image;
blur_image=GaussianBlurImageChannel(image,DefaultChannels,radius,sigma,
exception);
return(blur_image);
}
MagickExport Image *GaussianBlurImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
char
geometry[MaxTextExtent];
KernelInfo
*kernel_info;
Image
*blur_image;
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);
(void) FormatLocaleString(geometry,MaxTextExtent,"gaussian:%.20gx%.20g",
radius,sigma);
kernel_info=AcquireKernelInfo(geometry);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
blur_image=(Image *) NULL;
#if defined(MAGICKCORE_OPENCL_SUPPORT)
blur_image=AccelerateConvolveImageChannel(image,channel,kernel_info,
exception);
#endif
if (blur_image == (Image *) NULL)
blur_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1,
kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o t i o n B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MotionBlurImage() simulates motion blur. We convolve the image with a
% Gaussian operator of the given radius and standard deviation (sigma).
% For reasonable results, radius should be larger than sigma. Use a
% radius of 0 and MotionBlurImage() selects a suitable radius for you.
% Angle gives the angle of the blurring motion.
%
% Andrew Protano contributed this effect.
%
% The format of the MotionBlurImage method is:
%
% Image *MotionBlurImage(const Image *image,const double radius,
% const double sigma,const double angle,ExceptionInfo *exception)
% Image *MotionBlurImageChannel(const Image *image,const ChannelType channel,
% const double radius,const double sigma,const double angle,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o angle: Apply the effect along this angle.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double *GetMotionBlurKernel(const size_t width,const double sigma)
{
double
*kernel,
normalize;
register ssize_t
i;
/*
Generate a 1-D convolution kernel.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,
sizeof(*kernel)));
if (kernel == (double *) NULL)
return(kernel);
normalize=0.0;
for (i=0; i < (ssize_t) width; i++)
{
kernel[i]=(double) (exp((-((double) i*i)/(double) (2.0*MagickSigma*
MagickSigma)))/(MagickSQ2PI*MagickSigma));
normalize+=kernel[i];
}
for (i=0; i < (ssize_t) width; i++)
kernel[i]/=normalize;
return(kernel);
}
MagickExport Image *MotionBlurImage(const Image *image,const double radius,
const double sigma,const double angle,ExceptionInfo *exception)
{
Image
*motion_blur;
motion_blur=MotionBlurImageChannel(image,DefaultChannels,radius,sigma,angle,
exception);
return(motion_blur);
}
MagickExport Image *MotionBlurImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
const double angle,ExceptionInfo *exception)
{
#define BlurImageTag "Blur/Image"
CacheView
*blur_view,
*image_view;
double
*kernel;
Image
*blur_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
OffsetInfo
*offset;
PointInfo
point;
register ssize_t
i;
size_t
width;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
width=GetOptimalKernelWidth1D(radius,sigma);
kernel=GetMotionBlurKernel(width,sigma);
if (kernel == (double *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
offset=(OffsetInfo *) AcquireQuantumMemory(width,sizeof(*offset));
if (offset == (OffsetInfo *) NULL)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
point.x=(double) width*sin(DegreesToRadians(angle));
point.y=(double) width*cos(DegreesToRadians(angle));
for (i=0; i < (ssize_t) width; i++)
{
offset[i].x=CastDoubleToLong(ceil((double) (i*point.y)/
hypot(point.x,point.y)-0.5));
offset[i].y=CastDoubleToLong(ceil((double) (i*point.x)/
hypot(point.x,point.y)-0.5));
}
/*
Motion blur image.
*/
#if defined(MAGICKCORE_OPENCL_SUPPORT)
blur_image=AccelerateMotionBlurImage(image,channel,kernel,width,offset,
exception);
if (blur_image != (Image *) NULL)
return blur_image;
#endif
blur_image=CloneImage(image,0,0,MagickTrue,exception);
if (blur_image == (Image *) NULL)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
offset=(OffsetInfo *) RelinquishMagickMemory(offset);
return((Image *) NULL);
}
if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
offset=(OffsetInfo *) RelinquishMagickMemory(offset);
InheritException(exception,&blur_image->exception);
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
blur_view=AcquireAuthenticCacheView(blur_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,blur_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict blur_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
qixel;
PixelPacket
pixel;
register const IndexPacket
*magick_restrict indexes;
register double
*magick_restrict k;
register ssize_t
i;
k=kernel;
qixel=bias;
if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse))
{
for (i=0; i < (ssize_t) width; i++)
{
(void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+
offset[i].y,&pixel,exception);
qixel.red+=(*k)*pixel.red;
qixel.green+=(*k)*pixel.green;
qixel.blue+=(*k)*pixel.blue;
qixel.opacity+=(*k)*pixel.opacity;
if (image->colorspace == CMYKColorspace)
{
indexes=GetCacheViewVirtualIndexQueue(image_view);
qixel.index+=(*k)*(*indexes);
}
k++;
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(qixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(qixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(qixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(qixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(blur_indexes+x,ClampToQuantum(qixel.index));
}
else
{
double
alpha,
gamma;
alpha=0.0;
gamma=0.0;
for (i=0; i < (ssize_t) width; i++)
{
(void) GetOneCacheViewVirtualPixel(image_view,x+offset[i].x,y+
offset[i].y,&pixel,exception);
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel));
qixel.red+=(*k)*alpha*pixel.red;
qixel.green+=(*k)*alpha*pixel.green;
qixel.blue+=(*k)*alpha*pixel.blue;
qixel.opacity+=(*k)*pixel.opacity;
if (image->colorspace == CMYKColorspace)
{
indexes=GetCacheViewVirtualIndexQueue(image_view);
qixel.index+=(*k)*alpha*GetPixelIndex(indexes);
}
gamma+=(*k)*alpha;
k++;
}
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*qixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*qixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(qixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index));
}
q++;
}
if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,BlurImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
blur_view=DestroyCacheView(blur_view);
image_view=DestroyCacheView(image_view);
kernel=(double *) RelinquishAlignedMemory(kernel);
offset=(OffsetInfo *) RelinquishMagickMemory(offset);
if (status == MagickFalse)
blur_image=DestroyImage(blur_image);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% K u w a h a r a I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% KuwaharaImage() is an edge preserving noise reduction filter.
%
% The format of the KuwaharaImage method is:
%
% Image *KuwaharaImage(const Image *image,const double width,
% const double sigma,ExceptionInfo *exception)
% Image *KuwaharaImageChannel(const Image *image,const ChannelType channel,
% const double width,const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the square window radius.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *KuwaharaImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*kuwahara_image;
kuwahara_image=KuwaharaImageChannel(image,DefaultChannels,radius,sigma,
exception);
return(kuwahara_image);
}
MagickExport Image *KuwaharaImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
#define KuwaharaImageTag "Kiwahara/Image"
CacheView
*image_view,
*kuwahara_view;
Image
*gaussian_image,
*kuwahara_image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
width;
ssize_t
y;
/*
Initialize Kuwahara image attributes.
*/
assert(image != (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);
(void) channel;
width=(size_t) radius+1;
gaussian_image=BlurImage(image,radius,sigma,exception);
if (gaussian_image == (Image *) NULL)
return((Image *) NULL);
kuwahara_image=CloneImage(image,0,0,MagickTrue,exception);
if (kuwahara_image == (Image *) NULL)
{
gaussian_image=DestroyImage(gaussian_image);
return((Image *) NULL);
}
if (SetImageStorageClass(kuwahara_image,DirectClass) == MagickFalse)
{
InheritException(exception,&kuwahara_image->exception);
gaussian_image=DestroyImage(gaussian_image);
kuwahara_image=DestroyImage(kuwahara_image);
return((Image *) NULL);
}
/*
Edge preserving noise reduction filter.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(gaussian_image,exception);
kuwahara_view=AcquireAuthenticCacheView(kuwahara_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,kuwahara_image,kuwahara_image->rows,1)
#endif
for (y=0; y < (ssize_t) kuwahara_image->rows; y++)
{
register IndexPacket
*magick_restrict kuwahara_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(kuwahara_view,0,y,kuwahara_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
kuwahara_indexes=GetCacheViewAuthenticIndexQueue(kuwahara_view);
for (x=0; x < (ssize_t) kuwahara_image->columns; x++)
{
double
min_variance;
MagickPixelPacket
pixel;
RectangleInfo
quadrant,
target;
register ssize_t
i;
min_variance=MagickMaximumValue;
SetGeometry(gaussian_image,&target);
quadrant.width=width;
quadrant.height=width;
for (i=0; i < 4; i++)
{
const PixelPacket
*magick_restrict p;
double
variance;
MagickPixelPacket
mean;
register const PixelPacket
*magick_restrict k;
register ssize_t
n;
quadrant.x=x;
quadrant.y=y;
switch (i)
{
case 0:
{
quadrant.x=x-(ssize_t) (width-1);
quadrant.y=y-(ssize_t) (width-1);
break;
}
case 1:
{
quadrant.y=y-(ssize_t) (width-1);
break;
}
case 2:
{
quadrant.x=x-(ssize_t) (width-1);
break;
}
default:
break;
}
p=GetCacheViewVirtualPixels(image_view,quadrant.x,quadrant.y,
quadrant.width,quadrant.height,exception);
if (p == (const PixelPacket *) NULL)
break;
GetMagickPixelPacket(image,&mean);
k=p;
for (n=0; n < (ssize_t) (width*width); n++)
{
mean.red+=(double) k->red;
mean.green+=(double) k->green;
mean.blue+=(double) k->blue;
k++;
}
mean.red/=(double) (width*width);
mean.green/=(double) (width*width);
mean.blue/=(double) (width*width);
k=p;
variance=0.0;
for (n=0; n < (ssize_t) (width*width); n++)
{
double
luma;
luma=GetPixelLuma(image,k);
variance+=(luma-MagickPixelLuma(&mean))*(luma-MagickPixelLuma(&mean));
k++;
}
if (variance < min_variance)
{
min_variance=variance;
target=quadrant;
}
}
if (i < 4)
{
status=MagickFalse;
break;
}
status=InterpolateMagickPixelPacket(gaussian_image,image_view,
UndefinedInterpolatePixel,(double) target.x+target.width/2.0,
(double) target.y+target.height/2.0,&pixel,exception);
if (status == MagickFalse)
break;
SetPixelPacket(kuwahara_image,&pixel,q,kuwahara_indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(kuwahara_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,KuwaharaImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
kuwahara_view=DestroyCacheView(kuwahara_view);
image_view=DestroyCacheView(image_view);
gaussian_image=DestroyImage(gaussian_image);
if (status == MagickFalse)
kuwahara_image=DestroyImage(kuwahara_image);
return(kuwahara_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l C o n t r a s t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocalContrastImage() attempts to increase the appearance of large-scale
% light-dark transitions. Local contrast enhancement works similarly to
% sharpening with an unsharp mask, however the mask is instead created using
% an image with a greater blur distance.
%
% The format of the LocalContrastImage method is:
%
% Image *LocalContrastImage(const Image *image, const double radius,
% const double strength, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the Gaussian blur, in percentage with 100%
% resulting in a blur radius of 20% of largest dimension.
%
% o strength: the strength of the blur mask in percentage.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *LocalContrastImage(const Image *image,const double radius,
const double strength,ExceptionInfo *exception)
{
#define LocalContrastImageTag "LocalContrast/Image"
CacheView
*image_view,
*contrast_view;
float
*interImage,
*scanline,
totalWeight;
Image
*contrast_image;
MagickBooleanType
status;
MemoryInfo
*interImage_info,
*scanline_info;
ssize_t
scanLineSize,
width;
/*
Initialize contrast image attributes.
*/
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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
contrast_image=AccelerateLocalContrastImage(image,radius,strength,exception);
if (contrast_image != (Image *) NULL)
return(contrast_image);
#endif
contrast_image=CloneImage(image,0,0,MagickTrue,exception);
if (contrast_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(contrast_image,DirectClass) == MagickFalse)
{
InheritException(exception,&contrast_image->exception);
contrast_image=DestroyImage(contrast_image);
return((Image *) NULL);
}
image_view=AcquireVirtualCacheView(image,exception);
contrast_view=AcquireAuthenticCacheView(contrast_image,exception);
scanLineSize=(ssize_t) MagickMax(image->columns,image->rows);
width=(ssize_t) scanLineSize*0.002f*fabs(radius);
scanLineSize+=(2*width);
scanline_info=AcquireVirtualMemory(GetOpenMPMaximumThreads()*
scanLineSize,sizeof(*scanline));
if (scanline_info == (MemoryInfo *) NULL)
{
contrast_view=DestroyCacheView(contrast_view);
image_view=DestroyCacheView(image_view);
contrast_image=DestroyImage(contrast_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
scanline=(float *) GetVirtualMemoryBlob(scanline_info);
/*
Create intermediate buffer.
*/
interImage_info=AcquireVirtualMemory(image->rows*(image->columns+(2*width)),
sizeof(*interImage));
if (interImage_info == (MemoryInfo *) NULL)
{
scanline_info=RelinquishVirtualMemory(scanline_info);
contrast_view=DestroyCacheView(contrast_view);
image_view=DestroyCacheView(image_view);
contrast_image=DestroyImage(contrast_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
interImage=(float *) GetVirtualMemoryBlob(interImage_info);
totalWeight=(width+1)*(width+1);
/*
Vertical pass.
*/
status=MagickTrue;
{
ssize_t
x;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
magick_number_threads(image,image,image->columns,1)
#endif
for (x=0; x < (ssize_t) image->columns; x++)
{
const int
id = GetOpenMPThreadId();
const PixelPacket
*magick_restrict p;
float
*out,
*pix,
*pixels;
register ssize_t
y;
ssize_t
i;
if (status == MagickFalse)
continue;
pixels=scanline;
pixels+=id*scanLineSize;
pix=pixels;
p=GetCacheViewVirtualPixels(image_view,x,-width,1,image->rows+(2*width),
exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
for (y=0; y < (ssize_t) image->rows+(2*width); y++)
{
*pix++=(float)GetPixelLuma(image,p);
p++;
}
out=interImage+x+width;
for (y=0; y < (ssize_t) image->rows; y++)
{
float
sum,
weight;
weight=1.0f;
sum=0;
pix=pixels+y;
for (i=0; i < width; i++)
{
sum+=weight*(*pix++);
weight+=1.0f;
}
for (i=width+1; i < (2*width); i++)
{
sum+=weight*(*pix++);
weight-=1.0f;
}
/* write to output */
*out=sum/totalWeight;
/* mirror into padding */
if (x <= width && x != 0)
*(out-(x*2))=*out;
if ((x > (ssize_t) image->columns-width-2) &&
(x != (ssize_t) image->columns-1))
*(out+((image->columns-x-1)*2))=*out;
out+=image->columns+(width*2);
}
}
}
/*
Horizontal pass.
*/
{
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
const PixelPacket
*magick_restrict p;
float
*pix,
*pixels;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
i;
if (status == MagickFalse)
continue;
pixels=scanline;
pixels+=id*scanLineSize;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,
exception);
q=GetCacheViewAuthenticPixels(contrast_view,0,y,image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
memcpy(pixels,interImage+(y*(image->columns+(2*width))),(image->columns+
(2*width))*sizeof(float));
for (x=0; x < (ssize_t) image->columns; x++)
{
float
mult,
srcVal,
sum,
weight;
weight=1.0f;
sum=0;
pix=pixels+x;
for (i=0; i < width; i++)
{
sum+=weight*(*pix++);
weight+=1.0f;
}
for (i=width+1; i < (2*width); i++)
{
sum+=weight*(*pix++);
weight-=1.0f;
}
/* Apply and write */
srcVal=(float) GetPixelLuma(image,p);
mult=(srcVal-(sum/totalWeight))*(strength/100.0f);
mult=(srcVal+mult)/srcVal;
SetPixelRed(q,ClampToQuantum((MagickRealType) GetPixelRed(p)*mult));
SetPixelGreen(q,ClampToQuantum((MagickRealType) GetPixelGreen(p)*mult));
SetPixelBlue(q,ClampToQuantum((MagickRealType) GetPixelBlue(p)*mult));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(contrast_view,exception) == MagickFalse)
status=MagickFalse;
}
}
scanline_info=RelinquishVirtualMemory(scanline_info);
interImage_info=RelinquishVirtualMemory(interImage_info);
contrast_view=DestroyCacheView(contrast_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
contrast_image=DestroyImage(contrast_image);
return(contrast_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P r e v i e w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PreviewImage() tiles 9 thumbnails of the specified image with an image
% processing operation applied with varying parameters. This may be helpful
% pin-pointing an appropriate parameter for a particular image processing
% operation.
%
% The format of the PreviewImages method is:
%
% Image *PreviewImages(const Image *image,const PreviewType preview,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o preview: the image processing operation.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *PreviewImage(const Image *image,const PreviewType preview,
ExceptionInfo *exception)
{
#define NumberTiles 9
#define PreviewImageTag "Preview/Image"
#define DefaultPreviewGeometry "204x204+10+10"
char
factor[MaxTextExtent],
label[MaxTextExtent];
double
degrees,
gamma,
percentage,
radius,
sigma,
threshold;
Image
*images,
*montage_image,
*preview_image,
*thumbnail;
ImageInfo
*preview_info;
MagickBooleanType
proceed;
MontageInfo
*montage_info;
QuantizeInfo
quantize_info;
RectangleInfo
geometry;
register ssize_t
i,
x;
size_t
colors;
ssize_t
y;
/*
Open output image file.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
colors=2;
degrees=0.0;
gamma=(-0.2f);
preview_info=AcquireImageInfo();
SetGeometry(image,&geometry);
(void) ParseMetaGeometry(DefaultPreviewGeometry,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
images=NewImageList();
percentage=12.5;
GetQuantizeInfo(&quantize_info);
radius=0.0;
sigma=1.0;
threshold=0.0;
x=0;
y=0;
for (i=0; i < NumberTiles; i++)
{
thumbnail=ThumbnailImage(image,geometry.width,geometry.height,exception);
if (thumbnail == (Image *) NULL)
break;
(void) SetImageProgressMonitor(thumbnail,(MagickProgressMonitor) NULL,
(void *) NULL);
(void) SetImageProperty(thumbnail,"label",DefaultTileLabel);
if (i == (NumberTiles/2))
{
(void) QueryColorDatabase("#dfdfdf",&thumbnail->matte_color,exception);
AppendImageToList(&images,thumbnail);
continue;
}
switch (preview)
{
case RotatePreview:
{
degrees+=45.0;
preview_image=RotateImage(thumbnail,degrees,exception);
(void) FormatLocaleString(label,MaxTextExtent,"rotate %g",degrees);
break;
}
case ShearPreview:
{
degrees+=5.0;
preview_image=ShearImage(thumbnail,degrees,degrees,exception);
(void) FormatLocaleString(label,MaxTextExtent,"shear %gx%g",
degrees,2.0*degrees);
break;
}
case RollPreview:
{
x=(ssize_t) ((i+1)*thumbnail->columns)/NumberTiles;
y=(ssize_t) ((i+1)*thumbnail->rows)/NumberTiles;
preview_image=RollImage(thumbnail,x,y,exception);
(void) FormatLocaleString(label,MaxTextExtent,"roll %+.20gx%+.20g",
(double) x,(double) y);
break;
}
case HuePreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
(void) FormatLocaleString(factor,MaxTextExtent,"100,100,%g",
2.0*percentage);
(void) ModulateImage(preview_image,factor);
(void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor);
break;
}
case SaturationPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
(void) FormatLocaleString(factor,MaxTextExtent,"100,%g",2.0*percentage);
(void) ModulateImage(preview_image,factor);
(void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor);
break;
}
case BrightnessPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
(void) FormatLocaleString(factor,MaxTextExtent,"%g",2.0*percentage);
(void) ModulateImage(preview_image,factor);
(void) FormatLocaleString(label,MaxTextExtent,"modulate %s",factor);
break;
}
case GammaPreview:
default:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
gamma+=0.4f;
(void) GammaImageChannel(preview_image,DefaultChannels,gamma);
(void) FormatLocaleString(label,MaxTextExtent,"gamma %g",gamma);
break;
}
case SpiffPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image != (Image *) NULL)
for (x=0; x < i; x++)
(void) ContrastImage(preview_image,MagickTrue);
(void) FormatLocaleString(label,MaxTextExtent,"contrast (%.20g)",
(double) i+1);
break;
}
case DullPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
for (x=0; x < i; x++)
(void) ContrastImage(preview_image,MagickFalse);
(void) FormatLocaleString(label,MaxTextExtent,"+contrast (%.20g)",
(double) i+1);
break;
}
case GrayscalePreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
colors<<=1;
quantize_info.number_colors=colors;
quantize_info.colorspace=GRAYColorspace;
(void) QuantizeImage(&quantize_info,preview_image);
(void) FormatLocaleString(label,MaxTextExtent,
"-colorspace gray -colors %.20g",(double) colors);
break;
}
case QuantizePreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
colors<<=1;
quantize_info.number_colors=colors;
(void) QuantizeImage(&quantize_info,preview_image);
(void) FormatLocaleString(label,MaxTextExtent,"colors %.20g",(double)
colors);
break;
}
case DespecklePreview:
{
for (x=0; x < (i-1); x++)
{
preview_image=DespeckleImage(thumbnail,exception);
if (preview_image == (Image *) NULL)
break;
thumbnail=DestroyImage(thumbnail);
thumbnail=preview_image;
}
preview_image=DespeckleImage(thumbnail,exception);
if (preview_image == (Image *) NULL)
break;
(void) FormatLocaleString(label,MaxTextExtent,"despeckle (%.20g)",
(double) i+1);
break;
}
case ReduceNoisePreview:
{
preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) radius,
(size_t) radius,exception);
(void) FormatLocaleString(label,MaxTextExtent,"noise %g",radius);
break;
}
case AddNoisePreview:
{
switch ((int) i)
{
case 0:
{
(void) CopyMagickString(factor,"uniform",MaxTextExtent);
break;
}
case 1:
{
(void) CopyMagickString(factor,"gaussian",MaxTextExtent);
break;
}
case 2:
{
(void) CopyMagickString(factor,"multiplicative",MaxTextExtent);
break;
}
case 3:
{
(void) CopyMagickString(factor,"impulse",MaxTextExtent);
break;
}
case 5:
{
(void) CopyMagickString(factor,"laplacian",MaxTextExtent);
break;
}
case 6:
{
(void) CopyMagickString(factor,"poisson",MaxTextExtent);
break;
}
default:
{
(void) CopyMagickString(thumbnail->magick,"NULL",MaxTextExtent);
break;
}
}
preview_image=StatisticImage(thumbnail,NonpeakStatistic,(size_t) i,
(size_t) i,exception);
(void) FormatLocaleString(label,MaxTextExtent,"+noise %s",factor);
break;
}
case SharpenPreview:
{
preview_image=SharpenImage(thumbnail,radius,sigma,exception);
(void) FormatLocaleString(label,MaxTextExtent,"sharpen %gx%g",
radius,sigma);
break;
}
case BlurPreview:
{
preview_image=BlurImage(thumbnail,radius,sigma,exception);
(void) FormatLocaleString(label,MaxTextExtent,"blur %gx%g",radius,
sigma);
break;
}
case ThresholdPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
(void) BilevelImage(thumbnail,
(double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0);
(void) FormatLocaleString(label,MaxTextExtent,"threshold %g",
(double) (percentage*((MagickRealType) QuantumRange+1.0))/100.0);
break;
}
case EdgeDetectPreview:
{
preview_image=EdgeImage(thumbnail,radius,exception);
(void) FormatLocaleString(label,MaxTextExtent,"edge %g",radius);
break;
}
case SpreadPreview:
{
preview_image=SpreadImage(thumbnail,radius,exception);
(void) FormatLocaleString(label,MaxTextExtent,"spread %g",
radius+0.5);
break;
}
case SolarizePreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
(void) SolarizeImage(preview_image,(double) QuantumRange*
percentage/100.0);
(void) FormatLocaleString(label,MaxTextExtent,"solarize %g",
(QuantumRange*percentage)/100.0);
break;
}
case ShadePreview:
{
degrees+=10.0;
preview_image=ShadeImage(thumbnail,MagickTrue,degrees,degrees,
exception);
(void) FormatLocaleString(label,MaxTextExtent,"shade %gx%g",
degrees,degrees);
break;
}
case RaisePreview:
{
RectangleInfo
raise;
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
raise.width=(size_t) (2*i+2);
raise.height=(size_t) (2*i+2);
raise.x=(i-1)/2;
raise.y=(i-1)/2;
(void) RaiseImage(preview_image,&raise,MagickTrue);
(void) FormatLocaleString(label,MaxTextExtent,
"raise %.20gx%.20g%+.20g%+.20g",(double) raise.width,(double)
raise.height,(double) raise.x,(double) raise.y);
break;
}
case SegmentPreview:
{
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
threshold+=0.4f;
(void) SegmentImage(preview_image,sRGBColorspace,MagickFalse,threshold,
threshold);
(void) FormatLocaleString(label,MaxTextExtent,"segment %gx%g",
threshold,threshold);
break;
}
case SwirlPreview:
{
preview_image=SwirlImage(thumbnail,degrees,exception);
(void) FormatLocaleString(label,MaxTextExtent,"swirl %g",degrees);
degrees+=45.0;
break;
}
case ImplodePreview:
{
degrees+=0.1f;
preview_image=ImplodeImage(thumbnail,degrees,exception);
(void) FormatLocaleString(label,MaxTextExtent,"implode %g",degrees);
break;
}
case WavePreview:
{
degrees+=5.0f;
preview_image=WaveImage(thumbnail,0.5*degrees,2.0*degrees,exception);
(void) FormatLocaleString(label,MaxTextExtent,"wave %gx%g",
0.5*degrees,2.0*degrees);
break;
}
case OilPaintPreview:
{
preview_image=OilPaintImage(thumbnail,(double) radius,exception);
(void) FormatLocaleString(label,MaxTextExtent,"paint %g",radius);
break;
}
case CharcoalDrawingPreview:
{
preview_image=CharcoalImage(thumbnail,(double) radius,(double) sigma,
exception);
(void) FormatLocaleString(label,MaxTextExtent,"charcoal %gx%g",
radius,sigma);
break;
}
case JPEGPreview:
{
char
filename[MaxTextExtent];
int
file;
MagickBooleanType
status;
preview_image=CloneImage(thumbnail,0,0,MagickTrue,exception);
if (preview_image == (Image *) NULL)
break;
preview_info->quality=(size_t) percentage;
(void) FormatLocaleString(factor,MaxTextExtent,"%.20g",(double)
preview_info->quality);
file=AcquireUniqueFileResource(filename);
if (file != -1)
file=close(file)-1;
(void) FormatLocaleString(preview_image->filename,MaxTextExtent,
"jpeg:%s",filename);
status=WriteImage(preview_info,preview_image);
if (status != MagickFalse)
{
Image
*quality_image;
(void) CopyMagickString(preview_info->filename,
preview_image->filename,MaxTextExtent);
quality_image=ReadImage(preview_info,exception);
if (quality_image != (Image *) NULL)
{
preview_image=DestroyImage(preview_image);
preview_image=quality_image;
}
}
(void) RelinquishUniqueFileResource(preview_image->filename);
if ((GetBlobSize(preview_image)/1024) >= 1024)
(void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%gmb ",
factor,(double) ((MagickOffsetType) GetBlobSize(preview_image))/
1024.0/1024.0);
else
if (GetBlobSize(preview_image) >= 1024)
(void) FormatLocaleString(label,MaxTextExtent,
"quality %s\n%gkb ",factor,(double) ((MagickOffsetType)
GetBlobSize(preview_image))/1024.0);
else
(void) FormatLocaleString(label,MaxTextExtent,"quality %s\n%.20gb ",
factor,(double) ((MagickOffsetType) GetBlobSize(thumbnail)));
break;
}
}
thumbnail=DestroyImage(thumbnail);
percentage+=12.5;
radius+=0.5;
sigma+=0.25;
if (preview_image == (Image *) NULL)
break;
(void) DeleteImageProperty(preview_image,"label");
(void) SetImageProperty(preview_image,"label",label);
AppendImageToList(&images,preview_image);
proceed=SetImageProgress(image,PreviewImageTag,(MagickOffsetType) i,
NumberTiles);
if (proceed == MagickFalse)
break;
}
if (images == (Image *) NULL)
{
preview_info=DestroyImageInfo(preview_info);
return((Image *) NULL);
}
/*
Create the montage.
*/
montage_info=CloneMontageInfo(preview_info,(MontageInfo *) NULL);
(void) CopyMagickString(montage_info->filename,image->filename,MaxTextExtent);
montage_info->shadow=MagickTrue;
(void) CloneString(&montage_info->tile,"3x3");
(void) CloneString(&montage_info->geometry,DefaultPreviewGeometry);
(void) CloneString(&montage_info->frame,DefaultTileFrame);
montage_image=MontageImages(images,montage_info,exception);
montage_info=DestroyMontageInfo(montage_info);
images=DestroyImageList(images);
if (montage_image == (Image *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
if (montage_image->montage != (char *) NULL)
{
/*
Free image directory.
*/
montage_image->montage=(char *) RelinquishMagickMemory(
montage_image->montage);
if (image->directory != (char *) NULL)
montage_image->directory=(char *) RelinquishMagickMemory(
montage_image->directory);
}
preview_info=DestroyImageInfo(preview_info);
return(montage_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o t a t i o n a l B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RotationalBlurImage() applies a rotational blur to the image.
%
% Andrew Protano contributed this effect.
%
% The format of the RotationalBlurImage method is:
%
% Image *RotationalBlurImage(const Image *image,const double angle,
% ExceptionInfo *exception)
% Image *RotationalBlurImageChannel(const Image *image,
% const ChannelType channel,const double angle,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o angle: the angle of the rotational blur.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *RotationalBlurImage(const Image *image,const double angle,
ExceptionInfo *exception)
{
Image
*blur_image;
blur_image=RotationalBlurImageChannel(image,DefaultChannels,angle,exception);
return(blur_image);
}
MagickExport Image *RotationalBlurImageChannel(const Image *image,
const ChannelType channel,const double angle,ExceptionInfo *exception)
{
CacheView
*blur_view,
*image_view;
Image
*blur_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
MagickRealType
blur_radius,
*cos_theta,
offset,
*sin_theta,
theta;
PointInfo
blur_center;
register ssize_t
i;
size_t
n;
ssize_t
y;
/*
Allocate blur image.
*/
assert(image != (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);
#if defined(MAGICKCORE_OPENCL_SUPPORT)
blur_image=AccelerateRadialBlurImage(image,channel,angle,exception);
if (blur_image != (Image *) NULL)
return(blur_image);
#endif
blur_image=CloneImage(image,0,0,MagickTrue,exception);
if (blur_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse)
{
InheritException(exception,&blur_image->exception);
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
blur_center.x=(double) (image->columns-1)/2.0;
blur_center.y=(double) (image->rows-1)/2.0;
blur_radius=hypot(blur_center.x,blur_center.y);
n=(size_t) fabs(4.0*DegreesToRadians(angle)*sqrt((double) blur_radius)+2UL);
theta=DegreesToRadians(angle)/(MagickRealType) (n-1);
cos_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n,
sizeof(*cos_theta));
sin_theta=(MagickRealType *) AcquireQuantumMemory((size_t) n,
sizeof(*sin_theta));
if ((cos_theta == (MagickRealType *) NULL) ||
(sin_theta == (MagickRealType *) NULL))
{
if (cos_theta != (MagickRealType *) NULL)
cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta);
if (sin_theta != (MagickRealType *) NULL)
sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta);
blur_image=DestroyImage(blur_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
offset=theta*(MagickRealType) (n-1)/2.0;
for (i=0; i < (ssize_t) n; i++)
{
cos_theta[i]=cos((double) (theta*i-offset));
sin_theta[i]=sin((double) (theta*i-offset));
}
/*
Radial blur image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
blur_view=AcquireAuthenticCacheView(blur_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,blur_image,blur_image->rows,1)
#endif
for (y=0; y < (ssize_t) blur_image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register IndexPacket
*magick_restrict blur_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view);
for (x=0; x < (ssize_t) blur_image->columns; x++)
{
MagickPixelPacket
qixel;
MagickRealType
normalize,
radius;
PixelPacket
pixel;
PointInfo
center;
register ssize_t
i;
size_t
step;
center.x=(double) x-blur_center.x;
center.y=(double) y-blur_center.y;
radius=hypot((double) center.x,center.y);
if (radius == 0)
step=1;
else
{
step=(size_t) (blur_radius/radius);
if (step == 0)
step=1;
else
if (step >= n)
step=n-1;
}
normalize=0.0;
qixel=bias;
if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse))
{
for (i=0; i < (ssize_t) n; i+=(ssize_t) step)
{
(void) GetOneCacheViewVirtualPixel(image_view,(ssize_t)
(blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5),
(ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y*
cos_theta[i]+0.5),&pixel,exception);
qixel.red+=pixel.red;
qixel.green+=pixel.green;
qixel.blue+=pixel.blue;
qixel.opacity+=pixel.opacity;
if (image->colorspace == CMYKColorspace)
{
indexes=GetCacheViewVirtualIndexQueue(image_view);
qixel.index+=(*indexes);
}
normalize+=1.0;
}
normalize=PerceptibleReciprocal(normalize);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(normalize*qixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(normalize*qixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(normalize*qixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(blur_indexes+x,ClampToQuantum(normalize*qixel.index));
}
else
{
double
alpha,
gamma;
alpha=1.0;
gamma=0.0;
for (i=0; i < (ssize_t) n; i+=(ssize_t) step)
{
(void) GetOneCacheViewVirtualPixel(image_view,(ssize_t)
(blur_center.x+center.x*cos_theta[i]-center.y*sin_theta[i]+0.5),
(ssize_t) (blur_center.y+center.x*sin_theta[i]+center.y*
cos_theta[i]+0.5),&pixel,exception);
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(&pixel));
qixel.red+=alpha*pixel.red;
qixel.green+=alpha*pixel.green;
qixel.blue+=alpha*pixel.blue;
qixel.opacity+=pixel.opacity;
if (image->colorspace == CMYKColorspace)
{
indexes=GetCacheViewVirtualIndexQueue(image_view);
qixel.index+=alpha*(*indexes);
}
gamma+=alpha;
normalize+=1.0;
}
gamma=PerceptibleReciprocal(gamma);
normalize=PerceptibleReciprocal(normalize);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*qixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*qixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*qixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(normalize*qixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*qixel.index));
}
q++;
}
if (SyncCacheViewAuthenticPixels(blur_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,BlurImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
blur_view=DestroyCacheView(blur_view);
image_view=DestroyCacheView(image_view);
cos_theta=(MagickRealType *) RelinquishMagickMemory(cos_theta);
sin_theta=(MagickRealType *) RelinquishMagickMemory(sin_theta);
if (status == MagickFalse)
blur_image=DestroyImage(blur_image);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e l e c t i v e B l u r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SelectiveBlurImage() selectively blur pixels within a contrast threshold.
% It is similar to the unsharpen mask that sharpens everything with contrast
% above a certain threshold.
%
% The format of the SelectiveBlurImage method is:
%
% Image *SelectiveBlurImage(const Image *image,const double radius,
% const double sigma,const double threshold,ExceptionInfo *exception)
% Image *SelectiveBlurImageChannel(const Image *image,
% const ChannelType channel,const double radius,const double sigma,
% const double threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o threshold: only pixels within this contrast threshold are included
% in the blur operation.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SelectiveBlurImage(const Image *image,const double radius,
const double sigma,const double threshold,ExceptionInfo *exception)
{
Image
*blur_image;
blur_image=SelectiveBlurImageChannel(image,DefaultChannels,radius,sigma,
threshold,exception);
return(blur_image);
}
MagickExport Image *SelectiveBlurImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
const double threshold,ExceptionInfo *exception)
{
#define SelectiveBlurImageTag "SelectiveBlur/Image"
CacheView
*blur_view,
*image_view,
*luminance_view;
double
*kernel;
Image
*blur_image,
*luminance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
register ssize_t
i;
size_t
width;
ssize_t
center,
j,
u,
v,
y;
/*
Initialize blur image attributes.
*/
assert(image != (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);
width=GetOptimalKernelWidth1D(radius,sigma);
kernel=(double *) MagickAssumeAligned(AcquireAlignedMemory((size_t) width,
width*sizeof(*kernel)));
if (kernel == (double *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
j=(ssize_t) (width-1)/2;
i=0;
for (v=(-j); v <= j; v++)
{
for (u=(-j); u <= j; u++)
kernel[i++]=(double) (exp(-((double) u*u+v*v)/(2.0*MagickSigma*
MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma));
}
if (image->debug != MagickFalse)
{
char
format[MaxTextExtent],
*message;
register const double
*k;
ssize_t
u,
v;
(void) LogMagickEvent(TransformEvent,GetMagickModule(),
" SelectiveBlurImage with %.20gx%.20g kernel:",(double) width,(double)
width);
message=AcquireString("");
k=kernel;
for (v=0; v < (ssize_t) width; v++)
{
*message='\0';
(void) FormatLocaleString(format,MaxTextExtent,"%.20g: ",(double) v);
(void) ConcatenateString(&message,format);
for (u=0; u < (ssize_t) width; u++)
{
(void) FormatLocaleString(format,MaxTextExtent,"%+f ",*k++);
(void) ConcatenateString(&message,format);
}
(void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message);
}
message=DestroyString(message);
}
blur_image=CloneImage(image,0,0,MagickTrue,exception);
if (blur_image == (Image *) NULL)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
return((Image *) NULL);
}
if (SetImageStorageClass(blur_image,DirectClass) == MagickFalse)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
InheritException(exception,&blur_image->exception);
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
luminance_image=CloneImage(image,0,0,MagickTrue,exception);
if (luminance_image == (Image *) NULL)
{
kernel=(double *) RelinquishAlignedMemory(kernel);
blur_image=DestroyImage(blur_image);
return((Image *) NULL);
}
status=TransformImageColorspace(luminance_image,GRAYColorspace);
if (status == MagickFalse)
{
InheritException(exception,&luminance_image->exception);
kernel=(double *) RelinquishAlignedMemory(kernel);
blur_image=DestroyImage(blur_image);
luminance_image=DestroyImage(luminance_image);
return((Image *) NULL);
}
/*
Threshold blur image.
*/
status=MagickTrue;
progress=0;
center=(ssize_t) ((image->columns+width)*((width-1)/2L)+((width-1)/2L));
GetMagickPixelPacket(image,&bias);
SetMagickPixelPacketBias(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
luminance_view=AcquireVirtualCacheView(luminance_image,exception);
blur_view=AcquireAuthenticCacheView(blur_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,blur_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
gamma;
MagickBooleanType
sync;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict l,
*magick_restrict p;
register IndexPacket
*magick_restrict blur_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) (width-1)/2L),y-(ssize_t)
((width-1)/2L),image->columns+width,width,exception);
l=GetCacheViewVirtualPixels(luminance_view,-((ssize_t) (width-1)/2L),y-
(ssize_t) ((width-1)/2L),luminance_image->columns+width,width,exception);
q=GetCacheViewAuthenticPixels(blur_view,0,y,blur_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) ||
(l == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
blur_indexes=GetCacheViewAuthenticIndexQueue(blur_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
contrast;
DoublePixelPacket
pixel;
MagickRealType
intensity;
register const double
*magick_restrict k;
register ssize_t
u;
ssize_t
j,
v;
pixel.red=bias.red;
pixel.green=bias.green;
pixel.blue=bias.blue;
pixel.opacity=bias.opacity;
pixel.index=bias.index;
k=kernel;
intensity=GetPixelIntensity(image,p+center);
gamma=0.0;
j=0;
if (((channel & OpacityChannel) == 0) || (image->matte == MagickFalse))
{
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
{
pixel.red+=(*k)*GetPixelRed(p+u+j);
pixel.green+=(*k)*GetPixelGreen(p+u+j);
pixel.blue+=(*k)*GetPixelBlue(p+u+j);
gamma+=(*k);
}
k++;
}
j+=(ssize_t) (image->columns+width);
}
if (gamma != 0.0)
{
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
}
if ((channel & OpacityChannel) != 0)
{
gamma=0.0;
j=0;
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
{
pixel.opacity+=(*k)*(p+u+j)->opacity;
gamma+=(*k);
}
k++;
}
j+=(ssize_t) (image->columns+width);
}
gamma=PerceptibleReciprocal(gamma);
SetPixelOpacity(q,ClampToQuantum(gamma*pixel.opacity));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
gamma=0.0;
j=0;
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
{
pixel.index+=(*k)*GetPixelIndex(indexes+x+u+j);
gamma+=(*k);
}
k++;
}
j+=(ssize_t) (image->columns+width);
}
gamma=PerceptibleReciprocal(gamma);
SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index));
}
}
else
{
MagickRealType
alpha;
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
{
alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(p+u+j));
pixel.red+=(*k)*alpha*GetPixelRed(p+u+j);
pixel.green+=(*k)*alpha*GetPixelGreen(p+u+j);
pixel.blue+=(*k)*alpha*GetPixelBlue(p+u+j);
pixel.opacity+=(*k)*GetPixelOpacity(p+u+j);
gamma+=(*k)*alpha;
}
k++;
}
j+=(ssize_t) (image->columns+width);
}
if (gamma != 0.0)
{
gamma=PerceptibleReciprocal(gamma);
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(gamma*pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(gamma*pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(gamma*pixel.blue));
}
if ((channel & OpacityChannel) != 0)
{
j=0;
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
pixel.opacity+=(*k)*GetPixelOpacity(p+u+j);
k++;
}
j+=(ssize_t) (image->columns+width);
}
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
gamma=0.0;
j=0;
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
contrast=GetPixelIntensity(luminance_image,l+u+j)-intensity;
if (fabs(contrast) < threshold)
{
alpha=(MagickRealType) (QuantumScale*
GetPixelAlpha(p+u+j));
pixel.index+=(*k)*alpha*GetPixelIndex(indexes+x+u+j);
gamma+=(*k);
}
k++;
}
j+=(ssize_t) (image->columns+width);
}
gamma=PerceptibleReciprocal(gamma);
SetPixelIndex(blur_indexes+x,ClampToQuantum(gamma*pixel.index));
}
}
p++;
l++;
q++;
}
sync=SyncCacheViewAuthenticPixels(blur_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SelectiveBlurImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
blur_image->type=image->type;
blur_view=DestroyCacheView(blur_view);
luminance_view=DestroyCacheView(luminance_view);
image_view=DestroyCacheView(image_view);
luminance_image=DestroyImage(luminance_image);
kernel=(double *) RelinquishAlignedMemory(kernel);
if (status == MagickFalse)
blur_image=DestroyImage(blur_image);
return(blur_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShadeImage() shines a distant light on an image to create a
% three-dimensional effect. You control the positioning of the light with
% azimuth and elevation; azimuth is measured in degrees off the x axis
% and elevation is measured in pixels above the Z axis.
%
% The format of the ShadeImage method is:
%
% Image *ShadeImage(const Image *image,const MagickBooleanType gray,
% const double azimuth,const double elevation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o gray: A value other than zero shades the intensity of each pixel.
%
% o azimuth, elevation: Define the light source direction.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShadeImage(const Image *image,const MagickBooleanType gray,
const double azimuth,const double elevation,ExceptionInfo *exception)
{
#define GetShadeIntensity(image,pixel) \
ClampPixel(GetPixelIntensity((image),(pixel)))
#define ShadeImageTag "Shade/Image"
CacheView
*image_view,
*shade_view;
Image
*linear_image,
*shade_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PrimaryInfo
light;
ssize_t
y;
/*
Initialize shaded image attributes.
*/
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);
linear_image=CloneImage(image,0,0,MagickTrue,exception);
shade_image=CloneImage(image,0,0,MagickTrue,exception);
if ((linear_image == (Image *) NULL) || (shade_image == (Image *) NULL))
{
if (linear_image != (Image *) NULL)
linear_image=DestroyImage(linear_image);
if (shade_image != (Image *) NULL)
shade_image=DestroyImage(shade_image);
return((Image *) NULL);
}
if (SetImageStorageClass(shade_image,DirectClass) == MagickFalse)
{
InheritException(exception,&shade_image->exception);
linear_image=DestroyImage(linear_image);
shade_image=DestroyImage(shade_image);
return((Image *) NULL);
}
/*
Compute the light vector.
*/
light.x=(double) QuantumRange*cos(DegreesToRadians(azimuth))*
cos(DegreesToRadians(elevation));
light.y=(double) QuantumRange*sin(DegreesToRadians(azimuth))*
cos(DegreesToRadians(elevation));
light.z=(double) QuantumRange*sin(DegreesToRadians(elevation));
/*
Shade image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(linear_image,exception);
shade_view=AcquireAuthenticCacheView(shade_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(linear_image,shade_image,linear_image->rows,1)
#endif
for (y=0; y < (ssize_t) linear_image->rows; y++)
{
MagickRealType
distance,
normal_distance,
shade;
PrimaryInfo
normal;
register const PixelPacket
*magick_restrict p,
*magick_restrict s0,
*magick_restrict s1,
*magick_restrict s2;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-1,y-1,linear_image->columns+2,3,
exception);
q=QueueCacheViewAuthenticPixels(shade_view,0,y,shade_image->columns,1,
exception);
if ((p == (PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
/*
Shade this row of pixels.
*/
normal.z=2.0*(double) QuantumRange; /* constant Z of surface normal */
for (x=0; x < (ssize_t) linear_image->columns; x++)
{
/*
Determine the surface normal and compute shading.
*/
s0=p+1;
s1=s0+image->columns+2;
s2=s1+image->columns+2;
normal.x=(double) (GetShadeIntensity(linear_image,s0-1)+
GetShadeIntensity(linear_image,s1-1)+
GetShadeIntensity(linear_image,s2-1)-
GetShadeIntensity(linear_image,s0+1)-
GetShadeIntensity(linear_image,s1+1)-
GetShadeIntensity(linear_image,s2+1));
normal.y=(double) (GetShadeIntensity(linear_image,s2-1)+
GetShadeIntensity(linear_image,s2)+
GetShadeIntensity(linear_image,s2+1)-
GetShadeIntensity(linear_image,s0-1)-
GetShadeIntensity(linear_image,s0)-
GetShadeIntensity(linear_image,s0+1));
if ((fabs(normal.x) <= MagickEpsilon) &&
(fabs(normal.y) <= MagickEpsilon))
shade=light.z;
else
{
shade=0.0;
distance=normal.x*light.x+normal.y*light.y+normal.z*light.z;
if (distance > MagickEpsilon)
{
normal_distance=normal.x*normal.x+normal.y*normal.y+normal.z*
normal.z;
if (normal_distance > (MagickEpsilon*MagickEpsilon))
shade=distance/sqrt((double) normal_distance);
}
}
if (gray != MagickFalse)
{
SetPixelRed(q,shade);
SetPixelGreen(q,shade);
SetPixelBlue(q,shade);
}
else
{
SetPixelRed(q,ClampToQuantum(QuantumScale*shade*GetPixelRed(s1)));
SetPixelGreen(q,ClampToQuantum(QuantumScale*shade*GetPixelGreen(s1)));
SetPixelBlue(q,ClampToQuantum(QuantumScale*shade*GetPixelBlue(s1)));
}
q->opacity=s1->opacity;
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(shade_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ShadeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
shade_view=DestroyCacheView(shade_view);
image_view=DestroyCacheView(image_view);
linear_image=DestroyImage(linear_image);
if (status == MagickFalse)
shade_image=DestroyImage(shade_image);
return(shade_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a r p e n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SharpenImage() sharpens the image. We convolve the image with a Gaussian
% operator of the given radius and standard deviation (sigma). For
% reasonable results, radius should be larger than sigma. Use a radius of 0
% and SharpenImage() selects a suitable radius for you.
%
% Using a separable kernel would be faster, but the negative weights cancel
% out on the corners of the kernel producing often undesirable ringing in the
% filtered result; this can be avoided by using a 2D gaussian shaped image
% sharpening kernel instead.
%
% The format of the SharpenImage method is:
%
% Image *SharpenImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
% Image *SharpenImageChannel(const Image *image,const ChannelType channel,
% const double radius,const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Laplacian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SharpenImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
Image
*sharp_image;
sharp_image=SharpenImageChannel(image,DefaultChannels,radius,sigma,exception);
return(sharp_image);
}
MagickExport Image *SharpenImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
ExceptionInfo *exception)
{
double
gamma,
normalize;
Image
*sharp_image;
KernelInfo
*kernel_info;
register ssize_t
i;
size_t
width;
ssize_t
j,
u,
v;
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);
width=GetOptimalKernelWidth2D(radius,sigma);
kernel_info=AcquireKernelInfo((const char *) NULL);
if (kernel_info == (KernelInfo *) NULL)
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(kernel_info,0,sizeof(*kernel_info));
kernel_info->width=width;
kernel_info->height=width;
kernel_info->x=(ssize_t) (width-1)/2;
kernel_info->y=(ssize_t) (width-1)/2;
kernel_info->signature=MagickCoreSignature;
kernel_info->values=(double *) MagickAssumeAligned(AcquireAlignedMemory(
kernel_info->width,kernel_info->height*sizeof(*kernel_info->values)));
if (kernel_info->values == (double *) NULL)
{
kernel_info=DestroyKernelInfo(kernel_info);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
normalize=0.0;
j=(ssize_t) (kernel_info->width-1)/2;
i=0;
for (v=(-j); v <= j; v++)
{
for (u=(-j); u <= j; u++)
{
kernel_info->values[i]=(double) (-exp(-((double) u*u+v*v)/(2.0*
MagickSigma*MagickSigma))/(2.0*MagickPI*MagickSigma*MagickSigma));
normalize+=kernel_info->values[i];
i++;
}
}
kernel_info->values[i/2]=(double) ((-2.0)*normalize);
normalize=0.0;
for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++)
normalize+=kernel_info->values[i];
gamma=PerceptibleReciprocal(normalize);
for (i=0; i < (ssize_t) (kernel_info->width*kernel_info->height); i++)
kernel_info->values[i]*=gamma;
sharp_image=MorphologyImageChannel(image,channel,ConvolveMorphology,1,
kernel_info,exception);
kernel_info=DestroyKernelInfo(kernel_info);
return(sharp_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S p r e a d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SpreadImage() is a special effects method that randomly displaces each
% pixel in a block defined by the radius parameter.
%
% The format of the SpreadImage method is:
%
% Image *SpreadImage(const Image *image,const double radius,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: Choose a random pixel in a neighborhood of this extent.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SpreadImage(const Image *image,const double radius,
ExceptionInfo *exception)
{
#define SpreadImageTag "Spread/Image"
CacheView
*image_view,
*spread_view;
Image
*spread_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
RandomInfo
**magick_restrict random_info;
size_t
width;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
/*
Initialize spread image attributes.
*/
assert(image != (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);
spread_image=CloneImage(image,0,0,MagickTrue,exception);
if (spread_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(spread_image,DirectClass) == MagickFalse)
{
InheritException(exception,&spread_image->exception);
spread_image=DestroyImage(spread_image);
return((Image *) NULL);
}
/*
Spread image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(spread_image,&bias);
width=GetOptimalKernelWidth1D(radius,0.5);
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireVirtualCacheView(image,exception);
spread_view=AcquireAuthenticCacheView(spread_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,spread_image,spread_image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) spread_image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickPixelPacket
pixel;
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(spread_view,0,y,spread_image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(spread_view);
pixel=bias;
for (x=0; x < (ssize_t) spread_image->columns; x++)
{
PointInfo
point;
point.x=GetPseudoRandomValue(random_info[id]);
point.y=GetPseudoRandomValue(random_info[id]);
status=InterpolateMagickPixelPacket(image,image_view,image->interpolate,
(double) x+width*(point.x-0.5),(double) y+width*(point.y-0.5),&pixel,
exception);
if (status == MagickFalse)
break;
SetPixelPacket(spread_image,&pixel,q,indexes+x);
q++;
}
if (SyncCacheViewAuthenticPixels(spread_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SpreadImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
spread_view=DestroyCacheView(spread_view);
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
spread_image=DestroyImage(spread_image);
return(spread_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n s h a r p M a s k I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnsharpMaskImage() sharpens one or more image channels. We convolve the
% image with a Gaussian operator of the given radius and standard deviation
% (sigma). For reasonable results, radius should be larger than sigma. Use a
% radius of 0 and UnsharpMaskImage() selects a suitable radius for you.
%
% The format of the UnsharpMaskImage method is:
%
% Image *UnsharpMaskImage(const Image *image,const double radius,
% const double sigma,const double amount,const double threshold,
% ExceptionInfo *exception)
% Image *UnsharpMaskImageChannel(const Image *image,
% const ChannelType channel,const double radius,const double sigma,
% const double gain,const double threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o radius: the radius of the Gaussian, in pixels, not counting the center
% pixel.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o gain: the percentage of the difference between the original and the
% blur image that is added back into the original.
%
% o threshold: the threshold in pixels needed to apply the diffence gain.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *UnsharpMaskImage(const Image *image,const double radius,
const double sigma,const double gain,const double threshold,
ExceptionInfo *exception)
{
Image
*sharp_image;
sharp_image=UnsharpMaskImageChannel(image,DefaultChannels,radius,sigma,gain,
threshold,exception);
return(sharp_image);
}
MagickExport Image *UnsharpMaskImageChannel(const Image *image,
const ChannelType channel,const double radius,const double sigma,
const double gain,const double threshold,ExceptionInfo *exception)
{
#define SharpenImageTag "Sharpen/Image"
CacheView
*image_view,
*unsharp_view;
Image
*unsharp_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
bias;
MagickRealType
quantum_threshold;
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);
/* This kernel appears to be broken.
#if defined(MAGICKCORE_OPENCL_SUPPORT)
unsharp_image=AccelerateUnsharpMaskImage(image,channel,radius,sigma,gain,
threshold,exception);
if (unsharp_image != (Image *) NULL)
return(unsharp_image);
#endif
*/
unsharp_image=BlurImageChannel(image,(ChannelType) (channel &~ SyncChannels),
radius,sigma,exception);
if (unsharp_image == (Image *) NULL)
return((Image *) NULL);
quantum_threshold=(MagickRealType) QuantumRange*threshold;
/*
Unsharp-mask image.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&bias);
image_view=AcquireVirtualCacheView(image,exception);
unsharp_view=AcquireAuthenticCacheView(unsharp_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,unsharp_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
DoublePixelPacket
pixel;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict unsharp_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(unsharp_view,0,y,unsharp_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
unsharp_indexes=GetCacheViewAuthenticIndexQueue(unsharp_view);
pixel.red=bias.red;
pixel.green=bias.green;
pixel.blue=bias.blue;
pixel.opacity=bias.opacity;
pixel.index=bias.index;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
pixel.red=GetPixelRed(p)-(MagickRealType) GetPixelRed(q);
if (fabs(2.0*pixel.red) < quantum_threshold)
pixel.red=(MagickRealType) GetPixelRed(p);
else
pixel.red=(MagickRealType) GetPixelRed(p)+(pixel.red*gain);
SetPixelRed(q,ClampToQuantum(pixel.red));
}
if ((channel & GreenChannel) != 0)
{
pixel.green=GetPixelGreen(p)-(MagickRealType) q->green;
if (fabs(2.0*pixel.green) < quantum_threshold)
pixel.green=(MagickRealType) GetPixelGreen(p);
else
pixel.green=(MagickRealType) GetPixelGreen(p)+(pixel.green*gain);
SetPixelGreen(q,ClampToQuantum(pixel.green));
}
if ((channel & BlueChannel) != 0)
{
pixel.blue=GetPixelBlue(p)-(MagickRealType) q->blue;
if (fabs(2.0*pixel.blue) < quantum_threshold)
pixel.blue=(MagickRealType) GetPixelBlue(p);
else
pixel.blue=(MagickRealType) GetPixelBlue(p)+(pixel.blue*gain);
SetPixelBlue(q,ClampToQuantum(pixel.blue));
}
if ((channel & OpacityChannel) != 0)
{
pixel.opacity=GetPixelOpacity(p)-(MagickRealType) q->opacity;
if (fabs(2.0*pixel.opacity) < quantum_threshold)
pixel.opacity=(MagickRealType) GetPixelOpacity(p);
else
pixel.opacity=GetPixelOpacity(p)+(pixel.opacity*gain);
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
pixel.index=GetPixelIndex(indexes+x)-(MagickRealType)
GetPixelIndex(unsharp_indexes+x);
if (fabs(2.0*pixel.index) < quantum_threshold)
pixel.index=(MagickRealType) GetPixelIndex(indexes+x);
else
pixel.index=(MagickRealType) GetPixelIndex(indexes+x)+
(pixel.index*gain);
SetPixelIndex(unsharp_indexes+x,ClampToQuantum(pixel.index));
}
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(unsharp_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SharpenImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
unsharp_image->type=image->type;
unsharp_view=DestroyCacheView(unsharp_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
unsharp_image=DestroyImage(unsharp_image);
return(unsharp_image);
}
|
GB_unop__identity_bool_fp32.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 Generated/ folder, do not edit it (auto-generated).
#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_bool_fp32
// op(A') function: GB_unop_tran__identity_bool_fp32
// C type: bool
// A type: float
// cast: bool cij = (aij != 0)
// unaryop: cij = aij
#define GB_ATYPE \
float
#define GB_CTYPE \
bool
// 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 ;
// casting
#define GB_CAST(z, aij) \
bool z = (aij != 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
bool z = (aij != 0) ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_bool_fp32
(
bool *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *GB_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)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (float), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
bool z = (aij != 0) ;
Cx [p] = z ;
}
#endif
}
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 ;
float aij = Ax [p] ;
bool z = (aij != 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_bool_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.